diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -1944,6 +1944,20 @@ let LangOpts = [CPlusPlus]; } +def RequireDesignatedInit : InheritableAttr { + let Spellings = [GNU<"require_designated_init">]; + let Subjects = SubjectList<[Type]>; + // use the following for error instead of warning + // let Subjects = SubjectList<[Type], ErrorDiag>; + let Documentation = [RequireDesignatedInitDocs]; +} + +def Required : InheritableAttr { + let Spellings = [GNU<"required">]; + let Subjects = SubjectList<[Field]>; + let Documentation = [RequiredDocs]; +} + def WorkGroupSizeHint : InheritableAttr { // Does not have a [[]] spelling because it is an OpenCL-related attribute. let Spellings = [GNU<"work_group_size_hint">]; diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -1445,6 +1445,61 @@ }]; } +def RequireDesignatedInitDocs : Documentation { + let Category = DocCatType; + let Content = [{ +This attribute can be applied to a struct definition to require that anytime a +variable of that struct's type is declared, the declaration uses `designated +initializer syntax `_. +For a struct ``Foo`` with one integer field ``x``, the following declarations +are valid and invalid when this attribute is applied to the struct's definition. + +.. code-block:: c++ + + Foo foo {.x = 1}; // valid + Foo foo {}; // valid + Foo foo {1}; // invalid + Foo foo; // invalid + +For a struct ``Foo`` with three integer fields ``x``, ``y``, and ``z``, the +following declarations are valid and invalid when this attribute is applied to +the struct's definition. + +.. code-block:: c++ + + Foo foo {.x = 1, .y = 2, .z = 3}; // valid + Foo foo {.z = 3, .x = 1, .y = 2}; // valid + Foo foo {.x = 1, .z = 3}; // valid + Foo foo {}; // valid + Foo foo {1, 2, 3}; // invalid + Foo foo {.x = 1, 2, 3}; // invalid + Foo foo; // invalid + }]; +} + +def RequiredDocs : Documentation { + let Category = DocCatType; + let Content = [{ +This attribute can be applied to a field definition within a struct or a class +to require that anytime a variable of the struct/class's type is declared, that +field must be initialized using `designated initializer syntax `_. +A field marked with this attribute may not be omitted or default-constructed. +For a struct ``Foo`` with a ``required`` integer field ``x``, the following +declarations are valid and invalid. + +.. code-block:: c++ + + struct Foo { + int __attribute__((required)) x; + }; + + Foo foo; // invalid + Foo foo {}; // invalid + Foo foo {1}; // invalid + Foo foo {.x = 1}; // valid + }]; +} + def WarnMaybeUnusedDocs : Documentation { let Category = DocCatVariable; let Heading = "maybe_unused, unused"; @@ -4194,4 +4249,4 @@ not initialized on device side. It has internal linkage and is initialized by the initializer on host side. }]; -} \ No newline at end of file +} diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -3530,6 +3530,16 @@ "'objc_designated_initializer' attribute only applies to init methods " "of interface or class extension declarations">; +def err_require_designated_init_failed : Error< + "variable declaration does not use designated initializer syntax">; +def note_declared_required_designated_init_here : Note< + "required by 'require_designated_init' attribute here">; + +def err_required_failed : Error< + "initializer for variable %0 must explicitly initialize field %1">; +def note_declared_required_here : Note< + "enforced by 'required' attribute here">; + // objc_bridge attribute diagnostics. def err_objc_attr_not_id : Error< "parameter of %0 attribute must be a single name of an Objective-C %select{class|protocol}1">; diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -52,7 +52,7 @@ Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { if (OwnedType) { - Decl *Group[2] = { OwnedType, Ptr }; + Decl *Group[2] = {OwnedType, Ptr}; return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); } @@ -62,15 +62,15 @@ namespace { class TypeNameValidatorCCC final : public CorrectionCandidateCallback { - public: - TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, - bool AllowTemplates = false, - bool AllowNonTemplates = true) - : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), - AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { - WantExpressionKeywords = false; - WantCXXNamedCasts = false; - WantRemainingKeywords = false; +public: + TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, + bool AllowTemplates = false, + bool AllowNonTemplates = true) + : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), + AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { + WantExpressionKeywords = false; + WantCXXNamedCasts = false; + WantRemainingKeywords = false; } bool ValidateCandidate(const TypoCorrection &candidate) override { @@ -109,7 +109,7 @@ return llvm::make_unique(*this); } - private: +private: bool AllowInvalidDecl; bool WantClassName; bool AllowTemplates; @@ -195,7 +195,7 @@ if (!TD) continue; if (auto *BasePrimaryTemplate = - dyn_cast_or_null(TD->getTemplatedDecl())) { + dyn_cast_or_null(TD->getTemplatedDecl())) { if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) BaseRD = BasePrimaryTemplate; else if (auto *CTD = dyn_cast(TD)) { @@ -254,8 +254,8 @@ S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; ASTContext &Context = S.Context; - auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, - cast(Context.getRecordType(RD))); + auto *NNS = NestedNameSpecifier::Create( + Context, nullptr, false, cast(Context.getRecordType(RD))); QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); CXXScopeSpec SS; @@ -278,9 +278,8 @@ /// opaque pointer (actually a QualType) corresponding to that /// type. Otherwise, returns NULL. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, - Scope *S, CXXScopeSpec *SS, - bool isClassName, bool HasTrailingDot, - ParsedType ObjectTypePtr, + Scope *S, CXXScopeSpec *SS, bool isClassName, + bool HasTrailingDot, ParsedType ObjectTypePtr, bool IsCtorOrDtorName, bool WantNontrivialTypeSourceInfo, bool IsClassTemplateDeductionContext, @@ -334,8 +333,8 @@ // FIXME: LookupNestedNameSpecifierName isn't the right kind of // lookup for class-names. - LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : - LookupOrdinaryName; + LookupNameKind Kind = + isClassName ? LookupNestedNameSpecifierName : LookupOrdinaryName; LookupResult Result(*this, &II, NameLoc, Kind); if (LookupCtx) { // Perform "qualified" name lookup into the declaration context we @@ -393,15 +392,14 @@ !(getLangOpts().CPlusPlus && NewSSPtr && isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, Template, MemberOfUnknownSpecialization))) { - ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, - isClassName, HasTrailingDot, ObjectTypePtr, - IsCtorOrDtorName, - WantNontrivialTypeSourceInfo, - IsClassTemplateDeductionContext); + ParsedType Ty = getTypeName( + *NewII, NameLoc, S, NewSSPtr, isClassName, HasTrailingDot, + ObjectTypePtr, IsCtorOrDtorName, WantNontrivialTypeSourceInfo, + IsClassTemplateDeductionContext); if (Ty) { diagnoseTypo(Correction, PDiag(diag::err_unknown_type_or_class_name_suggest) - << Result.getLookupName() << isClassName); + << Result.getLookupName() << isClassName); if (SS && NNS) SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); *CorrectedII = NewII; @@ -432,9 +430,8 @@ Res != ResEnd; ++Res) { if (isa(*Res) || isa(*Res) || (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { - if (!IIDecl || - (*Res)->getLocation().getRawEncoding() < - IIDecl->getLocation().getRawEncoding()) + if (!IIDecl || (*Res)->getLocation().getRawEncoding() < + IIDecl->getLocation().getRawEncoding()) IIDecl = *Res; } } @@ -474,7 +471,7 @@ FoundRD->isInjectedClassName() && declaresSameEntity(LookupRD, cast(FoundRD->getParent()))) Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) - << &II << /*Type*/1; + << &II << /*Type*/ 1; DiagnoseUseOfDecl(IIDecl, NameLoc); @@ -576,8 +573,8 @@ // Diagnose that this identifier was undeclared, and retry the lookup during // template instantiation. - Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II - << RD; + Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) + << &II << RD; } else { // This is not a situation that we should recover from. return ParsedType(); @@ -589,7 +586,8 @@ // to build a fake NestedNameSpecifierLoc. NestedNameSpecifierLocBuilder NNSLocBuilder; NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); - NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); + NestedNameSpecifierLoc QualifierLoc = + NNSLocBuilder.getWithLocInContext(Context); TypeLocBuilder Builder; DependentNameTypeLoc DepTL = Builder.push(T); @@ -612,11 +610,16 @@ if (R.getResultKind() == LookupResult::Found) if (const TagDecl *TD = R.getAsSingle()) { switch (TD->getTagKind()) { - case TTK_Struct: return DeclSpec::TST_struct; - case TTK_Interface: return DeclSpec::TST_interface; - case TTK_Union: return DeclSpec::TST_union; - case TTK_Class: return DeclSpec::TST_class; - case TTK_Enum: return DeclSpec::TST_enum; + case TTK_Struct: + return DeclSpec::TST_struct; + case TTK_Interface: + return DeclSpec::TST_interface; + case TTK_Union: + return DeclSpec::TST_union; + case TTK_Class: + return DeclSpec::TST_class; + case TTK_Enum: + return DeclSpec::TST_enum; } } @@ -653,10 +656,8 @@ return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); } -void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, - SourceLocation IILoc, - Scope *S, - CXXScopeSpec *SS, +void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, + Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName) { // Don't report typename errors for editor placeholders. @@ -688,7 +689,8 @@ diagnoseTypo(Corrected, PDiag(IsTemplateName ? diag::err_no_template_suggest : diag::err_unknown_typename_suggest) - << II, CanRecover); + << II, + CanRecover); } else if (DeclContext *DC = computeDeclContext(*SS, false)) { std::string CorrectedStr(Corrected.getAsString(getLangOpts())); bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && @@ -739,8 +741,8 @@ // (struct, union, enum) from Parser::ParseImplicitInt here, instead? if (!SS || (!SS->isSet() && !SS->isInvalid())) - Diag(IILoc, IsTemplateName ? diag::err_no_template - : diag::err_unknown_typename) + Diag(IILoc, + IsTemplateName ? diag::err_no_template : diag::err_unknown_typename) << II; else if (DeclContext *DC = computeDeclContext(*SS, false)) Diag(IILoc, IsTemplateName ? diag::err_no_member_template @@ -752,11 +754,11 @@ DiagID = diag::ext_typename_missing; Diag(SS->getRange().getBegin(), DiagID) - << SS->getScopeRep() << II->getName() - << SourceRange(SS->getRange().getBegin(), IILoc) - << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); - SuggestedType = ActOnTypenameType(S, SourceLocation(), - *SS, *II, IILoc).get(); + << SS->getScopeRep() << II->getName() + << SourceRange(SS->getRange().getBegin(), IILoc) + << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); + SuggestedType = + ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); } else { assert(SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"); @@ -766,8 +768,8 @@ /// Determine whether the given result set contains either a type name /// or static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { - bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && - NextToken.is(tok::less); + bool CheckTemplate = + R.getSema().getLangOpts().CPlusPlus && NextToken.is(tok::less); for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { if (isa(*I) || isa(*I)) @@ -789,36 +791,36 @@ if (TagDecl *Tag = R.getAsSingle()) { StringRef FixItTagName; switch (Tag->getTagKind()) { - case TTK_Class: - FixItTagName = "class "; - break; + case TTK_Class: + FixItTagName = "class "; + break; - case TTK_Enum: - FixItTagName = "enum "; - break; + case TTK_Enum: + FixItTagName = "enum "; + break; - case TTK_Struct: - FixItTagName = "struct "; - break; + case TTK_Struct: + FixItTagName = "struct "; + break; - case TTK_Interface: - FixItTagName = "__interface "; - break; + case TTK_Interface: + FixItTagName = "__interface "; + break; - case TTK_Union: - FixItTagName = "union "; - break; + case TTK_Union: + FixItTagName = "union "; + break; } StringRef TagName = FixItTagName.drop_back(); SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) - << Name << TagName << SemaRef.getLangOpts().CPlusPlus - << FixItHint::CreateInsertion(NameLoc, FixItTagName); + << Name << TagName << SemaRef.getLangOpts().CPlusPlus + << FixItHint::CreateInsertion(NameLoc, FixItTagName); for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); I != IEnd; ++I) SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) - << Name << TagName; + << Name << TagName; // Replace lookup results with just the tag decl. Result.clear(Sema::LookupTagName); @@ -830,8 +832,8 @@ } /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. -static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, - QualType T, SourceLocation NameLoc) { +static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, QualType T, + SourceLocation NameLoc) { ASTContext &Context = S.Context; TypeLocBuilder Builder; @@ -961,13 +963,13 @@ if (SS.isEmpty()) { diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); - } else {// FIXME: is this even reachable? Test it. + } else { // FIXME: is this even reachable? Test it. std::string CorrectedStr(Corrected.getAsString(getLangOpts())); bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && Name->getName().equals(CorrectedStr); diagnoseTypo(Corrected, PDiag(QualifiedDiag) - << Name << computeDeclContext(SS, false) - << DroppedSpecifier << SS.getRange()); + << Name << computeDeclContext(SS, false) + << DroppedSpecifier << SS.getRange()); } // Update the name, so that the caller has the new name. @@ -1078,8 +1080,8 @@ TemplateName Template; if (Result.end() - Result.begin() > 1) { IsFunctionTemplate = true; - Template = Context.getOverloadedTemplateName(Result.begin(), - Result.end()); + Template = + Context.getOverloadedTemplateName(Result.begin(), Result.end()); } else if (!Result.empty()) { auto *TD = cast(getAsTemplateNameDecl( *Result.begin(), /*AllowFunctionTemplates=*/true, @@ -1232,7 +1234,8 @@ } void Sema::PushDeclContext(Scope *S, DeclContext *DC) { - assert(getContainingDC(DC) == CurContext && + assert( + getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one."); CurContext = DC; S->setEntity(DC); @@ -1287,7 +1290,8 @@ #ifndef NDEBUG Scope *Ancestor = S->getParent(); - while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); + while (!Ancestor->getEntity()) + Ancestor = Ancestor->getParent(); assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); #endif @@ -1301,14 +1305,15 @@ // Switch back to the lexical context. The safety of this is // enforced by an assert in EnterDeclaratorContext. Scope *Ancestor = S->getParent(); - while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); + while (!Ancestor->getEntity()) + Ancestor = Ancestor->getParent(); CurContext = Ancestor->getEntity(); // We don't need to do anything with the scope, which is going to // disappear. } -void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { +void Sema::ActOnReenterFunctionContext(Scope *S, Decl *D) { // We assume that the caller has already called // ActOnReenterTemplateScope so getTemplatedDecl() works. FunctionDecl *FD = D->getAsFunction(); @@ -1317,8 +1322,9 @@ // Same implementation as PushDeclContext, but enters the context // from the lexical parent, rather than the top-level class. - assert(CurContext == FD->getLexicalParent() && - "The next DeclContext should be lexically contained in the current one."); + assert( + CurContext == FD->getLexicalParent() && + "The next DeclContext should be lexically contained in the current one."); CurContext = FD; S->setEntity(CurContext); @@ -1381,7 +1387,7 @@ // are function-local declarations. if (getLangOpts().CPlusPlus && D->isOutOfLine() && !D->getDeclContext()->getRedeclContext()->Equals( - D->getLexicalDeclContext()->getRedeclContext()) && + D->getLexicalDeclContext()->getRedeclContext()) && !D->getLexicalDeclContext()->isFunctionOrMethod()) return; @@ -1440,9 +1446,8 @@ return nullptr; } -static bool isOutOfScopePreviousDeclaration(NamedDecl *, - DeclContext*, - ASTContext&); +static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, + ASTContext &); /// Filters out lookup results that don't fall within the given scope /// as determined by isDeclInScope. @@ -1497,11 +1502,10 @@ // if a declaration of D [...] appears in the purview of a module, all // other such declarations shall appear in the purview of the same module Diag(New->getLocation(), diag::err_mismatched_owning_module) - << New - << NewIsModuleInterface - << (NewIsModuleInterface ? NewM->getFullModuleName() : "") - << OldIsModuleInterface - << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); + << New << NewIsModuleInterface + << (NewIsModuleInterface ? NewM->getFullModuleName() : "") + << OldIsModuleInterface + << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); Diag(Old->getLocation(), diag::note_previous_declaration); New->setInvalidDecl(); return true; @@ -1511,8 +1515,7 @@ } static bool isUsingDecl(NamedDecl *D) { - return isa(D) || - isa(D) || + return isa(D) || isa(D) || isa(D); } @@ -1559,7 +1562,7 @@ bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { const DeclContext *DC = D->getDeclContext(); while (!DC->isTranslationUnit()) { - if (const RecordDecl *RD = dyn_cast(DC)){ + if (const RecordDecl *RD = dyn_cast(DC)) { if (!RD->hasNameForLinkage()) return true; } @@ -1607,8 +1610,7 @@ return false; } - if (FD->doesThisDeclarationHaveABody() && - Context.DeclMustBeEmitted(FD)) + if (FD->doesThisDeclarationHaveABody() && Context.DeclMustBeEmitted(FD)) return false; } else if (const VarDecl *VD = dyn_cast(D)) { // Constants and utility variables are defined in headers with internal @@ -1739,8 +1741,7 @@ if (const ExprWithCleanups *Cleanups = dyn_cast(Init)) Init = Cleanups->getSubExpr(); - const CXXConstructExpr *Construct = - dyn_cast(Init); + const CXXConstructExpr *Construct = dyn_cast(Init); if (Construct && !Construct->isElidable()) { CXXConstructorDecl *CD = Construct->getConstructor(); if (!CD->isTrivial() && !RD->hasAttr() && @@ -1777,7 +1778,7 @@ for (auto *TmpD : D->decls()) { if (const auto *T = dyn_cast(TmpD)) DiagnoseUnusedDecl(T); - else if(const auto *R = dyn_cast(TmpD)) + else if (const auto *R = dyn_cast(TmpD)) DiagnoseUnusedNestedTypedefs(R); } } @@ -1820,13 +1821,15 @@ else Diagnose = L->getStmt() == nullptr; if (Diagnose) - S.Diag(L->getLocation(), diag::err_undeclared_label_use) <getDeclName(); + S.Diag(L->getLocation(), diag::err_undeclared_label_use) + << L->getDeclName(); } void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { S->mergeNRVOIntoParent(); - if (S->decl_empty()) return; + if (S->decl_empty()) + return; assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"); @@ -1843,7 +1846,8 @@ DiagnoseUnusedNestedTypedefs(RD); } - if (!D->getDeclName()) continue; + if (!D->getDeclName()) + continue; // If this was a forward reference to a label, verify it was defined. if (LabelDecl *LD = dyn_cast(D)) @@ -1899,7 +1903,7 @@ ObjCInterfaceDecl *Def = dyn_cast_or_null(IDecl); // This routine must always return a class definition, if any. if (Def && Def->getDefinition()) - Def = Def->getDefinition(); + Def = Def->getDefinition(); return Def; } @@ -1973,8 +1977,8 @@ /// file scope. lazily create a decl for it. ForRedeclaration is true /// if we're creating this built-in in anticipation of redeclaring the /// built-in. -NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, - Scope *S, bool ForRedeclaration, +NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, + bool ForRedeclaration, SourceLocation Loc) { LookupPredefedObjCSuperType(*this, S, II); @@ -2005,31 +2009,26 @@ DeclContext *Parent = Context.getTranslationUnitDecl(); if (getLangOpts().CPlusPlus) { - LinkageSpecDecl *CLinkageDecl = - LinkageSpecDecl::Create(Context, Parent, Loc, Loc, - LinkageSpecDecl::lang_c, false); + LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( + Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); CLinkageDecl->setImplicit(); Parent->addDecl(CLinkageDecl); Parent = CLinkageDecl; } - FunctionDecl *New = FunctionDecl::Create(Context, - Parent, - Loc, Loc, II, R, /*TInfo=*/nullptr, - SC_Extern, - false, - R->isFunctionProtoType()); + FunctionDecl *New = + FunctionDecl::Create(Context, Parent, Loc, Loc, II, R, /*TInfo=*/nullptr, + SC_Extern, false, R->isFunctionProtoType()); New->setImplicit(); // Create Decl objects for each parameter, adding them to the // FunctionDecl. if (const FunctionProtoType *FT = dyn_cast(R)) { - SmallVector Params; + SmallVector Params; for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { - ParmVarDecl *parm = - ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), - nullptr, FT->getParamType(i), /*TInfo=*/nullptr, - SC_None, nullptr); + ParmVarDecl *parm = ParmVarDecl::Create( + Context, New, SourceLocation(), SourceLocation(), nullptr, + FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); parm->setScopeInfo(0, i); Params.push_back(parm); } @@ -2082,7 +2081,7 @@ // If both declarations give a tag declaration a typedef name for linkage // purposes, then they declare the same entity. - if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && + if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/ true) && Decl->getAnonDeclWithTypedefName()) continue; } @@ -2105,20 +2104,18 @@ // Must not redefine a typedef with a variably-modified type. int Kind = isa(Old) ? 1 : 0; Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) - << Kind << NewType; + << Kind << NewType; if (Old->getLocation().isValid()) notePreviousDefinition(Old, New->getLocation()); New->setInvalidDecl(); return true; } - if (OldType != NewType && - !OldType->isDependentType() && - !NewType->isDependentType() && - !Context.hasSameType(OldType, NewType)) { + if (OldType != NewType && !OldType->isDependentType() && + !NewType->isDependentType() && !Context.hasSameType(OldType, NewType)) { int Kind = isa(Old) ? 1 : 0; Diag(New->getLocation(), diag::err_redefinition_different_typedef) - << Kind << NewType << OldType; + << Kind << NewType << OldType; if (Old->getLocation().isValid()) notePreviousDefinition(Old, New->getLocation()); New->setInvalidDecl(); @@ -2136,31 +2133,32 @@ LookupResult &OldDecls) { // If the new decl is known invalid already, don't bother doing any // merging checks. - if (New->isInvalidDecl()) return; + if (New->isInvalidDecl()) + return; // Allow multiple definitions for ObjC built-in typedefs. // FIXME: Verify the underlying types are equivalent! if (getLangOpts().ObjC) { const IdentifierInfo *TypeID = New->getIdentifier(); switch (TypeID->getLength()) { - default: break; - case 2: - { - if (!TypeID->isStr("id")) - break; - QualType T = New->getUnderlyingType(); - if (!T->isPointerType()) + default: + break; + case 2: { + if (!TypeID->isStr("id")) + break; + QualType T = New->getUnderlyingType(); + if (!T->isPointerType()) + break; + if (!T->isVoidPointerType()) { + QualType PT = T->getAs()->getPointeeType(); + if (!PT->isStructureType()) break; - if (!T->isVoidPointerType()) { - QualType PT = T->getAs()->getPointeeType(); - if (!PT->isStructureType()) - break; - } - Context.setObjCIdRedefinitionType(T); - // Install the built-in type for 'id', ignoring the current definition. - New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); - return; } + Context.setObjCIdRedefinitionType(T); + // Install the built-in type for 'id', ignoring the current definition. + New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); + return; + } case 5: if (!TypeID->isStr("Class")) break; @@ -2183,7 +2181,7 @@ TypeDecl *Old = OldDecls.getAsSingle(); if (!Old) { Diag(New->getLocation(), diag::err_redefinition_different_kind) - << New->getDeclName(); + << New->getDeclName(); NamedDecl *OldD = OldDecls.getRepresentativeDecl(); if (OldD->getLocation().isValid()) @@ -2197,7 +2195,7 @@ return New->setInvalidDecl(); if (auto *OldTD = dyn_cast(Old)) { - auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); + auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/ true); auto *NewTag = New->getAnonDeclWithTypedefName(); NamedDecl *Hidden = nullptr; if (OldTag && NewTag && @@ -2277,8 +2275,7 @@ if (!isa(Old)) return; - Diag(New->getLocation(), diag::err_redefinition) - << New->getDeclName(); + Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); notePreviousDefinition(Old, New->getLocation()); return New->setInvalidDecl(); } @@ -2299,7 +2296,7 @@ return; Diag(New->getLocation(), diag::ext_redefinition_of_typedef) - << New->getDeclName(); + << New->getDeclName(); notePreviousDefinition(Old, New->getLocation()); } @@ -2400,8 +2397,8 @@ if (OldAlign != NewAlign) { S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) - << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() - << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); + << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() + << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); } } @@ -2416,9 +2413,9 @@ // specifier, any other declaration of that object shall also // have no alignment specifier. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) - << OldAlignasAttr; + << OldAlignasAttr; S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) - << OldAlignasAttr; + << OldAlignasAttr; } bool AnyAdded = false; @@ -2468,15 +2465,15 @@ NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), AttrSpellingListIndex); else if (const auto *ImportA = dyn_cast(Attr)) - NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), - AttrSpellingListIndex); + NewAttr = + S.mergeDLLImportAttr(D, ImportA->getRange(), AttrSpellingListIndex); else if (const auto *ExportA = dyn_cast(Attr)) - NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), - AttrSpellingListIndex); + NewAttr = + S.mergeDLLExportAttr(D, ExportA->getRange(), AttrSpellingListIndex); else if (const auto *FA = dyn_cast(Attr)) - NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), - FA->getFormatIdx(), FA->getFirstArg(), - AttrSpellingListIndex); + NewAttr = + S.mergeFormatAttr(D, FA->getRange(), FA->getType(), FA->getFormatIdx(), + FA->getFirstArg(), AttrSpellingListIndex); else if (const auto *SA = dyn_cast(Attr)) NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), AttrSpellingListIndex); @@ -2625,9 +2622,9 @@ // specifier, any other declaration of that object shall also // have no alignment specifier. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) - << AA; + << AA; S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) - << AA; + << AA; NewAttributes.erase(NewAttributes.begin() + I); --E; continue; @@ -2668,7 +2665,7 @@ // This redeclaration adds an __asm__ label to a declaration that has // already been ODR-used. Diag(New->getLocation(), diag::err_late_asm_label_name) - << isa(Old) << New->getAttr()->getRange(); + << isa(Old) << New->getAttr()->getRange(); } } @@ -2702,10 +2699,9 @@ // Redeclaration adds code-seg attribute. const auto *NewCSA = New->getAttr(); - if (NewCSA && !Old->hasAttr() && - !NewCSA->isImplicit() && isa(New)) { - Diag(New->getLocation(), diag::warn_mismatched_section) - << 0 /*codeseg*/; + if (NewCSA && !Old->hasAttr() && !NewCSA->isImplicit() && + isa(New)) { + Diag(New->getLocation(), diag::warn_mismatched_section) << 0 /*codeseg*/; Diag(Old->getLocation(), diag::note_previous_declaration); } @@ -2716,13 +2712,13 @@ // Ensure that any moving of objects within the allocated map is done before // we process them. - if (!foundAny) New->setAttrs(AttrVec()); + if (!foundAny) + New->setAttrs(AttrVec()); for (auto *I : Old->specific_attrs()) { // Ignore deprecated/unavailable/availability attributes if requested. AvailabilityMergeKind LocalAMK = AMK_None; - if (isa(I) || - isa(I) || + if (isa(I) || isa(I) || isa(I)) { switch (AMK) { case AMK_None: @@ -2747,14 +2743,14 @@ if (mergeAlignedAttrs(*this, New, Old)) foundAny = true; - if (!foundAny) New->dropAttrs(); + if (!foundAny) + New->dropAttrs(); } /// mergeParamDeclAttributes - Copy attributes from the old parameter /// to the new one. static void mergeParamDeclAttributes(ParmVarDecl *newDecl, - const ParmVarDecl *oldDecl, - Sema &S) { + const ParmVarDecl *oldDecl, Sema &S) { // C++11 [dcl.attr.depend]p2: // The first declaration of a function shall specify the // carries_dependency attribute for its declarator-id if any declaration @@ -2762,15 +2758,17 @@ const CarriesDependencyAttr *CDA = newDecl->getAttr(); if (CDA && !oldDecl->hasAttr()) { S.Diag(CDA->getLocation(), - diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; + diag::err_carries_dependency_missing_on_first_decl) + << 1 /*Param*/; // Find the first declaration of the parameter. // FIXME: Should we build redeclaration chains for function parameters? const FunctionDecl *FirstFD = - cast(oldDecl->getDeclContext())->getFirstDecl(); + cast(oldDecl->getDeclContext())->getFirstDecl(); const ParmVarDecl *FirstVD = - FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); + FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); S.Diag(FirstVD->getLocation(), - diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; + diag::note_carries_dependency_missing_first_decl) + << 1 /*Param*/; } if (!oldDecl->hasAttrs()) @@ -2780,43 +2778,41 @@ // Ensure that any moving of objects within the allocated map is // done before we process them. - if (!foundAny) newDecl->setAttrs(AttrVec()); + if (!foundAny) + newDecl->setAttrs(AttrVec()); for (const auto *I : oldDecl->specific_attrs()) { if (!DeclHasAttr(newDecl, I)) { InheritableAttr *newAttr = - cast(I->clone(S.Context)); + cast(I->clone(S.Context)); newAttr->setInherited(true); newDecl->addAttr(newAttr); foundAny = true; } } - if (!foundAny) newDecl->dropAttrs(); + if (!foundAny) + newDecl->dropAttrs(); } static void mergeParamDeclTypes(ParmVarDecl *NewParam, - const ParmVarDecl *OldParam, - Sema &S) { + const ParmVarDecl *OldParam, Sema &S) { if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { if (*Oldnullability != *Newnullability) { S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) - << DiagNullabilityKind( - *Newnullability, - ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) - != 0)) - << DiagNullabilityKind( - *Oldnullability, - ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) - != 0)); + << DiagNullabilityKind(*Newnullability, + ((NewParam->getObjCDeclQualifier() & + Decl::OBJC_TQ_CSNullability) != 0)) + << DiagNullabilityKind(*Oldnullability, + ((OldParam->getObjCDeclQualifier() & + Decl::OBJC_TQ_CSNullability) != 0)); S.Diag(OldParam->getLocation(), diag::note_previous_declaration); } } else { QualType NewT = NewParam->getType(); NewT = S.Context.getAttributedType( - AttributedType::getNullabilityAttrKind(*Oldnullability), - NewT, NewT); + AttributedType::getNullabilityAttrKind(*Oldnullability), NewT, NewT); NewParam->setType(NewT); } } @@ -2878,10 +2874,9 @@ /// only extern inline functions can be redefined, and even then only in /// GNU89 mode. static bool canRedefineFunction(const FunctionDecl *FD, - const LangOptions& LangOpts) { + const LangOptions &LangOpts) { return ((FD->hasAttr() || LangOpts.GNUInline) && - !LangOpts.CPlusPlus && - FD->isInlineSpecified() && + !LangOpts.CPlusPlus && FD->isInlineSpecified() && FD->getStorageClass() == SC_Extern); } @@ -2906,13 +2901,13 @@ return false; } -template static bool isExternC(T *D) { return D->isExternC(); } +template static bool isExternC(T *D) { return D->isExternC(); } static bool isExternC(VarTemplateDecl *) { return false; } /// Check whether a redeclaration of an entity introduced by a /// using-declaration is valid, given that we know it's not an overload /// (nor a hidden tag declaration). -template +template static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New) { // C++11 [basic.scope.declarative]p4: @@ -2987,8 +2982,8 @@ if (NamedDC->Equals(SemaDC)) return; - assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || - NewD->isInvalidDecl() || OldD->isInvalidDecl()) && + assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || + OldD->isInvalidDecl()) && "unexpected context for redeclaration"); auto *LexDC = NewD->getLexicalDeclContext(); @@ -3017,8 +3012,8 @@ /// merged with. /// /// Returns true if there was an error, false otherwise. -bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, - Scope *S, bool MergeTypeWithOld) { +bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, + bool MergeTypeWithOld) { // Verify the old decl was also a function. FunctionDecl *Old = OldD->getAsFunction(); if (!Old) { @@ -3027,8 +3022,7 @@ Diag(New->getLocation(), diag::err_using_decl_friend); Diag(Shadow->getTargetDecl()->getLocation(), diag::note_using_decl_target); - Diag(Shadow->getUsingDecl()->getLocation(), - diag::note_using_decl) << 0; + Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; return true; } @@ -3038,7 +3032,7 @@ OldD = Old = cast(Shadow->getTargetDecl()); } else { Diag(New->getLocation(), diag::err_redefinition_different_kind) - << New->getDeclName(); + << New->getDeclName(); notePreviousDefinition(OldD, New->getLocation()); return true; } @@ -3066,8 +3060,7 @@ // Don't complain about specializations. They are not supposed to have // storage classes. if (!isa(New) && !isa(Old) && - New->getStorageClass() == SC_Static && - Old->hasExternalFormalLinkage() && + New->getStorageClass() == SC_Static && Old->hasExternalFormalLinkage() && !New->getTemplateSpecializationInfo() && !canRedefineFunction(Old, getLangOpts())) { if (getLangOpts().MicrosoftExt) { @@ -3095,7 +3088,7 @@ bool OldOvl = Old->hasAttr(); if (OldOvl != New->hasAttr() && !Old->isImplicit()) { Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) - << New << OldOvl; + << New << OldOvl; // Try our best to find a decl that actually has the overloadable // attribute for the note. In most cases (e.g. programs with only one @@ -3117,7 +3110,7 @@ if (DiagOld) Diag(DiagOld->getLocation(), diag::note_attribute_overloadable_prev_overload) - << OldOvl; + << OldOvl; if (OldOvl) New->addAttr(OverloadableAttr::CreateImplicit(Context)); @@ -3171,10 +3164,10 @@ // Calling conventions aren't compatible, so complain. bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); Diag(New->getLocation(), diag::err_cconv_change) - << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) - << !FirstCCExplicit - << (!FirstCCExplicit ? "" : - FunctionType::getNameForCallConv(FI.getCC())); + << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) + << !FirstCCExplicit + << (!FirstCCExplicit ? "" + : FunctionType::getNameForCallConv(FI.getCC())); // Put the note on the first decl, since it is the one that matters. Diag(First->getLocation(), diag::note_previous_declaration); @@ -3193,8 +3186,7 @@ OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { if (NewTypeInfo.getHasRegParm()) { Diag(New->getLocation(), diag::err_regparm_mismatch) - << NewType->getRegParmType() - << OldType->getRegParmType(); + << NewType->getRegParmType() << OldType->getRegParmType(); Diag(OldLocation, diag::note_previous_declaration); return true; } @@ -3220,7 +3212,7 @@ NewTypeInfo.getNoCallerSavedRegs()) { if (NewTypeInfo.getNoCallerSavedRegs()) { AnyX86NoCallerSavedRegistersAttr *Attr = - New->getAttr(); + New->getAttr(); Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; Diag(OldLocation, diag::note_previous_declaration); return true; @@ -3240,18 +3232,16 @@ // If this redeclaration makes the function inline, we may need to add it to // UndefinedButUsed. - if (!Old->isInlined() && New->isInlined() && - !New->hasAttr() && - !getLangOpts().GNUInline && - Old->isUsed(false) && - !Old->isDefined() && !New->isThisDeclarationADefinition()) - UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), - SourceLocation())); + if (!Old->isInlined() && New->isInlined() && !New->hasAttr() && + !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() && + !New->isThisDeclarationADefinition()) + UndefinedButUsed.insert( + std::make_pair(Old->getCanonicalDecl(), SourceLocation())); // If this redeclaration makes it newly gnu_inline, we don't want to warn // about it. - if (New->hasAttr() && - Old->isInlined() && !Old->hasAttr()) { + if (New->hasAttr() && Old->isInlined() && + !Old->hasAttr()) { UndefinedButUsed.erase(Old->getCanonicalDecl()); } @@ -3303,11 +3293,10 @@ else Diag(New->getLocation(), diag::err_ovl_diff_return_type) << New->getReturnTypeSourceRange(); - Diag(OldLocation, PrevDiag) << Old << Old->getType() - << Old->getReturnTypeSourceRange(); + Diag(OldLocation, PrevDiag) + << Old << Old->getType() << Old->getReturnTypeSourceRange(); return true; - } - else + } else NewQType = ResQT; } @@ -3319,13 +3308,12 @@ AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); if (OldAT && OldAT->isDeduced()) { New->setType( - SubstAutoType(New->getType(), - OldAT->isDependentType() ? Context.DependentTy - : OldAT->getDeducedType())); - NewQType = Context.getCanonicalType( - SubstAutoType(NewQType, - OldAT->isDependentType() ? Context.DependentTy - : OldAT->getDeducedType())); + SubstAutoType(New->getType(), OldAT->isDependentType() + ? Context.DependentTy + : OldAT->getDeducedType())); + NewQType = Context.getCanonicalType(SubstAutoType( + NewQType, OldAT->isDependentType() ? Context.DependentTy + : OldAT->getDeducedType())); } } @@ -3339,8 +3327,8 @@ // 2 CXXMethodDecls referring to the same function will be injected. // We don't want a redeclaration error. bool IsClassScopeExplicitSpecialization = - OldMethod->isFunctionTemplateSpecialization() && - NewMethod->isFunctionTemplateSpecialization(); + OldMethod->isFunctionTemplateSpecialization() && + NewMethod->isFunctionTemplateSpecialization(); bool isFriend = NewMethod->getFriendObjectKind(); if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && @@ -3372,29 +3360,30 @@ Diag(New->getLocation(), NewDiag); } else { Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) - << New << New->getType(); + << New << New->getType(); } Diag(OldLocation, PrevDiag) << Old << Old->getType(); return true; - // Complain if this is an explicit declaration of a special - // member that was initially declared implicitly. - // - // As an exception, it's okay to befriend such methods in order - // to permit the implicit constructor/destructor/operator calls. + // Complain if this is an explicit declaration of a special + // member that was initially declared implicitly. + // + // As an exception, it's okay to befriend such methods in order + // to permit the implicit constructor/destructor/operator calls. } else if (OldMethod->isImplicit()) { if (isFriend) { NewMethod->setImplicit(); } else { Diag(NewMethod->getLocation(), diag::err_definition_of_implicitly_declared_member) - << New << getSpecialMember(OldMethod); + << New << getSpecialMember(OldMethod); return true; } - } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { + } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && + !isFriend) { Diag(NewMethod->getLocation(), diag::err_definition_of_explicitly_defaulted_member) - << getSpecialMember(OldMethod); + << getSpecialMember(OldMethod); return true; } } @@ -3417,9 +3406,11 @@ const CarriesDependencyAttr *CDA = New->getAttr(); if (CDA && !Old->hasAttr()) { Diag(CDA->getLocation(), - diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; + diag::err_carries_dependency_missing_on_first_decl) + << 0 /*Function*/; Diag(Old->getFirstDecl()->getLocation(), - diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; + diag::note_carries_dependency_missing_first_decl) + << 0 /*Function*/; } // (C++98 8.3.5p3): @@ -3431,8 +3422,8 @@ QualType OldQTypeForComparison = OldQType; if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { auto *OldType = OldQType->castAs(); - const FunctionType *OldTypeForComparison - = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); + const FunctionType *OldTypeForComparison = + Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); OldQTypeForComparison = QualType(OldTypeForComparison, 0); assert(OldQTypeForComparison.isCanonical()); } @@ -3488,12 +3479,11 @@ New->setHasInheritedPrototype(); // Synthesize parameters with the same types. - SmallVector Params; + SmallVector Params; for (const auto &ParamType : OldProto->param_types()) { - ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), - SourceLocation(), nullptr, - ParamType, /*TInfo=*/nullptr, - SC_None, nullptr); + ParmVarDecl *Param = ParmVarDecl::Create( + Context, New, SourceLocation(), SourceLocation(), nullptr, + ParamType, /*TInfo=*/nullptr, SC_None, nullptr); Param->setScopeInfo(0, Params.size()); Param->setImplicit(); Params.push_back(Param); @@ -3516,16 +3506,15 @@ // the K&R definition becomes variadic. This is sort of an edge case, but // it's legal per the standard depending on how you read C99 6.7.5.3p15 and // C99 6.9.1p8. - if (!getLangOpts().CPlusPlus && - Old->hasPrototype() && !New->hasPrototype() && + if (!getLangOpts().CPlusPlus && Old->hasPrototype() && !New->hasPrototype() && New->getType()->getAs() && Old->getNumParams() == New->getNumParams()) { SmallVector ArgTypes; SmallVector Warnings; - const FunctionProtoType *OldProto - = Old->getType()->getAs(); - const FunctionProtoType *NewProto - = New->getType()->getAs(); + const FunctionProtoType *OldProto = + Old->getType()->getAs(); + const FunctionProtoType *NewProto = + New->getType()->getAs(); // Determine whether this is the GNU C extension. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), @@ -3541,8 +3530,8 @@ } else if (Context.typesAreCompatible(OldParm->getType(), NewParm->getType(), /*CompareUnqualified=*/true)) { - GNUCompatibleParamWarning Warn = { OldParm, NewParm, - NewProto->getParamType(Idx) }; + GNUCompatibleParamWarning Warn = {OldParm, NewParm, + NewProto->getParamType(Idx)}; Warnings.push_back(Warn); ArgTypes.push_back(NewParm->getType()); } else @@ -3553,8 +3542,7 @@ for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { Diag(Warnings[Warn].NewParm->getLocation(), diag::ext_param_promoted_not_compatible_with_prototype) - << Warnings[Warn].PromotedType - << Warnings[Warn].OldParm->getType(); + << Warnings[Warn].PromotedType << Warnings[Warn].OldParm->getType(); if (Warnings[Warn].OldParm->getLocation().isValid()) Diag(Warnings[Warn].OldParm->getLocation(), diag::note_previous_declaration); @@ -3581,7 +3569,7 @@ if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; Diag(OldLocation, diag::note_previous_builtin_declaration) - << Old << Old->getType(); + << Old << Old->getType(); // If this is a global redeclaration, just forget hereafter // about the "builtin-ness" of the function. @@ -3630,12 +3618,12 @@ // Merge attributes from the parameters. These can mismatch with K&R // declarations. if (New->getNumParams() == Old->getNumParams()) - for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { - ParmVarDecl *NewParam = New->getParamDecl(i); - ParmVarDecl *OldParam = Old->getParamDecl(i); - mergeParamDeclAttributes(NewParam, OldParam, *this); - mergeParamDeclTypes(NewParam, OldParam, *this); - } + for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { + ParmVarDecl *NewParam = New->getParamDecl(i); + ParmVarDecl *OldParam = Old->getParamDecl(i); + mergeParamDeclAttributes(NewParam, OldParam, *this); + mergeParamDeclTypes(NewParam, OldParam, *this); + } if (getLangOpts().CPlusPlus) return MergeCXXFunctionDecl(New, Old, S); @@ -3654,36 +3642,36 @@ ObjCMethodDecl *oldMethod) { // Merge the attributes, including deprecated/unavailable AvailabilityMergeKind MergeKind = - isa(oldMethod->getDeclContext()) - ? AMK_ProtocolImplementation - : isa(newMethod->getDeclContext()) ? AMK_Redeclaration - : AMK_Override; + isa(oldMethod->getDeclContext()) + ? AMK_ProtocolImplementation + : isa(newMethod->getDeclContext()) ? AMK_Redeclaration + : AMK_Override; mergeDeclAttributes(newMethod, oldMethod, MergeKind); // Merge attributes from the parameters. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), oe = oldMethod->param_end(); - for (ObjCMethodDecl::param_iterator - ni = newMethod->param_begin(), ne = newMethod->param_end(); + for (ObjCMethodDecl::param_iterator ni = newMethod->param_begin(), + ne = newMethod->param_end(); ni != ne && oi != oe; ++ni, ++oi) mergeParamDeclAttributes(*ni, *oi, *this); CheckObjCMethodOverride(newMethod, oldMethod); } -static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { +static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old) { assert(!S.Context.hasSameType(New->getType(), Old->getType())); S.Diag(New->getLocation(), New->isThisDeclarationADefinition() - ? diag::err_redefinition_different_type - : diag::err_redeclaration_different_type) - << New->getDeclName() << New->getType() << Old->getType(); + ? diag::err_redefinition_different_type + : diag::err_redeclaration_different_type) + << New->getDeclName() << New->getType() << Old->getType(); diag::kind PrevDiag; SourceLocation OldLocation; - std::tie(PrevDiag, OldLocation) - = getNoteDiagForInvalidRedeclaration(Old, New); + std::tie(PrevDiag, OldLocation) = + getNoteDiagForInvalidRedeclaration(Old, New); S.Diag(OldLocation, PrevDiag); New->setInvalidDecl(); } @@ -3746,11 +3734,9 @@ NewArray->getElementType())) MergedT = Old->getType(); } - } - else if (New->getType()->isObjCObjectPointerType() && + } else if (New->getType()->isObjCObjectPointerType() && Old->getType()->isObjCObjectPointerType()) { - MergedT = Context.mergeObjCGCQualifiers(New->getType(), - Old->getType()); + MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType()); } } else { // C 6.2.7p2: @@ -3765,7 +3751,8 @@ // equivalent. // FIXME: The C++ standard doesn't say anything about this. if ((New->getType()->isDependentType() || - Old->getType()->isDependentType()) && New->isLocalVarDecl()) { + Old->getType()->isDependentType()) && + New->isLocalVarDecl()) { // If the old type was dependent, we can't merge with it, so the new type // becomes dependent for now. We'll reproduce the original type when we // instantiate the TypeSourceInfo for the variable. @@ -3871,7 +3858,7 @@ // Here, we need only consider static data members. if (Old->isStaticDataMember() && !New->isOutOfLine()) { Diag(New->getLocation(), diag::err_duplicate_member) - << New->getIdentifier(); + << New->getIdentifier(); Diag(Old->getLocation(), diag::note_previous_declaration); New->setInvalidDecl(); } @@ -3879,8 +3866,7 @@ mergeDeclAttributes(New, Old); // Warn if an already-declared variable is made a weak_import in a subsequent // declaration - if (New->hasAttr() && - Old->getStorageClass() == SC_None && + if (New->hasAttr() && Old->getStorageClass() == SC_None && !Old->hasAttr()) { Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); notePreviousDefinition(Old, New->getLocation()); @@ -3915,8 +3901,7 @@ getNoteDiagForInvalidRedeclaration(Old, New); // [dcl.stc]p8: Check if we have a non-static decl followed by a static. - if (New->getStorageClass() == SC_Static && - !New->isStaticDataMember() && + if (New->getStorageClass() == SC_Static && !New->isStaticDataMember() && Old->hasExternalFormalLinkage()) { if (getLangOpts().MicrosoftExt) { Diag(New->getLocation(), diag::ext_static_non_static) @@ -3949,8 +3934,8 @@ } // Check if extern is followed by non-extern and vice-versa. - if (New->hasExternalStorage() && - !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { + if (New->hasExternalStorage() && !Old->hasLinkage() && + Old->isLocalVarDeclOrParm()) { Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); Diag(OldLocation, PrevDiag); return New->setInvalidDecl(); @@ -3992,15 +3977,17 @@ // UndefinedButUsed. if (!Old->isInline() && New->isInline() && Old->isUsed(false) && !Old->getDefinition() && !New->isThisDeclarationADefinition()) - UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), - SourceLocation())); + UndefinedButUsed.insert( + std::make_pair(Old->getCanonicalDecl(), SourceLocation())); if (New->getTLSKind() != Old->getTLSKind()) { if (!Old->getTLSKind()) { - Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); + Diag(New->getLocation(), diag::err_thread_non_thread) + << New->getDeclName(); Diag(OldLocation, PrevDiag); } else if (!New->getTLSKind()) { - Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); + Diag(New->getLocation(), diag::err_non_thread_thread) + << New->getDeclName(); Diag(OldLocation, PrevDiag); } else { // Do not allow redeclaration to change the variable between requiring @@ -4008,7 +3995,7 @@ // FIXME: GCC allows this, but uses the TLS keyword on the first // declaration to determine the kind. Do we need to be compatible here? Diag(New->getLocation(), diag::err_thread_thread_different_kind) - << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); + << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); Diag(OldLocation, PrevDiag); } } @@ -4112,10 +4099,8 @@ /// of the same variable. Either diagnose or fix the problem. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { if (!hasVisibleDefinition(Old) && - (New->getFormalLinkage() == InternalLinkage || - New->isInline() || - New->getDescribedVarTemplate() || - New->getNumTemplateParameterLists() || + (New->getFormalLinkage() == InternalLinkage || New->isInline() || + New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || New->getDeclContext()->isDependentContext())) { // The previous definition is hidden, and multiple definitions are // permitted (in separate TUs). Demote this to a declaration. @@ -4136,9 +4121,8 @@ /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. -Decl * -Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, - RecordDecl *&AnonRecord) { +Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, + DeclSpec &DS, RecordDecl *&AnonRecord) { return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, AnonRecord); } @@ -4246,11 +4230,11 @@ /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. It also accepts template /// parameters to cope with template friend declarations. -Decl * -Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, - MultiTemplateParamsArg TemplateParams, - bool IsExplicitInstantiation, - RecordDecl *&AnonRecord) { +Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, + DeclSpec &DS, + MultiTemplateParamsArg TemplateParams, + bool IsExplicitInstantiation, + RecordDecl *&AnonRecord) { Decl *TagD = nullptr; TagDecl *Tag = nullptr; if (DS.getTypeSpecType() == DeclSpec::TST_class || @@ -4285,7 +4269,7 @@ if (TypeQuals & DeclSpec::TQ_restrict) Diag(DS.getRestrictSpecLoc(), diag::err_typecheck_invalid_restrict_not_pointer_noarg) - << DS.getSourceRange(); + << DS.getSourceRange(); } if (DS.isInlineSpecified()) @@ -4320,7 +4304,7 @@ const CXXScopeSpec &SS = DS.getTypeSpecScope(); bool IsExplicitSpecialization = - !TemplateParams.empty() && TemplateParams.back()->size() == 0; + !TemplateParams.empty() && TemplateParams.back()->size() == 0; if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && !IsExplicitInstantiation && !IsExplicitSpecialization && !isa(Tag)) { @@ -4344,8 +4328,7 @@ if (RecordDecl *Record = dyn_cast_or_null(Tag)) { if (!Record->getDeclName() && Record->isCompleteDefinition() && DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { - if (getLangOpts().CPlusPlus || - Record->getDeclContext()->isRecord()) { + if (getLangOpts().CPlusPlus || Record->getDeclContext()->isRecord()) { // If CurContext is a DeclContext that can contain statements, // RecursiveASTVisitor won't visit the decls that // BuildAnonymousStructOrUnion() will put into CurContext. @@ -4420,11 +4403,11 @@ DeclaresAnything = false; } - if (DS.isModulePrivateSpecified() && - Tag && Tag->getDeclContext()->isFunctionOrMethod()) + if (DS.isModulePrivateSpecified() && Tag && + Tag->getDeclContext()->isFunctionOrMethod()) Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) - << Tag->getTagKind() - << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); + << Tag->getTagKind() + << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); ActOnDocumentableDecl(TagD); @@ -4465,12 +4448,12 @@ Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) Diag(DS.getStorageClassSpecLoc(), DiagID) - << DeclSpec::getSpecifierName(SCS); + << DeclSpec::getSpecifierName(SCS); } if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) Diag(DS.getThreadStorageClassSpecLoc(), DiagID) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); if (DS.getTypeQualifiers()) { if (DS.getTypeQualifiers() & DeclSpec::TQ_const) Diag(DS.getConstSpecLoc(), DiagID) << "const"; @@ -4506,15 +4489,14 @@ /// check if there's an existing declaration that can't be overloaded. /// /// \return true if this is a forbidden redeclaration -static bool CheckAnonMemberRedeclaration(Sema &SemaRef, - Scope *S, +static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, - SourceLocation NameLoc, - bool IsUnion) { + SourceLocation NameLoc, bool IsUnion) { LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, Sema::ForVisibleRedeclaration); - if (!SemaRef.LookupName(R, S)) return false; + if (!SemaRef.LookupName(R, S)) + return false; // Pick a representative declaration. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); @@ -4524,7 +4506,7 @@ return false; SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) - << IsUnion << Name; + << IsUnion << Name; SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); return true; @@ -4579,7 +4561,7 @@ assert(Chaining.size() >= 2); NamedDecl **NamedChain = - new (SemaRef.Context)NamedDecl*[Chaining.size()]; + new (SemaRef.Context) NamedDecl *[Chaining.size()]; for (unsigned i = 0; i < Chaining.size(); i++) NamedChain[i] = Chaining[i]; @@ -4595,7 +4577,8 @@ SemaRef.PushOnScopeChains(IndirectField, S); // That includes picking up the appropriate access specifier. - if (AS != AS_none) IndirectField->setAccess(AS); + if (AS != AS_none) + IndirectField->setAccess(AS); Chaining.resize(OldChainingSize); } @@ -4608,24 +4591,29 @@ /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to /// a VarDecl::StorageClass. Any error reporting is up to the caller: /// illegal input values are mapped to SC_None. -static StorageClass -StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { +static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); assert(StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."); switch (StorageClassSpec) { - case DeclSpec::SCS_unspecified: return SC_None; + case DeclSpec::SCS_unspecified: + return SC_None; case DeclSpec::SCS_extern: if (DS.isExternInLinkageSpec()) return SC_None; return SC_Extern; - case DeclSpec::SCS_static: return SC_Static; - case DeclSpec::SCS_auto: return SC_Auto; - case DeclSpec::SCS_register: return SC_Register; - case DeclSpec::SCS_private_extern: return SC_PrivateExtern; + case DeclSpec::SCS_static: + return SC_Static; + case DeclSpec::SCS_auto: + return SC_Auto; + case DeclSpec::SCS_register: + return SC_Register; + case DeclSpec::SCS_private_extern: + return SC_PrivateExtern; // Illegal SCSs map to None: error reporting is up to the caller. - case DeclSpec::SCS_mutable: // Fall through. - case DeclSpec::SCS_typedef: return SC_None; + case DeclSpec::SCS_mutable: // Fall through. + case DeclSpec::SCS_typedef: + return SC_None; } llvm_unreachable("unknown storage class specifier"); } @@ -4666,8 +4654,7 @@ /// (C++ [class.union]) and a C11 feature; anonymous structures /// are a C11 feature and GNU C++ extension. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, - AccessSpecifier AS, - RecordDecl *Record, + AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy) { DeclContext *Owner = Record->getDeclContext(); @@ -4696,7 +4683,7 @@ (OwnerScope->isNamespace() && !cast(OwnerScope)->isAnonymousNamespace()))) { Diag(Record->getLocation(), diag::err_anonymous_union_not_static) - << FixItHint::CreateInsertion(Record->getLocation(), "static "); + << FixItHint::CreateInsertion(Record->getLocation(), "static "); // Recover by adding 'static'. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), @@ -4709,12 +4696,12 @@ isa(Owner)) { Diag(DS.getStorageClassSpecLoc(), diag::err_anonymous_union_with_storage_spec) - << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); + << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); // Recover by removing the storage specifier. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, - SourceLocation(), - PrevSpec, DiagID, Context.getPrintingPolicy()); + SourceLocation(), PrevSpec, DiagID, + Context.getPrintingPolicy()); } } @@ -4722,28 +4709,27 @@ if (DS.getTypeQualifiers()) { if (DS.getTypeQualifiers() & DeclSpec::TQ_const) Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) - << Record->isUnion() << "const" - << FixItHint::CreateRemoval(DS.getConstSpecLoc()); + << Record->isUnion() << "const" + << FixItHint::CreateRemoval(DS.getConstSpecLoc()); if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified) - << Record->isUnion() << "volatile" - << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); + << Record->isUnion() << "volatile" + << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified) - << Record->isUnion() << "restrict" - << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); + << Record->isUnion() << "restrict" + << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) - Diag(DS.getAtomicSpecLoc(), - diag::ext_anonymous_struct_union_qualified) - << Record->isUnion() << "_Atomic" - << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); + Diag(DS.getAtomicSpecLoc(), diag::ext_anonymous_struct_union_qualified) + << Record->isUnion() << "_Atomic" + << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) Diag(DS.getUnalignedSpecLoc(), diag::ext_anonymous_struct_union_qualified) - << Record->isUnion() << "__unaligned" - << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); + << Record->isUnion() << "__unaligned" + << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); DS.ClearTypeQualifiers(); } @@ -4760,7 +4746,7 @@ assert(FD->getAccess() != AS_none); if (FD->getAccess() != AS_public) { Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) - << Record->isUnion() << (FD->getAccess() == AS_protected); + << Record->isUnion() << (FD->getAccess() == AS_protected); Invalid = true; } @@ -4784,11 +4770,11 @@ // Visual C++ allows type definition in anonymous struct or union. if (getLangOpts().MicrosoftExt) Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) - << Record->isUnion(); + << Record->isUnion(); else { // This is a nested type declaration. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) - << Record->isUnion(); + << Record->isUnion(); Invalid = true; } } else { @@ -4797,7 +4783,7 @@ // not part of standard C++. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_anonymous_type) - << Record->isUnion(); + << Record->isUnion(); } } else if (isa(Mem)) { // Any access specifier is fine. @@ -4818,7 +4804,7 @@ if (getLangOpts().MicrosoftExt && DK == diag::err_anonymous_record_with_type) Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) - << Record->isUnion(); + << Record->isUnion(); else { Diag(Mem->getLocation(), DK) << Record->isUnion(); Invalid = true; @@ -4837,7 +4823,7 @@ if (!Record->isUnion() && !Owner->isRecord()) { Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) - << getLangOpts().CPlusPlus; + << getLangOpts().CPlusPlus; Invalid = true; } @@ -4903,7 +4889,7 @@ // Inject the members of the anonymous struct/union into the owning // context and into the identifier resolver chain for name lookup // purposes. - SmallVector Chain; + SmallVector Chain; Chain.push_back(Anon); if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) @@ -4967,7 +4953,7 @@ // Inject the members of the anonymous struct into the current // context and into the identifier resolver chain for name lookup // purposes. - SmallVector Chain; + SmallVector Chain; Chain.push_back(Anon); RecordDecl *RecordDef = Record->getDefinition(); @@ -4989,8 +4975,7 @@ } /// Retrieves the declaration name from a parsed unqualified-id. -DeclarationNameInfo -Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { +DeclarationNameInfo Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { DeclarationNameInfo NameInfo; NameInfo.setLoc(Name.StartLocation); @@ -5017,7 +5002,7 @@ if (!Template || !isa(Template)) { Diag(Name.StartLocation, diag::err_deduction_guide_name_not_class_template) - << (int)getTemplateNameKindForDiagnostics(TN) << TN; + << (int)getTemplateNameKindForDiagnostics(TN) << TN; if (Template) Diag(Template->getLocation(), diag::note_template_decl_here); return DeclarationNameInfo(); @@ -5030,16 +5015,16 @@ case UnqualifiedIdKind::IK_OperatorFunctionId: NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( - Name.OperatorFunctionId.Operator)); - NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc - = Name.OperatorFunctionId.SymbolLocations[0]; - NameInfo.getInfo().CXXOperatorName.EndOpNameLoc - = Name.EndLocation.getRawEncoding(); + Name.OperatorFunctionId.Operator)); + NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc = + Name.OperatorFunctionId.SymbolLocations[0]; + NameInfo.getInfo().CXXOperatorName.EndOpNameLoc = + Name.EndLocation.getRawEncoding(); return NameInfo; case UnqualifiedIdKind::IK_LiteralOperatorId: - NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( - Name.Identifier)); + NameInfo.setName( + Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier)); NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); return NameInfo; @@ -5049,7 +5034,7 @@ if (Ty.isNull()) return DeclarationNameInfo(); NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( - Context.getCanonicalType(Ty))); + Context.getCanonicalType(Ty))); NameInfo.setNamedTypeInfo(TInfo); return NameInfo; } @@ -5060,7 +5045,7 @@ if (Ty.isNull()) return DeclarationNameInfo(); NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( - Context.getCanonicalType(Ty))); + Context.getCanonicalType(Ty))); NameInfo.setNamedTypeInfo(TInfo); return NameInfo; } @@ -5081,7 +5066,7 @@ // was qualified. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( - Context.getCanonicalType(CurClassType))); + Context.getCanonicalType(CurClassType))); // FIXME: should we retrieve TypeSourceInfo? NameInfo.setNamedTypeInfo(nullptr); return NameInfo; @@ -5093,7 +5078,7 @@ if (Ty.isNull()) return DeclarationNameInfo(); NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( - Context.getCanonicalType(Ty))); + Context.getCanonicalType(Ty))); NameInfo.setNamedTypeInfo(TInfo); return NameInfo; } @@ -5127,10 +5112,9 @@ /// Also sets Params to the list of indices to the parameters that differ /// between the declaration and the definition. If hasSimilarParameters /// returns true and Params is empty, then all of the parameters match. -static bool hasSimilarParameters(ASTContext &Context, - FunctionDecl *Declaration, - FunctionDecl *Definition, - SmallVectorImpl &Params) { +static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, + FunctionDecl *Definition, + SmallVectorImpl &Params) { Params.clear(); if (Declaration->param_size() != Definition->param_size()) return false; @@ -5150,7 +5134,7 @@ if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || (DeclTyName && DeclTyName == DefTyName)) Params.push_back(Idx); - else // The two parameters aren't even close + else // The two parameters aren't even close return false; } @@ -5180,7 +5164,8 @@ // Grab the type from the parser. TypeSourceInfo *TSI = nullptr; QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); - if (T.isNull() || !T->isDependentType()) break; + if (T.isNull() || !T->isDependentType()) + break; // Make sure there's a type source info. This isn't really much // of a waste; most dependent types should have type source info @@ -5190,7 +5175,8 @@ // Rebuild the type in the current instantiation. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); - if (!TSI) return true; + if (!TSI) + return true; // Store the new type back in the decl spec. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); @@ -5202,7 +5188,8 @@ case DeclSpec::TST_typeofExpr: { Expr *E = DS.getRepAsExpr(); ExprResult Result = S.RebuildExprInCurrentInstantiation(E); - if (Result.isInvalid()) return true; + if (Result.isInvalid()) + return true; DS.UpdateExprRep(Result.get()); break; } @@ -5303,7 +5290,7 @@ if (Cur->isRecord()) { Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification : diag::err_member_extra_qualification) - << Name << FixItHint::CreateRemoval(SS.getRange()); + << Name << FixItHint::CreateRemoval(SS.getRange()); SS.clear(); } else { Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; @@ -5316,28 +5303,26 @@ // CheckTemplateSpecializationScope. if (!Cur->Encloses(DC) && !IsTemplateId) { if (Cur->isRecord()) - Diag(Loc, diag::err_member_qualification) - << Name << SS.getRange(); + Diag(Loc, diag::err_member_qualification) << Name << SS.getRange(); else if (isa(DC)) Diag(Loc, diag::err_invalid_declarator_global_scope) - << Name << SS.getRange(); + << Name << SS.getRange(); else if (isa(Cur)) Diag(Loc, diag::err_invalid_declarator_in_function) - << Name << SS.getRange(); + << Name << SS.getRange(); else if (isa(Cur)) - Diag(Loc, diag::err_invalid_declarator_in_block) - << Name << SS.getRange(); + Diag(Loc, diag::err_invalid_declarator_in_block) << Name << SS.getRange(); else Diag(Loc, diag::err_invalid_declarator_scope) - << Name << cast(Cur) << cast(DC) << SS.getRange(); + << Name << cast(Cur) << cast(DC) + << SS.getRange(); return true; } if (Cur->isRecord()) { // Cannot qualify members within a class. - Diag(Loc, diag::err_member_qualification) - << Name << SS.getRange(); + Diag(Loc, diag::err_member_qualification) << Name << SS.getRange(); SS.clear(); // C++ constructors and destructors with incorrect scopes can break @@ -5359,9 +5344,9 @@ while (SpecLoc.getPrefix()) SpecLoc = SpecLoc.getPrefix(); if (dyn_cast_or_null( - SpecLoc.getNestedNameSpecifier()->getAsType())) + SpecLoc.getNestedNameSpecifier()->getAsType())) Diag(Loc, diag::err_decltype_in_declarator) - << SpecLoc.getTypeLoc().getSourceRange(); + << SpecLoc.getTypeLoc().getSourceRange(); return false; } @@ -5377,7 +5362,7 @@ if (D.isDecompositionDeclarator()) { return ActOnDecompositionDeclarator(S, D, TemplateParamLists); } else if (!Name) { - if (!D.isInvalidType()) // Reject this if we think it is valid. + if (!D.isInvalidType()) // Reject this if we think it is valid. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) << D.getDeclSpec().getSourceRange() << D.getSourceRange(); return nullptr; @@ -5407,8 +5392,8 @@ // and return early, to avoid the coming semantic disaster. Diag(D.getIdentifierLoc(), diag::err_template_qualified_declarator_no_match) - << D.getCXXScopeSpec().getScopeRep() - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getScopeRep() + << D.getCXXScopeSpec().getRange(); return nullptr; } bool IsDependentContext = DC->isDependentContext(); @@ -5419,9 +5404,8 @@ // If a class is incomplete, do not parse entities inside it. if (isa(DC) && !cast(DC)->hasDefinition()) { - Diag(D.getIdentifierLoc(), - diag::err_member_def_undefined_record) - << Name << DC << D.getCXXScopeSpec().getRange(); + Diag(D.getIdentifierLoc(), diag::err_member_def_undefined_record) + << Name << DC << D.getCXXScopeSpec().getRange(); return nullptr; } if (!D.getDeclSpec().isFriendSpecified()) { @@ -5557,8 +5541,7 @@ New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); } else if (R->isFunctionType()) { - New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, - TemplateParamLists, + New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, AddToScope); } else { New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, @@ -5599,26 +5582,26 @@ QualifierCollector Qs; const Type *Ty = Qs.strip(T); - if (const PointerType* PTy = dyn_cast(Ty)) { + if (const PointerType *PTy = dyn_cast(Ty)) { QualType Pointee = PTy->getPointeeType(); - QualType FixedType = - TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, - Oversized); - if (FixedType.isNull()) return FixedType; + QualType FixedType = TryToFixInvalidVariablyModifiedType( + Pointee, Context, SizeIsNegative, Oversized); + if (FixedType.isNull()) + return FixedType; FixedType = Context.getPointerType(FixedType); return Qs.apply(Context, FixedType); } - if (const ParenType* PTy = dyn_cast(Ty)) { + if (const ParenType *PTy = dyn_cast(Ty)) { QualType Inner = PTy->getInnerType(); - QualType FixedType = - TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, - Oversized); - if (FixedType.isNull()) return FixedType; + QualType FixedType = TryToFixInvalidVariablyModifiedType( + Inner, Context, SizeIsNegative, Oversized); + if (FixedType.isNull()) + return FixedType; FixedType = Context.getParenType(FixedType); return Qs.apply(Context, FixedType); } - const VariableArrayType* VLATy = dyn_cast(T); + const VariableArrayType *VLATy = dyn_cast(T); if (!VLATy) return QualType(); // FIXME: We should probably handle this case @@ -5639,20 +5622,18 @@ } // Check whether the array is too large to be addressed. - unsigned ActiveSizeBits - = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), - Res); + unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits( + Context, VLATy->getElementType(), Res); if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { Oversized = Res; return QualType(); } - return Context.getConstantArrayType(VLATy->getElementType(), - Res, ArrayType::Normal, 0); + return Context.getConstantArrayType(VLATy->getElementType(), Res, + ArrayType::Normal, 0); } -static void -FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { +static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { SrcTL = SrcTL.getUnqualifiedLoc(); DstTL = DstTL.getUnqualifiedLoc(); if (PointerTypeLoc SrcPTL = SrcTL.getAs()) { @@ -5683,14 +5664,11 @@ /// Helper method to turn variable array types into constant array /// types in certain situations which would otherwise be errors (for /// GCC compatibility). -static TypeSourceInfo* -TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, - ASTContext &Context, - bool &SizeIsNegative, - llvm::APSInt &Oversized) { - QualType FixedTy - = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, - SizeIsNegative, Oversized); +static TypeSourceInfo *TryToFixInvalidVariablyModifiedTypeSourceInfo( + TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, + llvm::APSInt &Oversized) { + QualType FixedTy = TryToFixInvalidVariablyModifiedType( + TInfo->getType(), Context, SizeIsNegative, Oversized); if (FixedTy.isNull()) return nullptr; TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); @@ -5703,8 +5681,7 @@ /// that it can be found later for redeclarations. We include any extern "C" /// declaration that is not visible in the translation unit here, not just /// function-scope declarations. -void -Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { +void Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { if (!getLangOpts().CPlusPlus && ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) // Don't need to track declarations in the TU in C. @@ -5726,25 +5703,22 @@ // FIXME: We should probably indicate the identifier in question to avoid // confusion for constructs like "virtual int a(), b;" if (DS.isVirtualSpecified()) - Diag(DS.getVirtualSpecLoc(), - diag::err_virtual_non_function); + Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function); if (DS.hasExplicitSpecifier()) - Diag(DS.getExplicitSpecLoc(), - diag::err_explicit_non_function); + Diag(DS.getExplicitSpecLoc(), diag::err_explicit_non_function); if (DS.isNoreturnSpecified()) - Diag(DS.getNoreturnSpecLoc(), - diag::err_noreturn_non_function); + Diag(DS.getNoreturnSpecLoc(), diag::err_noreturn_non_function); } -NamedDecl* -Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, - TypeSourceInfo *TInfo, LookupResult &Previous) { +NamedDecl *Sema::ActOnTypedefDeclarator(Scope *S, Declarator &D, + DeclContext *DC, TypeSourceInfo *TInfo, + LookupResult &Previous) { // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). if (D.getCXXScopeSpec().isSet()) { Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getRange(); D.setInvalidType(); // Pretend we didn't see the scope specifier. DC = CurContext; @@ -5772,7 +5746,8 @@ } TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); - if (!NewTD) return nullptr; + if (!NewTD) + return nullptr; // Handle attributes prior to checking for duplicates in MergeVarDecl ProcessDeclAttributes(S, NewTD, D); @@ -5785,8 +5760,8 @@ return ND; } -void -Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { +void Sema::CheckTypedefForVariablyModifiedType(Scope *S, + TypedefNameDecl *NewTD) { // C99 6.7.7p2: If a typedef name specifies a variably modified type // then it shall have block scope. // Note that variably modified types must be fixed before merging the decl so @@ -5800,9 +5775,8 @@ bool SizeIsNegative; llvm::APSInt Oversized; TypeSourceInfo *FixedTInfo = - TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, - SizeIsNegative, - Oversized); + TryToFixInvalidVariablyModifiedTypeSourceInfo( + TInfo, Context, SizeIsNegative, Oversized); if (FixedTInfo) { Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); NewTD->setTypeSourceInfo(FixedTInfo); @@ -5813,7 +5787,7 @@ Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); else if (Oversized.getBoolValue()) Diag(NewTD->getLocation(), diag::err_array_too_large) - << Oversized.toString(10); + << Oversized.toString(10); else Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); NewTD->setInvalidDecl(); @@ -5825,17 +5799,18 @@ /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which /// declares a typedef-name, either using the 'typedef' type specifier or via /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. -NamedDecl* -Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, - LookupResult &Previous, bool &Redeclaration) { +NamedDecl *Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, + TypedefNameDecl *NewTD, + LookupResult &Previous, + bool &Redeclaration) { // Find the shadowed declaration before filtering for scope. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); // Merge the decl with the existing one if appropriate. If the decl is // in an outer scope, it isn't the same thing. - FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, - /*AllowInlineNamespace*/false); + FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, + /*AllowInlineNamespace*/ false); filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); if (!Previous.empty()) { Redeclaration = true; @@ -5880,9 +5855,9 @@ /// /// \returns true if PrevDecl is an out-of-scope previous declaration /// for a new delcaration with the same name. -static bool -isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, - ASTContext &Context) { +static bool isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, + DeclContext *DC, + ASTContext &Context) { if (!PrevDecl) return false; @@ -5922,7 +5897,8 @@ static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { CXXScopeSpec &SS = D.getCXXScopeSpec(); - if (!SS.isSet()) return; + if (!SS.isSet()) + return; DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); } @@ -5944,8 +5920,7 @@ } if (kind != -1U) { - Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) - << kind; + Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) << kind; } } else if (lifetime == Qualifiers::OCL_None) { // Try to infer lifetime. @@ -5962,7 +5937,7 @@ if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && var->getTLSKind()) { Diag(var->getLocation(), diag::err_arc_thread_ownership) - << var->getType(); + << var->getType(); return true; } } @@ -6031,7 +6006,7 @@ (!AnonNSInMicrosoftMode && (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) - << &ND << Attr; + << &ND << Attr; ND.setInvalidDecl(); } } @@ -6152,12 +6127,12 @@ // Ignore static data because out-of-line definitions are diagnosed // separately. IsStaticDataMember = VD->isStaticDataMember(); - IsDefinition = VD->isThisDeclarationADefinition(S.Context) != - VarDecl::DeclarationOnly; + IsDefinition = + VD->isThisDeclarationADefinition(S.Context) != VarDecl::DeclarationOnly; } else if (const auto *FD = dyn_cast(NewDecl)) { IsInline = FD->isInlined(); - IsQualifiedFriend = FD->getQualifier() && - FD->getFriendObjectKind() == Decl::FOK_Declared; + IsQualifiedFriend = + FD->getQualifier() && FD->getFriendObjectKind() == Decl::FOK_Declared; } if (OldImportAttr && !HasNewAttr && @@ -6215,7 +6190,8 @@ // Try to avoid calling GetGVALinkageForFunction. // All cases of this require the 'inline' keyword. - if (!FD->isInlined()) return false; + if (!FD->isInlined()) + return false; // This is only possible in C++ with the gnu_inline attribute. if (S.getLangOpts().CPlusPlus && !FD->hasAttr()) @@ -6241,8 +6217,7 @@ /// visible, because its type has internal linkage. /// /// FIXME: This is a hack. -template -static bool isIncompleteDeclExternC(Sema &S, const T *D) { +template static bool isIncompleteDeclExternC(Sema &S, const T *D) { if (S.getLangOpts().CPlusPlus) { // In C++, the overloadable attribute negates the effects of extern "C". if (!D->isInExternCContext() || D->template hasAttr()) @@ -6366,11 +6341,12 @@ // OpenCL v1.2 s6.9.r: // The event type cannot be used to declare a program scope variable. // OpenCL v2.0 s6.9.q: - // The clk_event_t and reserve_id_t types cannot be declared in program scope. + // The clk_event_t and reserve_id_t types cannot be declared in program + // scope. if (NULL == S->getParent()) { if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { - Diag(D.getIdentifierLoc(), - diag::err_invalid_type_for_program_scope_var) << R; + Diag(D.getIdentifierLoc(), diag::err_invalid_type_for_program_scope_var) + << R; D.setInvalidType(); return nullptr; } @@ -6410,7 +6386,7 @@ // space qualifier or with the const qualifier. if (DC->isTranslationUnit() && !(R.getAddressSpace() == LangAS::opencl_constant || - R.isConstQualified())) { + R.isConstQualified())) { Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); D.setInvalidType(); } @@ -6452,8 +6428,8 @@ SC = SC_Extern; DeclContext *OriginalDC = DC; - bool IsLocalExternDecl = SC == SC_Extern && - adjustContextForLocalExternDecl(DC); + bool IsLocalExternDecl = + SC == SC_Extern && adjustContextForLocalExternDecl(DC); if (SCSpec == DeclSpec::SCS_mutable) { // mutable can only appear on non-static class members, so it's always @@ -6464,15 +6440,16 @@ } if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && - !D.getAsmLabel() && !getSourceManager().isInSystemMacro( - D.getDeclSpec().getStorageClassSpecLoc())) { + !D.getAsmLabel() && + !getSourceManager().isInSystemMacro( + D.getDeclSpec().getStorageClassSpecLoc())) { // In C++11, the 'register' storage class specifier is deprecated. // Suppress the warning in system macros, it's used in macros in some // popular C system headers, such as in glibc's htonl() macro. Diag(D.getDeclSpec().getStorageClassSpecLoc(), getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class : diag::warn_deprecated_register) - << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); + << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); } DiagnoseFunctionSpecifiers(D.getDeclSpec()); @@ -6514,7 +6491,8 @@ case SC_Static: Diag(D.getDeclSpec().getStorageClassSpecLoc(), diag::err_static_out_of_line) - << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); + << FixItHint::CreateRemoval( + D.getDeclSpec().getStorageClassSpecLoc()); break; case SC_Auto: case SC_Register: @@ -6526,7 +6504,8 @@ Diag(D.getDeclSpec().getStorageClassSpecLoc(), diag::err_storage_class_for_static_member) - << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); + << FixItHint::CreateRemoval( + D.getDeclSpec().getStorageClassSpecLoc()); break; case SC_PrivateExtern: llvm_unreachable("C storage class in c++!"); @@ -6538,20 +6517,21 @@ if (RD->isLocalClass()) Diag(D.getIdentifierLoc(), diag::err_static_data_member_not_allowed_in_local_class) - << Name << RD->getDeclName(); + << Name << RD->getDeclName(); // C++98 [class.union]p1: If a union contains a static data member, // the program is ill-formed. C++11 drops this restriction. if (RD->isUnion()) Diag(D.getIdentifierLoc(), getLangOpts().CPlusPlus11 - ? diag::warn_cxx98_compat_static_data_member_in_union - : diag::ext_static_data_member_in_union) << Name; + ? diag::warn_cxx98_compat_static_data_member_in_union + : diag::ext_static_data_member_in_union) + << Name; // We conservatively disallow static data members in anonymous structs. else if (!RD->getDeclName()) Diag(D.getIdentifierLoc(), diag::err_static_data_member_not_allowed_in_anon_struct) - << Name << RD->isUnion(); + << Name << RD->isUnion(); } } @@ -6573,9 +6553,9 @@ // about it, but allow the declaration of the variable. Diag(TemplateParams->getTemplateLoc(), diag::err_template_variable_noparams) - << II - << SourceRange(TemplateParams->getTemplateLoc(), - TemplateParams->getRAngleLoc()); + << II + << SourceRange(TemplateParams->getTemplateLoc(), + TemplateParams->getRAngleLoc()); TemplateParams = nullptr; } else { if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { @@ -6626,9 +6606,8 @@ // If this is supposed to be a variable template, create it as such. if (IsVariableTemplate) { - NewTemplate = - VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, - TemplateParams, NewVD); + NewTemplate = VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), + Name, TemplateParams, NewVD); NewVD->setDescribedVarTemplate(NewTemplate); } @@ -6673,8 +6652,9 @@ } else if (CurContext->isFunctionOrMethod()) { // 'inline' is not allowed on block scope variable declaration. Diag(D.getDeclSpec().getInlineSpecLoc(), - diag::err_inline_declaration_block_scope) << Name - << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); + diag::err_inline_declaration_block_scope) + << Name + << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); } else { Diag(D.getDeclSpec().getInlineSpecLoc(), getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable @@ -6707,11 +6687,10 @@ // 'extern'. if (NewVD->hasLocalStorage() && (SCSpec != DeclSpec::SCS_unspecified || - TSCS != DeclSpec::TSCS_thread_local || - !DC->isFunctionOrMethod())) + TSCS != DeclSpec::TSCS_thread_local || !DC->isFunctionOrMethod())) Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), diag::err_thread_non_global) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); else if (!Context.getTargetInfo().isTLSSupported()) { if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { // Postpone error emission until we've collected attributes required to @@ -6756,13 +6735,15 @@ D.getDeclSpec().getModulePrivateSpecLoc()); else if (IsMemberSpecialization) Diag(NewVD->getLocation(), diag::err_module_private_specialization) - << 2 - << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); + << 2 + << FixItHint::CreateRemoval( + D.getDeclSpec().getModulePrivateSpecLoc()); else if (NewVD->hasLocalStorage()) Diag(NewVD->getLocation(), diag::err_module_private_local) - << 0 << NewVD->getDeclName() - << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) - << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); + << 0 << NewVD->getDeclName() + << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) + << FixItHint::CreateRemoval( + D.getDeclSpec().getModulePrivateSpecLoc()); else { NewVD->setModulePrivate(); if (NewTemplate) @@ -6804,7 +6785,7 @@ NewVD->setInvalidDecl(); // Handle GNU asm-label extension (encoded as an attribute). - if (Expr *E = (Expr*)D.getAsmLabel()) { + if (Expr *E = (Expr *)D.getAsmLabel()) { // The parser guarantees this is a string. StringLiteral *SE = cast(E); StringRef Label = SE->getString(); @@ -6833,9 +6814,8 @@ if (!TI.isValidGCCRegisterName(Label)) Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; - else if (!TI.validateGlobalRegisterVariable(Label, - Context.getTypeSize(R), - HasSizeMismatch)) + else if (!TI.validateGlobalRegisterVariable( + Label, Context.getTypeSize(R), HasSizeMismatch)) Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; else if (HasSizeMismatch) Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; @@ -6847,18 +6827,18 @@ } } - NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), - Context, Label, 0)); + NewVD->addAttr(::new (Context) + AsmLabelAttr(SE->getStrTokenLoc(0), Context, Label, 0)); } else if (!ExtnameUndeclaredIdentifiers.empty()) { - llvm::DenseMap::iterator I = - ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); + llvm::DenseMap::iterator I = + ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); if (I != ExtnameUndeclaredIdentifiers.end()) { if (isDeclExternC(NewVD)) { NewVD->addAttr(I->second); ExtnameUndeclaredIdentifiers.erase(I); } else Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) - << /*Variable*/1 << NewVD; + << /*Variable*/ 1 << NewVD; } } @@ -6872,13 +6852,13 @@ // declaration has linkage). FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), D.getCXXScopeSpec().isNotEmpty() || - IsMemberSpecialization || - IsVariableTemplateSpecialization); + IsMemberSpecialization || + IsVariableTemplateSpecialization); // Check whether the previous declaration is in the same block scope. This // affects whether we merge types with it, per C++11 [dcl.array]p3. - if (getLangOpts().CPlusPlus && - NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) + if (getLangOpts().CPlusPlus && NewVD->isLocalVarDecl() && + NewVD->hasExternalStorage()) NewVD->setPreviousDeclInSameBlockScope( Previous.isSingleResult() && !Previous.isShadowed() && isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); @@ -6899,15 +6879,15 @@ // The user tried to define a non-static data member // out-of-line (C++ [dcl.meaning]p1). Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getRange(); Previous.clear(); NewVD->setInvalidDecl(); } } else if (D.getCXXScopeSpec().isSet()) { // No previous declaration in the qualifying scope. Diag(D.getIdentifierLoc(), diag::err_no_member) - << Name << computeDeclContext(D.getCXXScopeSpec(), true) - << D.getCXXScopeSpec().getRange(); + << Name << computeDeclContext(D.getCXXScopeSpec(), true) + << D.getCXXScopeSpec().getRange(); NewVD->setInvalidDecl(); } @@ -7172,7 +7152,6 @@ // shadowing context, but that's just a false negative. } - DeclarationName Name = R.getLookupName(); // Emit warning and note. @@ -7244,9 +7223,9 @@ /// Check for conflict between this global or extern "C" declaration and /// previous global or extern "C" declarations. This is only used in C++. -template -static bool checkGlobalOrExternCConflict( - Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { +template +static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, + LookupResult &Previous) { assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); @@ -7313,9 +7292,8 @@ Prev = cast(Prev)->getFirstDecl(); S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) - << IsGlobal << ND; - S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) - << IsGlobal; + << IsGlobal << ND; + S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) << IsGlobal; return false; } @@ -7327,7 +7305,7 @@ /// with the same name that appear in different scopes refer to the same /// [entity]. An entity with C language linkage shall not be declared with /// the same name as an entity in global scope. -template +template static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous) { if (!S.getLangOpts().CPlusPlus) { @@ -7347,13 +7325,13 @@ // A declaration in the translation unit can conflict with an extern "C" // declaration. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) - return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); + return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/ true, Previous); // An extern "C" declaration can conflict with a declaration in the // translation unit or can be a redeclaration of an extern "C" declaration // in another scope. - if (isIncompleteDeclExternC(S,ND)) - return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); + if (isIncompleteDeclExternC(S, ND)) + return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/ false, Previous); // Neither global nor extern "C": nothing to do. return false; @@ -7375,7 +7353,7 @@ if (T->isObjCObjectType()) { Diag(NewVD->getLocation(), diag::err_statically_allocated_object) - << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); + << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); T = Context.getObjCObjectPointerType(T); NewVD->setType(T); } @@ -7493,8 +7471,8 @@ } } - if (NewVD->hasLocalStorage() && T.isObjCGCWeak() - && !NewVD->hasAttr()) { + if (NewVD->hasLocalStorage() && T.isObjCGCWeak() && + !NewVD->hasAttr()) { if (getLangOpts().getGC() != LangOptions::NonGC) Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); else { @@ -7504,8 +7482,7 @@ } bool isVM = T->isVariablyModifiedType(); - if (isVM || NewVD->hasAttr() || - NewVD->hasAttr()) + if (isVM || NewVD->hasAttr() || NewVD->hasAttr()) setFunctionHasBranchProtectedScope(); if ((isVM && NewVD->hasLinkage()) || @@ -7515,7 +7492,7 @@ TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); QualType FixedT; - if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) + if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) FixedT = FixedTInfo->getType(); else if (FixedTInfo) { // Type and type-as-written are canonically different. We need to fix up @@ -7531,13 +7508,13 @@ if (NewVD->isFileVarDecl()) Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) - << SizeRange; + << SizeRange; else if (NewVD->isStaticLocal()) Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) - << SizeRange; + << SizeRange; else Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) - << SizeRange; + << SizeRange; NewVD->setInvalidDecl(); return; } @@ -7560,8 +7537,7 @@ // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names // of objects and functions. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { - Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) - << T; + Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) << T; NewVD->setInvalidDecl(); return; } @@ -7664,15 +7640,14 @@ /// \param DiagID the primary error to report. /// \param MD the overriding method. /// \param OEK which overrides to include as notes. -static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, +static void ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, OverrideErrorKind OEK = OEK_All) { S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); for (const CXXMethodDecl *O : MD->overridden_methods()) { // This check (& the OEK parameter) could be replaced by a predicate, but // without lambdas that would be overkill. This is still nicer than writing // out the diag loop 3 times. - if ((OEK == OEK_All) || - (OEK == OEK_NonDeleted && !O->isDeleted()) || + if ((OEK == OEK_All) || (OEK == OEK_NonDeleted && !O->isDeleted()) || (OEK == OEK_Deleted && O->isDeleted())) S.Diag(O->getLocation(), diag::note_overridden_virtual_function); } @@ -7716,14 +7691,14 @@ } namespace { - // Struct for holding all of the extra arguments needed by - // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. - struct ActOnFDArgs { - Scope *S; - Declarator &D; - MultiTemplateParamsArg TemplateParamLists; - bool AddToScope; - }; +// Struct for holding all of the extra arguments needed by +// DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. +struct ActOnFDArgs { + Scope *S; + Declarator &D; + MultiTemplateParamsArg TemplateParamLists; + bool AddToScope; +}; } // end anonymous namespace namespace { @@ -7731,7 +7706,7 @@ // Callback to only accept typo corrections that have a non-zero edit distance. // Also only accept corrections that have the same parent decl. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { - public: +public: DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, CXXRecordDecl *Parent) : Context(Context), OriginalFD(TypoFD), @@ -7743,7 +7718,7 @@ SmallVector MismatchedParams; for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), - CDeclEnd = candidate.end(); + CDeclEnd = candidate.end(); CDecl != CDeclEnd; ++CDecl) { FunctionDecl *FD = dyn_cast(*CDecl); @@ -7766,7 +7741,7 @@ return llvm::make_unique(*this); } - private: +private: ASTContext &Context; FunctionDecl *OriginalFD; CXXRecordDecl *ExpectedParent; @@ -7787,19 +7762,21 @@ /// /// Returns a NamedDecl iff typo correction was performed and substituting in /// the new declaration name does not cause new errors. -static NamedDecl *DiagnoseInvalidRedeclaration( - Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, - ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { +static NamedDecl *DiagnoseInvalidRedeclaration(Sema &SemaRef, + LookupResult &Previous, + FunctionDecl *NewFD, + ActOnFDArgs &ExtraArgs, + bool IsLocalFriend, Scope *S) { DeclarationName Name = NewFD->getDeclName(); DeclContext *NewDC = NewFD->getDeclContext(); SmallVector MismatchedParams; SmallVector, 1> NearMatches; TypoCorrection Correction; bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); - unsigned DiagMsg = - IsLocalFriend ? diag::err_no_matching_local_friend : - NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : - diag::err_member_decl_does_not_match; + unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend + : NewFD->getFriendObjectKind() + ? diag::err_qualified_friend_no_match + : diag::err_member_decl_does_not_match; LookupResult Prev(SemaRef, Name, NewFD->getLocation(), IsLocalFriend ? Sema::LookupLocalFriendName : Sema::LookupOrdinaryName, @@ -7828,7 +7805,7 @@ NearMatches.push_back(std::make_pair(FD, ParamNum)); } } - // If the qualified name lookup yielded nothing, try typo correction + // If the qualified name lookup yielded nothing, try typo correction } else if ((Correction = SemaRef.CorrectTypo( Prev.getLookupNameInfo(), Prev.getLookupKind(), S, &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, @@ -7839,7 +7816,7 @@ Previous.clear(); Previous.setLookupName(Correction.getCorrection()); for (TypoCorrection::decl_iterator CDecl = Correction.begin(), - CDeclEnd = Correction.end(); + CDeclEnd = Correction.end(); CDecl != CDeclEnd; ++CDecl) { FunctionDecl *FD = dyn_cast(*CDecl); if (FD && !FD->hasBody() && @@ -7882,9 +7859,9 @@ SemaRef.diagnoseTypo( Correction, SemaRef.PDiag(IsLocalFriend - ? diag::err_no_matching_local_friend_suggest - : diag::err_member_decl_does_not_match_suggest) - << Name << NewDC << IsDefinition); + ? diag::err_no_matching_local_friend_suggest + : diag::err_member_decl_does_not_match_suggest) + << Name << NewDC << IsDefinition); return Result; } @@ -7903,8 +7880,9 @@ if (CXXMethodDecl *NewMD = dyn_cast(NewFD)) NewFDisConst = NewMD->isConst(); - for (SmallVectorImpl >::iterator - NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); + for (SmallVectorImpl>::iterator + NearMatch = NearMatches.begin(), + NearMatchEnd = NearMatches.end(); NearMatch != NearMatchEnd; ++NearMatch) { FunctionDecl *FD = NearMatch->first; CXXMethodDecl *MD = dyn_cast(FD); @@ -7913,27 +7891,29 @@ // FIXME: These notes are poorly worded for the local friend case. if (unsigned Idx = NearMatch->second) { - ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); + ParmVarDecl *FDParam = FD->getParamDecl(Idx - 1); SourceLocation Loc = FDParam->getTypeSpecStartLoc(); - if (Loc.isInvalid()) Loc = FD->getLocation(); + if (Loc.isInvalid()) + Loc = FD->getLocation(); SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match : diag::note_local_decl_close_param_match) - << Idx << FDParam->getType() - << NewFD->getParamDecl(Idx - 1)->getType(); + << Idx << FDParam->getType() + << NewFD->getParamDecl(Idx - 1)->getType(); } else if (FDisConst != NewFDisConst) { SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) << NewFDisConst << FD->getSourceRange().getEnd(); } else - SemaRef.Diag(FD->getLocation(), - IsMember ? diag::note_member_def_close_match - : diag::note_local_decl_close_match); + SemaRef.Diag(FD->getLocation(), IsMember + ? diag::note_member_def_close_match + : diag::note_local_decl_close_match); } return nullptr; } static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { switch (D.getDeclSpec().getStorageClassSpec()) { - default: llvm_unreachable("Unknown storage class!"); + default: + llvm_unreachable("Unknown storage class!"); case DeclSpec::SCS_auto: case DeclSpec::SCS_register: case DeclSpec::SCS_mutable: @@ -7942,7 +7922,8 @@ D.getMutableDeclSpec().ClearStorageClassSpecs(); D.setInvalidType(); break; - case DeclSpec::SCS_unspecified: break; + case DeclSpec::SCS_unspecified: + break; case DeclSpec::SCS_extern: if (D.getDeclSpec().isExternInLinkageSpec()) return SC_None; @@ -7960,14 +7941,15 @@ } else return SC_Static; } - case DeclSpec::SCS_private_extern: return SC_PrivateExtern; + case DeclSpec::SCS_private_extern: + return SC_PrivateExtern; } // No explicit storage class has already been returned return SC_None; } -static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, +static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, @@ -7986,8 +7968,8 @@ // attributed reference to a type name (which eventually refers to a // function type). bool HasPrototype = - (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || - (!R->getAsAdjusted() && R->isFunctionProtoType()); + (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || + (!R->getAsAdjusted() && R->isFunctionProtoType()); NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, isInline, HasPrototype, @@ -8053,8 +8035,7 @@ } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { if (!DC->isRecord()) { - SemaRef.Diag(D.getIdentifierLoc(), - diag::err_conv_function_not_member); + SemaRef.Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member); return nullptr; } @@ -8076,10 +8057,11 @@ // (The parser checks for a return type and makes the declarator a // constructor if it has no return type). if (Name.getAsIdentifierInfo() && - Name.getAsIdentifierInfo() == cast(DC)->getIdentifier()){ + Name.getAsIdentifierInfo() == + cast(DC)->getIdentifier()) { SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) - << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) - << SourceRange(D.getIdentifierLoc()); + << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) + << SourceRange(D.getIdentifierLoc()); return nullptr; } @@ -8183,10 +8165,8 @@ } static void checkIsValidOpenCLKernelParameter( - Sema &S, - Declarator &D, - ParmVarDecl *Param, - llvm::SmallPtrSetImpl &ValidTypes) { + Sema &S, Declarator &D, ParmVarDecl *Param, + llvm::SmallPtrSetImpl &ValidTypes) { QualType PT = Param->getType(); // Cache the valid types we encounter to avoid rechecking structs that are @@ -8323,8 +8303,7 @@ ParamType == InvalidAddrSpacePtrKernelParam) { S.Diag(Param->getLocation(), diag::err_record_with_pointers_kernel_param) - << PT->isUnionType() - << PT; + << PT->isUnionType() << PT; } else { S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; } @@ -8340,12 +8319,11 @@ I != E; ++I) { const FieldDecl *OuterField = *I; S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) - << OuterField->getType(); + << OuterField->getType(); } S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) - << QT->isPointerType() - << QT; + << QT->isPointerType() << QT; D.setInvalidType(); return; } @@ -8366,15 +8344,14 @@ /// nothing. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { while (S->isClassScope() || - (LangOpts.CPlusPlus && - S->isFunctionPrototypeScope()) || + (LangOpts.CPlusPlus && S->isFunctionPrototypeScope()) || ((S->getFlags() & Scope::DeclScope) == 0) || (S->getEntity() && S->getEntity()->isTransparentContext())) S = S->getParent(); return S; } -NamedDecl* +NamedDecl * Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, @@ -8391,7 +8368,7 @@ if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), diag::err_invalid_thread) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); if (D.isFirstDeclarationOfMember()) adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), @@ -8411,9 +8388,10 @@ DeclContext *OriginalDC = DC; bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); - FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, - isVirtualOkay); - if (!NewFD) return nullptr; + FunctionDecl *NewFD = + CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, isVirtualOkay); + if (!NewFD) + return nullptr; if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) NewFD->setTopLevelDeclInObjCContainer(); @@ -8443,7 +8421,7 @@ // or an overloaded operator, then set the pure flag (isVirtual will already // return true). if (const CXXRecordDecl *Parent = - dyn_cast(NewFD->getDeclContext())) { + dyn_cast(NewFD->getDeclContext())) { if (Parent->isInterface() && cast(NewFD)->isUserProvided()) NewFD->setPure(true); @@ -8493,10 +8471,8 @@ Invalid = true; } - FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, - NewFD->getLocation(), - Name, TemplateParams, - NewFD); + FunctionTemplate = FunctionTemplateDecl::Create( + Context, DC, NewFD->getLocation(), Name, TemplateParams, NewFD); FunctionTemplate->setLexicalDeclContext(CurContext); NewFD->setDescribedFunctionTemplate(FunctionTemplate); @@ -8529,9 +8505,8 @@ } Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) - << Name << RemoveRange - << FixItHint::CreateRemoval(RemoveRange) - << FixItHint::CreateInsertion(InsertLoc, "<>"); + << Name << RemoveRange << FixItHint::CreateRemoval(RemoveRange) + << FixItHint::CreateInsertion(InsertLoc, "<>"); } } } else { @@ -8561,13 +8536,13 @@ // 'virtual' was specified outside of the class. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) - << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); + << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); } else if (NewFD->getDescribedFunctionTemplate()) { // C++ [temp.mem]p3: // A member function template shall not be virtual. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_member_function_template) - << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); + << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); } else { // Okay: Add virtual to the method. NewFD->setVirtualAsWritten(true); @@ -8603,8 +8578,9 @@ if (CurContext->isFunctionOrMethod()) { // 'inline' is not allowed on block scope function declaration. Diag(D.getDeclSpec().getInlineSpecLoc(), - diag::err_inline_declaration_block_scope) << Name - << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); + diag::err_inline_declaration_block_scope) + << Name + << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); } } @@ -8645,11 +8621,10 @@ // If __module_private__ was specified, mark the function accordingly. if (D.getDeclSpec().isModulePrivateSpecified()) { if (isFunctionTemplateSpecialization) { - SourceLocation ModulePrivateLoc - = D.getDeclSpec().getModulePrivateSpecLoc(); + SourceLocation ModulePrivateLoc = + D.getDeclSpec().getModulePrivateSpecLoc(); Diag(ModulePrivateLoc, diag::err_module_private_specialization) - << 0 - << FixItHint::CreateRemoval(ModulePrivateLoc); + << 0 << FixItHint::CreateRemoval(ModulePrivateLoc); } else { NewFD->setModulePrivate(); if (FunctionTemplate) @@ -8670,17 +8645,17 @@ // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function // definition kind to FDK_Definition. switch (D.getFunctionDefinitionKind()) { - case FDK_Declaration: - case FDK_Definition: - break; + case FDK_Declaration: + case FDK_Definition: + break; - case FDK_Defaulted: - NewFD->setDefaulted(); - break; + case FDK_Defaulted: + NewFD->setDefaulted(); + break; - case FDK_Deleted: - NewFD->setDeletedAsWritten(); - break; + case FDK_Deleted: + NewFD->setDeletedAsWritten(); + break; } if (isa(NewFD) && DC == CurContext && @@ -8707,9 +8682,10 @@ Diag(D.getDeclSpec().getStorageClassSpecLoc(), ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && cast(DC)->getDescribedClassTemplate()) || - (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) - ? diag::ext_static_out_of_line : diag::err_static_out_of_line) - << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); + (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) + ? diag::ext_static_out_of_line + : diag::err_static_out_of_line) + << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); } // C++11 [except.spec]p15: @@ -8727,31 +8703,31 @@ // Filter out previous declarations that don't match the scope. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), D.getCXXScopeSpec().isNotEmpty() || - isMemberSpecialization || - isFunctionTemplateSpecialization); + isMemberSpecialization || + isFunctionTemplateSpecialization); // Handle GNU asm-label extension (encoded as an attribute). - if (Expr *E = (Expr*) D.getAsmLabel()) { + if (Expr *E = (Expr *)D.getAsmLabel()) { // The parser guarantees this is a string. StringLiteral *SE = cast(E); NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, SE->getString(), 0)); } else if (!ExtnameUndeclaredIdentifiers.empty()) { - llvm::DenseMap::iterator I = - ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); + llvm::DenseMap::iterator I = + ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); if (I != ExtnameUndeclaredIdentifiers.end()) { if (isDeclExternC(NewFD)) { NewFD->addAttr(I->second); ExtnameUndeclaredIdentifiers.erase(I); } else Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) - << /*Variable*/0 << NewFD; + << /*Variable*/ 0 << NewFD; } } // Copy the parameter declarations from the declarator D to the function // declaration NewFD, if they are available. First scavenge them into Params. - SmallVector Params; + SmallVector Params; unsigned FTIIdx; if (D.isFunctionDeclarator(FTIIdx)) { DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; @@ -8833,9 +8809,8 @@ NewFD->setParams(Params); if (D.getDeclSpec().isNoreturnSpecified()) - NewFD->addAttr( - ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), - Context, 0)); + NewFD->addAttr(::new (Context) C11NoReturnAttr( + D.getDeclSpec().getNoreturnSpecLoc(), Context, 0)); // Functions returning a variably modified type violate C99 6.7.5.2p2 // because all functions have linkage. @@ -8848,9 +8823,9 @@ // Apply an implicit SectionAttr if '#pragma clang section text' is active if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && !NewFD->hasAttr()) { - NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, - PragmaClangTextSection.SectionName, - PragmaClangTextSection.PragmaLocation)); + NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( + Context, PragmaClangTextSection.SectionName, + PragmaClangTextSection.PragmaLocation)); } // Apply an implicit SectionAttr if #pragma code_seg is active. @@ -8870,8 +8845,8 @@ // Apply an implicit CodeSegAttr from class declspec or // apply an implicit SectionAttr from #pragma code_seg if active. if (!NewFD->hasAttr()) { - if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, - D.isFunctionDefinition())) { + if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction( + NewFD, D.isFunctionDefinition())) { NewFD->addAttr(SAttr); } } @@ -8899,8 +8874,8 @@ CheckMSVCRTEntryPoint(NewFD); if (!NewFD->isInvalidDecl()) - D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, - isMemberSpecialization)); + D.setRedeclaration( + CheckFunctionDeclaration(S, NewFD, Previous, isMemberSpecialization)); else if (!Previous.empty()) // Recover gracefully from an invalid redeclaration. D.setRedeclaration(true); @@ -8936,7 +8911,7 @@ !NewFD->hasAttr()) Diag(D.getDeclSpec().getInlineSpecLoc(), diag::ext_operator_new_delete_declared_inline) - << NewFD->getDeclName(); + << NewFD->getDeclName(); // If the declarator is a template-id, translate the parser's template // argument list into our AST format. @@ -8946,8 +8921,7 @@ TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), TemplateId->NumArgs); - translateTemplateArguments(TemplateArgsPtr, - TemplateArgs); + translateTemplateArguments(TemplateArgsPtr, TemplateArgs); HasExplicitTemplateArgs = true; @@ -8956,7 +8930,7 @@ } else if (FunctionTemplate) { // Function template with explicit template arguments. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) - << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); + << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); HasExplicitTemplateArgs = false; } else { @@ -8995,16 +8969,15 @@ if (isFunctionTemplateSpecialization && isFriend && (NewFD->getType()->isDependentType() || DC->isDependentContext() || TemplateSpecializationType::anyDependentTemplateArguments( - TemplateArgs, - InstantiationDependent))) { + TemplateArgs, InstantiationDependent))) { assert(HasExplicitTemplateArgs && "friend function specialization without template args"); if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, Previous)) NewFD->setInvalidDecl(); } else if (isFunctionTemplateSpecialization) { - if (CurContext->isDependentContext() && CurContext->isRecord() - && !isFriend) { + if (CurContext->isDependentContext() && CurContext->isRecord() && + !isFriend) { isDependentClassScopeExplicitSpecialization = true; } else if (!NewFD->isInvalidDecl() && CheckFunctionTemplateSpecialization( @@ -9021,19 +8994,19 @@ if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) Diag(NewFD->getLocation(), diag::err_explicit_specialization_inconsistent_storage_class) - << SC - << FixItHint::CreateRemoval( - D.getDeclSpec().getStorageClassSpecLoc()); + << SC + << FixItHint::CreateRemoval( + D.getDeclSpec().getStorageClassSpecLoc()); else Diag(NewFD->getLocation(), diag::ext_explicit_specialization_storage_class) - << FixItHint::CreateRemoval( - D.getDeclSpec().getStorageClassSpecLoc()); + << FixItHint::CreateRemoval( + D.getDeclSpec().getStorageClassSpecLoc()); } } else if (isMemberSpecialization && isa(NewFD)) { if (CheckMemberSpecialization(NewFD, Previous)) - NewFD->setInvalidDecl(); + NewFD->setInvalidDecl(); } // Perform semantic checking on the function declaration. @@ -9056,9 +9029,8 @@ Previous.getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded"); - NamedDecl *PrincipalDecl = (FunctionTemplate - ? cast(FunctionTemplate) - : NewFD); + NamedDecl *PrincipalDecl = + (FunctionTemplate ? cast(FunctionTemplate) : NewFD); if (isFriend && NewFD->getPreviousDecl()) { AccessSpecifier Access = AS_public; @@ -9066,7 +9038,8 @@ Access = NewFD->getPreviousDecl()->getAccess(); NewFD->setAccess(Access); - if (FunctionTemplate) FunctionTemplate->setAccess(Access); + if (FunctionTemplate) + FunctionTemplate->setAccess(Access); } if (NewFD->isOverloadedOperator() && !DC->isRecord() && @@ -9076,27 +9049,23 @@ // If we have a function template, check the template parameter // list. This will check and merge default template arguments. if (FunctionTemplate) { - FunctionTemplateDecl *PrevTemplate = - FunctionTemplate->getPreviousDecl(); - CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), - PrevTemplate ? PrevTemplate->getTemplateParameters() - : nullptr, - D.getDeclSpec().isFriendSpecified() - ? (D.isFunctionDefinition() - ? TPC_FriendFunctionTemplateDefinition - : TPC_FriendFunctionTemplate) - : (D.getCXXScopeSpec().isSet() && - DC && DC->isRecord() && - DC->isDependentContext()) - ? TPC_ClassTemplateMember - : TPC_FunctionTemplate); + FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDecl(); + CheckTemplateParameterList( + FunctionTemplate->getTemplateParameters(), + PrevTemplate ? PrevTemplate->getTemplateParameters() : nullptr, + D.getDeclSpec().isFriendSpecified() + ? (D.isFunctionDefinition() ? TPC_FriendFunctionTemplateDefinition + : TPC_FriendFunctionTemplate) + : (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && + DC->isDependentContext()) + ? TPC_ClassTemplateMember + : TPC_FunctionTemplate); } if (NewFD->isInvalidDecl()) { // Ignore all the rest of this. } else if (!D.isRedeclaration()) { - struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, - AddToScope }; + struct ActOnFDArgs ExtraArgs = {S, D, TemplateParamLists, AddToScope}; // Fake up an access specifier if it's supposed to be a class member. if (isa(NewFD->getDeclContext())) NewFD->setAccess(AS_public); @@ -9152,10 +9121,9 @@ return Result; } } - } else if (!D.isFunctionDefinition() && - isa(NewFD) && NewFD->isOutOfLine() && - !isFriend && !isFunctionTemplateSpecialization && - !isMemberSpecialization) { + } else if (!D.isFunctionDefinition() && isa(NewFD) && + NewFD->isOutOfLine() && !isFriend && + !isFunctionTemplateSpecialization && !isMemberSpecialization) { // An out-of-line member function declaration must also be a // definition (C++ [class.mfct]p2). // Note that this is not the case for explicit specializations of @@ -9164,7 +9132,7 @@ // extension for compatibility with old SWIG code which likes to // generate them. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getRange(); } } @@ -9175,9 +9143,8 @@ if (NewFD->hasAttr() && !NewFD->getType()->getAs()) { - Diag(NewFD->getLocation(), - diag::err_attribute_overloadable_no_prototype) - << NewFD; + Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype) + << NewFD; // Turn this into a variadic function with no parameters. const FunctionType *FT = NewFD->getType()->getAs(); @@ -9201,7 +9168,7 @@ // If this is a function definition, check if we have to apply optnone due to // a pragma. - if(D.isFunctionDefinition()) + if (D.isFunctionDefinition()) AddRangeBasedOptnone(NewFD); // If this is the first declaration of an extern C variable, update @@ -9246,12 +9213,9 @@ MarkUnusedFileScopedDecl(NewFD); - - if (getLangOpts().OpenCL && NewFD->hasAttr()) { // OpenCL v1.2 s6.8 static is invalid for kernel functions. - if ((getLangOpts().OpenCLVersion >= 120) - && (SC == SC_Static)) { + if ((getLangOpts().OpenCLVersion >= 120) && (SC == SC_Static)) { Diag(D.getIdentifierLoc(), diag::err_static_kernel); D.setInvalidType(); } @@ -9298,12 +9262,12 @@ // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value // types. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { - if(const PipeType *PipeTy = PT->getAs()) { + if (const PipeType *PipeTy = PT->getAs()) { QualType ElemTy = PipeTy->getElementType(); - if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { - Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); - D.setInvalidType(); - } + if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { + Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type); + D.setInvalidType(); + } } } } @@ -9313,10 +9277,9 @@ // time via the ClassScopeFunctionSpecializationDecl node. if (isDependentClassScopeExplicitSpecialization) { ClassScopeFunctionSpecializationDecl *NewSpec = - ClassScopeFunctionSpecializationDecl::Create( - Context, CurContext, NewFD->getLocation(), - cast(NewFD), - HasExplicitTemplateArgs, TemplateArgs); + ClassScopeFunctionSpecializationDecl::Create( + Context, CurContext, NewFD->getLocation(), + cast(NewFD), HasExplicitTemplateArgs, TemplateArgs); CurContext->addDecl(NewSpec); AddToScope = false; } @@ -9363,7 +9326,7 @@ // The Microsoft compiler won't check outer classes for the CodeSeg // when the #pragma code_seg stack is active. if (S.CodeSegStack.CurrentValue) - return nullptr; + return nullptr; while ((Parent = dyn_cast(Parent->getParent()))) { if (const auto *SAttr = Parent->getAttr()) { @@ -9773,8 +9736,7 @@ // nothing after the fact. if (PreviousDeclsHaveMultiVersionAttribute(FD) && (!CurTA || CurTA->isInherited())) { - S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) - << 0; + S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) << 0; S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); NewFD->setInvalidDecl(); return true; @@ -9938,7 +9900,6 @@ return false; } - /// Check the validity of a mulitversion function declaration. /// Also sets the multiversion'ness' of the function itself. /// @@ -9961,7 +9922,7 @@ return true; } - MultiVersionKind MVType = NewFD->getMultiVersionKind(); + MultiVersionKind MVType = NewFD->getMultiVersionKind(); // Main isn't allowed to become a multiversion function, however it IS // permitted to have 'main' be marked with the 'target' optimization hint. @@ -10038,8 +9999,8 @@ // Determine whether the type of this function should be merged with // a previous visible declaration. This never happens for functions in C++, // and always happens in C if the previous declaration was visible. - bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && - !Previous.isShadowed(); + bool MergeTypeWithPrevious = + !getLangOpts().CPlusPlus && !Previous.isShadowed(); bool Redeclaration = false; NamedDecl *OldDecl = nullptr; @@ -10120,8 +10081,7 @@ if (OldDecl) OldMD = dyn_cast_or_null(OldDecl->getAsFunction()); if (!OldMD || !OldMD->isStatic()) { - const FunctionProtoType *FPT = - MD->getType()->castAs(); + const FunctionProtoType *FPT = MD->getType()->castAs(); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.TypeQuals.addConst(); MD->setType(Context.getFunctionType(FPT->getReturnType(), @@ -10131,12 +10091,14 @@ // In that case, we'll have warned already when the template was defined. if (!inTemplateInstantiation()) { SourceLocation AddConstLoc; - if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() - .IgnoreParens().getAs()) + if (FunctionTypeLoc FTL = MD->getTypeSourceInfo() + ->getTypeLoc() + .IgnoreParens() + .getAs()) AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) - << FixItHint::CreateInsertion(AddConstLoc, " const"); + << FixItHint::CreateInsertion(AddConstLoc, " const"); } } } @@ -10155,8 +10117,8 @@ if (FunctionTemplateDecl *OldTemplateDecl = dyn_cast(OldDecl)) { auto *OldFD = OldTemplateDecl->getTemplatedDecl(); - FunctionTemplateDecl *NewTemplateDecl - = NewFD->getDescribedFunctionTemplate(); + FunctionTemplateDecl *NewTemplateDecl = + NewFD->getDescribedFunctionTemplate(); assert(NewTemplateDecl && "Template/non-template mismatch"); // The call to MergeFunctionDecl above may have created some state in @@ -10229,24 +10191,23 @@ if (CXXConstructorDecl *Constructor = dyn_cast(NewFD)) { CheckConstructor(Constructor); } else if (CXXDestructorDecl *Destructor = - dyn_cast(NewFD)) { + dyn_cast(NewFD)) { CXXRecordDecl *Record = Destructor->getParent(); QualType ClassType = Context.getTypeDeclType(Record); // FIXME: Shouldn't we be able to perform this check even when the class // type is dependent? Both gcc and edg can handle that. if (!ClassType->isDependentType()) { - DeclarationName Name - = Context.DeclarationNames.getCXXDestructorName( - Context.getCanonicalType(ClassType)); + DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( + Context.getCanonicalType(ClassType)); if (NewFD->getDeclName() != Name) { Diag(NewFD->getLocation(), diag::err_destructor_name); NewFD->setInvalidDecl(); return Redeclaration; } } - } else if (CXXConversionDecl *Conversion - = dyn_cast(NewFD)) { + } else if (CXXConversionDecl *Conversion = + dyn_cast(NewFD)) { ActOnConversionDeclarator(Conversion); } else if (auto *Guide = dyn_cast(NewFD)) { if (auto *TD = Guide->getDescribedFunctionTemplate()) @@ -10306,9 +10267,8 @@ // specification, that's OK. // FIXME: If the types do differ in this way, it would be better to // retain the 'noexcept' form of the type. - if (!T.isNull() && - !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, - NewFD->getType())) + if (!T.isNull() && !Context.hasSameFunctionTypeIgnoringExceptionSpec( + T, NewFD->getType())) // The type of this function differs from the type of the builtin, // so forget about the builtin entirely. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); @@ -10370,7 +10330,7 @@ return Redeclaration; } -void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { +void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) { // C++11 [basic.start.main]p3: // A program that [...] declares main to be inline, static or // constexpr is ill-formed. @@ -10380,17 +10340,18 @@ // We accept _Noreturn main as an extension. if (FD->getStorageClass() == SC_Static) Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus - ? diag::err_static_main : diag::warn_static_main) - << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); + ? diag::err_static_main + : diag::warn_static_main) + << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); if (FD->isInlineSpecified()) Diag(DS.getInlineSpecLoc(), diag::err_inline_main) - << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); + << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); if (DS.isNoreturnSpecified()) { SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); Diag(NoreturnLoc, diag::ext_noreturn_main); Diag(NoreturnLoc, diag::note_main_remove_noreturn) - << FixItHint::CreateRemoval(NoreturnRange); + << FixItHint::CreateRemoval(NoreturnRange); } if (FD->isConstexpr()) { Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) @@ -10408,7 +10369,7 @@ QualType T = FD->getType(); assert(T->isFunctionType() && "function decl is not of function type"); - const FunctionType* FT = T->castAs(); + const FunctionType *FT = T->castAs(); // Set default calling convention for main() if (FT->getCallConv() != CC_C) { @@ -10451,9 +10412,10 @@ } // Treat protoless main() as nullary. - if (isa(FT)) return; + if (isa(FT)) + return; - const FunctionProtoType* FTP = cast(FT); + const FunctionProtoType *FTP = cast(FT); unsigned nparams = FTP->getNumParams(); assert(FD->getNumParams() == nparams); @@ -10481,8 +10443,8 @@ // if we had some location information about types. QualType CharPP = - Context.getPointerType(Context.getPointerType(Context.CharTy)); - QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; + Context.getPointerType(Context.getPointerType(Context.CharTy)); + QualType Expected[] = {Context.IntTy, CharPP, CharPP, CharPP}; for (unsigned i = 0; i < nparams; ++i) { QualType AT = FTP->getParamType(i); @@ -10498,7 +10460,7 @@ // char * const * QualifierCollector qs; - const PointerType* PT; + const PointerType *PT; if ((PT = qs.strip(AT)->getAs()) && (PT = qs.strip(PT->getPointeeType())->getAs()) && Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), @@ -10558,349 +10520,348 @@ if (Init->isConstantInitializer(Context, false, &Culprit)) return false; Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) - << Culprit->getSourceRange(); + << Culprit->getSourceRange(); return true; } namespace { - // Visits an initialization expression to see if OrigDecl is evaluated in - // its own initialization and throws a warning if it does. - class SelfReferenceChecker - : public EvaluatedExprVisitor { - Sema &S; - Decl *OrigDecl; - bool isRecordType; - bool isPODType; - bool isReferenceType; - - bool isInitList; - llvm::SmallVector InitFieldIndex; - - public: - typedef EvaluatedExprVisitor Inherited; - - SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), - S(S), OrigDecl(OrigDecl) { - isPODType = false; - isRecordType = false; - isReferenceType = false; - isInitList = false; - if (ValueDecl *VD = dyn_cast(OrigDecl)) { - isPODType = VD->getType().isPODType(S.Context); - isRecordType = VD->getType()->isRecordType(); - isReferenceType = VD->getType()->isReferenceType(); - } - } +// Visits an initialization expression to see if OrigDecl is evaluated in +// its own initialization and throws a warning if it does. +class SelfReferenceChecker : public EvaluatedExprVisitor { + Sema &S; + Decl *OrigDecl; + bool isRecordType; + bool isPODType; + bool isReferenceType; - // For most expressions, just call the visitor. For initializer lists, - // track the index of the field being initialized since fields are - // initialized in order allowing use of previously initialized fields. - void CheckExpr(Expr *E) { - InitListExpr *InitList = dyn_cast(E); - if (!InitList) { - Visit(E); - return; - } + bool isInitList; + llvm::SmallVector InitFieldIndex; - // Track and increment the index here. - isInitList = true; - InitFieldIndex.push_back(0); - for (auto Child : InitList->children()) { - CheckExpr(cast(Child)); - ++InitFieldIndex.back(); - } - InitFieldIndex.pop_back(); +public: + typedef EvaluatedExprVisitor Inherited; + + SelfReferenceChecker(Sema &S, Decl *OrigDecl) + : Inherited(S.Context), S(S), OrigDecl(OrigDecl) { + isPODType = false; + isRecordType = false; + isReferenceType = false; + isInitList = false; + if (ValueDecl *VD = dyn_cast(OrigDecl)) { + isPODType = VD->getType().isPODType(S.Context); + isRecordType = VD->getType()->isRecordType(); + isReferenceType = VD->getType()->isReferenceType(); + } + } + + // For most expressions, just call the visitor. For initializer lists, + // track the index of the field being initialized since fields are + // initialized in order allowing use of previously initialized fields. + void CheckExpr(Expr *E) { + InitListExpr *InitList = dyn_cast(E); + if (!InitList) { + Visit(E); + return; } - // Returns true if MemberExpr is checked and no further checking is needed. - // Returns false if additional checking is required. - bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { - llvm::SmallVector Fields; - Expr *Base = E; - bool ReferenceField = false; + // Track and increment the index here. + isInitList = true; + InitFieldIndex.push_back(0); + for (auto Child : InitList->children()) { + CheckExpr(cast(Child)); + ++InitFieldIndex.back(); + } + InitFieldIndex.pop_back(); + } - // Get the field members used. - while (MemberExpr *ME = dyn_cast(Base)) { - FieldDecl *FD = dyn_cast(ME->getMemberDecl()); - if (!FD) - return false; - Fields.push_back(FD); - if (FD->getType()->isReferenceType()) - ReferenceField = true; - Base = ME->getBase()->IgnoreParenImpCasts(); - } + // Returns true if MemberExpr is checked and no further checking is needed. + // Returns false if additional checking is required. + bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { + llvm::SmallVector Fields; + Expr *Base = E; + bool ReferenceField = false; - // Keep checking only if the base Decl is the same. - DeclRefExpr *DRE = dyn_cast(Base); - if (!DRE || DRE->getDecl() != OrigDecl) + // Get the field members used. + while (MemberExpr *ME = dyn_cast(Base)) { + FieldDecl *FD = dyn_cast(ME->getMemberDecl()); + if (!FD) return false; - - // A reference field can be bound to an unininitialized field. - if (CheckReference && !ReferenceField) - return true; - - // Convert FieldDecls to their index number. - llvm::SmallVector UsedFieldIndex; - for (const FieldDecl *I : llvm::reverse(Fields)) - UsedFieldIndex.push_back(I->getFieldIndex()); - - // See if a warning is needed by checking the first difference in index - // numbers. If field being used has index less than the field being - // initialized, then the use is safe. - for (auto UsedIter = UsedFieldIndex.begin(), - UsedEnd = UsedFieldIndex.end(), - OrigIter = InitFieldIndex.begin(), - OrigEnd = InitFieldIndex.end(); - UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { - if (*UsedIter < *OrigIter) - return true; - if (*UsedIter > *OrigIter) - break; - } - - // TODO: Add a different warning which will print the field names. - HandleDeclRefExpr(DRE); - return true; + Fields.push_back(FD); + if (FD->getType()->isReferenceType()) + ReferenceField = true; + Base = ME->getBase()->IgnoreParenImpCasts(); } - // For most expressions, the cast is directly above the DeclRefExpr. - // For conditional operators, the cast can be outside the conditional - // operator if both expressions are DeclRefExpr's. - void HandleValue(Expr *E) { - E = E->IgnoreParens(); - if (DeclRefExpr* DRE = dyn_cast(E)) { - HandleDeclRefExpr(DRE); - return; - } - - if (ConditionalOperator *CO = dyn_cast(E)) { - Visit(CO->getCond()); - HandleValue(CO->getTrueExpr()); - HandleValue(CO->getFalseExpr()); - return; - } + // Keep checking only if the base Decl is the same. + DeclRefExpr *DRE = dyn_cast(Base); + if (!DRE || DRE->getDecl() != OrigDecl) + return false; - if (BinaryConditionalOperator *BCO = - dyn_cast(E)) { - Visit(BCO->getCond()); - HandleValue(BCO->getFalseExpr()); - return; - } + // A reference field can be bound to an unininitialized field. + if (CheckReference && !ReferenceField) + return true; - if (OpaqueValueExpr *OVE = dyn_cast(E)) { - HandleValue(OVE->getSourceExpr()); - return; - } + // Convert FieldDecls to their index number. + llvm::SmallVector UsedFieldIndex; + for (const FieldDecl *I : llvm::reverse(Fields)) + UsedFieldIndex.push_back(I->getFieldIndex()); + + // See if a warning is needed by checking the first difference in index + // numbers. If field being used has index less than the field being + // initialized, then the use is safe. + for (auto UsedIter = UsedFieldIndex.begin(), UsedEnd = UsedFieldIndex.end(), + OrigIter = InitFieldIndex.begin(), OrigEnd = InitFieldIndex.end(); + UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { + if (*UsedIter < *OrigIter) + return true; + if (*UsedIter > *OrigIter) + break; + } - if (BinaryOperator *BO = dyn_cast(E)) { - if (BO->getOpcode() == BO_Comma) { - Visit(BO->getLHS()); - HandleValue(BO->getRHS()); - return; - } - } + // TODO: Add a different warning which will print the field names. + HandleDeclRefExpr(DRE); + return true; + } - if (isa(E)) { - if (isInitList) { - if (CheckInitListMemberExpr(cast(E), - false /*CheckReference*/)) - return; - } + // For most expressions, the cast is directly above the DeclRefExpr. + // For conditional operators, the cast can be outside the conditional + // operator if both expressions are DeclRefExpr's. + void HandleValue(Expr *E) { + E = E->IgnoreParens(); + if (DeclRefExpr *DRE = dyn_cast(E)) { + HandleDeclRefExpr(DRE); + return; + } - Expr *Base = E->IgnoreParenImpCasts(); - while (MemberExpr *ME = dyn_cast(Base)) { - // Check for static member variables and don't warn on them. - if (!isa(ME->getMemberDecl())) - return; - Base = ME->getBase()->IgnoreParenImpCasts(); - } - if (DeclRefExpr *DRE = dyn_cast(Base)) - HandleDeclRefExpr(DRE); - return; - } + if (ConditionalOperator *CO = dyn_cast(E)) { + Visit(CO->getCond()); + HandleValue(CO->getTrueExpr()); + HandleValue(CO->getFalseExpr()); + return; + } - Visit(E); + if (BinaryConditionalOperator *BCO = + dyn_cast(E)) { + Visit(BCO->getCond()); + HandleValue(BCO->getFalseExpr()); + return; } - // Reference types not handled in HandleValue are handled here since all - // uses of references are bad, not just r-value uses. - void VisitDeclRefExpr(DeclRefExpr *E) { - if (isReferenceType) - HandleDeclRefExpr(E); + if (OpaqueValueExpr *OVE = dyn_cast(E)) { + HandleValue(OVE->getSourceExpr()); + return; } - void VisitImplicitCastExpr(ImplicitCastExpr *E) { - if (E->getCastKind() == CK_LValueToRValue) { - HandleValue(E->getSubExpr()); + if (BinaryOperator *BO = dyn_cast(E)) { + if (BO->getOpcode() == BO_Comma) { + Visit(BO->getLHS()); + HandleValue(BO->getRHS()); return; } - - Inherited::VisitImplicitCastExpr(E); } - void VisitMemberExpr(MemberExpr *E) { + if (isa(E)) { if (isInitList) { - if (CheckInitListMemberExpr(E, true /*CheckReference*/)) + if (CheckInitListMemberExpr(cast(E), + false /*CheckReference*/)) return; } - // Don't warn on arrays since they can be treated as pointers. - if (E->getType()->canDecayToPointerType()) return; - - // Warn when a non-static method call is followed by non-static member - // field accesses, which is followed by a DeclRefExpr. - CXXMethodDecl *MD = dyn_cast(E->getMemberDecl()); - bool Warn = (MD && !MD->isStatic()); - Expr *Base = E->getBase()->IgnoreParenImpCasts(); + Expr *Base = E->IgnoreParenImpCasts(); while (MemberExpr *ME = dyn_cast(Base)) { + // Check for static member variables and don't warn on them. if (!isa(ME->getMemberDecl())) - Warn = false; + return; Base = ME->getBase()->IgnoreParenImpCasts(); } + if (DeclRefExpr *DRE = dyn_cast(Base)) + HandleDeclRefExpr(DRE); + return; + } - if (DeclRefExpr *DRE = dyn_cast(Base)) { - if (Warn) - HandleDeclRefExpr(DRE); - return; - } + Visit(E); + } + + // Reference types not handled in HandleValue are handled here since all + // uses of references are bad, not just r-value uses. + void VisitDeclRefExpr(DeclRefExpr *E) { + if (isReferenceType) + HandleDeclRefExpr(E); + } - // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. - // Visit that expression. - Visit(Base); + void VisitImplicitCastExpr(ImplicitCastExpr *E) { + if (E->getCastKind() == CK_LValueToRValue) { + HandleValue(E->getSubExpr()); + return; } - void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { - Expr *Callee = E->getCallee(); + Inherited::VisitImplicitCastExpr(E); + } - if (isa(Callee)) - return Inherited::VisitCXXOperatorCallExpr(E); + void VisitMemberExpr(MemberExpr *E) { + if (isInitList) { + if (CheckInitListMemberExpr(E, true /*CheckReference*/)) + return; + } + + // Don't warn on arrays since they can be treated as pointers. + if (E->getType()->canDecayToPointerType()) + return; - Visit(Callee); - for (auto Arg: E->arguments()) - HandleValue(Arg->IgnoreParenImpCasts()); + // Warn when a non-static method call is followed by non-static member + // field accesses, which is followed by a DeclRefExpr. + CXXMethodDecl *MD = dyn_cast(E->getMemberDecl()); + bool Warn = (MD && !MD->isStatic()); + Expr *Base = E->getBase()->IgnoreParenImpCasts(); + while (MemberExpr *ME = dyn_cast(Base)) { + if (!isa(ME->getMemberDecl())) + Warn = false; + Base = ME->getBase()->IgnoreParenImpCasts(); } - void VisitUnaryOperator(UnaryOperator *E) { - // For POD record types, addresses of its own members are well-defined. - if (E->getOpcode() == UO_AddrOf && isRecordType && - isa(E->getSubExpr()->IgnoreParens())) { - if (!isPODType) - HandleValue(E->getSubExpr()); - return; - } + if (DeclRefExpr *DRE = dyn_cast(Base)) { + if (Warn) + HandleDeclRefExpr(DRE); + return; + } + + // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. + // Visit that expression. + Visit(Base); + } + + void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { + Expr *Callee = E->getCallee(); + + if (isa(Callee)) + return Inherited::VisitCXXOperatorCallExpr(E); - if (E->isIncrementDecrementOp()) { + Visit(Callee); + for (auto Arg : E->arguments()) + HandleValue(Arg->IgnoreParenImpCasts()); + } + + void VisitUnaryOperator(UnaryOperator *E) { + // For POD record types, addresses of its own members are well-defined. + if (E->getOpcode() == UO_AddrOf && isRecordType && + isa(E->getSubExpr()->IgnoreParens())) { + if (!isPODType) HandleValue(E->getSubExpr()); - return; - } + return; + } - Inherited::VisitUnaryOperator(E); + if (E->isIncrementDecrementOp()) { + HandleValue(E->getSubExpr()); + return; } - void VisitObjCMessageExpr(ObjCMessageExpr *E) {} + Inherited::VisitUnaryOperator(E); + } - void VisitCXXConstructExpr(CXXConstructExpr *E) { - if (E->getConstructor()->isCopyConstructor()) { - Expr *ArgExpr = E->getArg(0); - if (InitListExpr *ILE = dyn_cast(ArgExpr)) - if (ILE->getNumInits() == 1) - ArgExpr = ILE->getInit(0); - if (ImplicitCastExpr *ICE = dyn_cast(ArgExpr)) - if (ICE->getCastKind() == CK_NoOp) - ArgExpr = ICE->getSubExpr(); - HandleValue(ArgExpr); - return; - } - Inherited::VisitCXXConstructExpr(E); + void VisitObjCMessageExpr(ObjCMessageExpr *E) {} + + void VisitCXXConstructExpr(CXXConstructExpr *E) { + if (E->getConstructor()->isCopyConstructor()) { + Expr *ArgExpr = E->getArg(0); + if (InitListExpr *ILE = dyn_cast(ArgExpr)) + if (ILE->getNumInits() == 1) + ArgExpr = ILE->getInit(0); + if (ImplicitCastExpr *ICE = dyn_cast(ArgExpr)) + if (ICE->getCastKind() == CK_NoOp) + ArgExpr = ICE->getSubExpr(); + HandleValue(ArgExpr); + return; } + Inherited::VisitCXXConstructExpr(E); + } - void VisitCallExpr(CallExpr *E) { - // Treat std::move as a use. - if (E->isCallToStdMove()) { - HandleValue(E->getArg(0)); - return; - } + void VisitCallExpr(CallExpr *E) { + // Treat std::move as a use. + if (E->isCallToStdMove()) { + HandleValue(E->getArg(0)); + return; + } + + Inherited::VisitCallExpr(E); + } - Inherited::VisitCallExpr(E); + void VisitBinaryOperator(BinaryOperator *E) { + if (E->isCompoundAssignmentOp()) { + HandleValue(E->getLHS()); + Visit(E->getRHS()); + return; } - void VisitBinaryOperator(BinaryOperator *E) { - if (E->isCompoundAssignmentOp()) { - HandleValue(E->getLHS()); - Visit(E->getRHS()); - return; - } + Inherited::VisitBinaryOperator(E); + } - Inherited::VisitBinaryOperator(E); - } - - // A custom visitor for BinaryConditionalOperator is needed because the - // regular visitor would check the condition and true expression separately - // but both point to the same place giving duplicate diagnostics. - void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { - Visit(E->getCond()); - Visit(E->getFalseExpr()); - } - - void HandleDeclRefExpr(DeclRefExpr *DRE) { - Decl* ReferenceDecl = DRE->getDecl(); - if (OrigDecl != ReferenceDecl) return; - unsigned diag; - if (isReferenceType) { - diag = diag::warn_uninit_self_reference_in_reference_init; - } else if (cast(OrigDecl)->isStaticLocal()) { - diag = diag::warn_static_self_reference_in_init; - } else if (isa(OrigDecl->getDeclContext()) || - isa(OrigDecl->getDeclContext()) || - DRE->getDecl()->getType()->isRecordType()) { - diag = diag::warn_uninit_self_reference_in_init; - } else { - // Local variables will be handled by the CFG analysis. - return; - } + // A custom visitor for BinaryConditionalOperator is needed because the + // regular visitor would check the condition and true expression separately + // but both point to the same place giving duplicate diagnostics. + void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { + Visit(E->getCond()); + Visit(E->getFalseExpr()); + } - S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, - S.PDiag(diag) - << DRE->getDecl() << OrigDecl->getLocation() - << DRE->getSourceRange()); + void HandleDeclRefExpr(DeclRefExpr *DRE) { + Decl *ReferenceDecl = DRE->getDecl(); + if (OrigDecl != ReferenceDecl) + return; + unsigned diag; + if (isReferenceType) { + diag = diag::warn_uninit_self_reference_in_reference_init; + } else if (cast(OrigDecl)->isStaticLocal()) { + diag = diag::warn_static_self_reference_in_init; + } else if (isa(OrigDecl->getDeclContext()) || + isa(OrigDecl->getDeclContext()) || + DRE->getDecl()->getType()->isRecordType()) { + diag = diag::warn_uninit_self_reference_in_init; + } else { + // Local variables will be handled by the CFG analysis. + return; } - }; - /// CheckSelfReference - Warns if OrigDecl is used in expression E. - static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, - bool DirectInit) { - // Parameters arguments are occassionially constructed with itself, - // for instance, in recursive functions. Skip them. - if (isa(OrigDecl)) - return; + S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, + S.PDiag(diag) + << DRE->getDecl() << OrigDecl->getLocation() + << DRE->getSourceRange()); + } +}; - E = E->IgnoreParens(); +/// CheckSelfReference - Warns if OrigDecl is used in expression E. +static void CheckSelfReference(Sema &S, Decl *OrigDecl, Expr *E, + bool DirectInit) { + // Parameters arguments are occassionially constructed with itself, + // for instance, in recursive functions. Skip them. + if (isa(OrigDecl)) + return; - // Skip checking T a = a where T is not a record or reference type. - // Doing so is a way to silence uninitialized warnings. - if (!DirectInit && !cast(OrigDecl)->getType()->isRecordType()) - if (ImplicitCastExpr *ICE = dyn_cast(E)) - if (ICE->getCastKind() == CK_LValueToRValue) - if (DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr())) - if (DRE->getDecl() == OrigDecl) - return; + E = E->IgnoreParens(); - SelfReferenceChecker(S, OrigDecl).CheckExpr(E); - } + // Skip checking T a = a where T is not a record or reference type. + // Doing so is a way to silence uninitialized warnings. + if (!DirectInit && !cast(OrigDecl)->getType()->isRecordType()) + if (ImplicitCastExpr *ICE = dyn_cast(E)) + if (ICE->getCastKind() == CK_LValueToRValue) + if (DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr())) + if (DRE->getDecl() == OrigDecl) + return; + + SelfReferenceChecker(S, OrigDecl).CheckExpr(E); +} } // end anonymous namespace namespace { - // Simple wrapper to add the name of a variable or (if no variable is - // available) a DeclarationName into a diagnostic. - struct VarDeclOrName { - VarDecl *VDecl; - DeclarationName Name; +// Simple wrapper to add the name of a variable or (if no variable is +// available) a DeclarationName into a diagnostic. +struct VarDeclOrName { + VarDecl *VDecl; + DeclarationName Name; - friend const Sema::SemaDiagnosticBuilder & - operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { - return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; - } - }; + friend const Sema::SemaDiagnosticBuilder & + operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { + return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; + } +}; } // end anonymous namespace QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, @@ -10924,15 +10885,14 @@ // Except for class argument deduction, and then for an initializing // declaration only, i.e. no static at class scope or extern. if (!isa(Deduced) || - VDecl->hasExternalStorage() || - VDecl->isStaticDataMember()) { + VDecl->hasExternalStorage() || VDecl->isStaticDataMember()) { Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) - << VDecl->getDeclName() << Type; + << VDecl->getDeclName() << Type; return QualType(); } } - ArrayRef DeduceInits; + ArrayRef DeduceInits; if (Init) DeduceInits = Init; @@ -10947,7 +10907,7 @@ InitializationKind Kind = InitializationKind::CreateForInit( VDecl->getLocation(), DirectInit, Init); // FIXME: Initialization should not be taking a mutable list of inits. - SmallVector InitsCopy(DeduceInits.begin(), DeduceInits.end()); + SmallVector InitsCopy(DeduceInits.begin(), DeduceInits.end()); return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, InitsCopy); } @@ -11083,7 +11043,7 @@ if (CXXMethodDecl *Method = dyn_cast(RealDecl)) { // Pure-specifiers are handled in ActOnPureSpecifier. Diag(Method->getLocation(), diag::err_member_function_initialization) - << Method->getDeclName() << Init->getSourceRange(); + << Method->getDeclName() << Init->getSourceRange(); Method->setInvalidDecl(); return; } @@ -11211,6 +11171,82 @@ Init = Result.get(); } + if (TagDecl *TD = VDecl->getType().getTypePtr()->getAsTagDecl()) { + // If the type of the declaration is a struct/class and that type has the + // require_designated_init attribute, check that the initializer has + // the proper designated initializer syntax. + if (TD && TD->hasAttr()) { + if (InitListExpr *ILE = dyn_cast(Init)) { + for (unsigned i = 0; i < ILE->getNumInits(); i++) { + Expr *init = ILE->getInit(i); + DesignatedInitExpr *DIE = dyn_cast(init); + if (!DIE) { + SourceRange SR(VDecl->getSourceRange().getBegin(), + Init->getSourceRange().getEnd()); + Diag(init->getExprLoc(), diag::err_require_designated_init_failed) + << SR; + auto attr = TD->getAttr(); + Diag(attr->getLocation(), + diag::note_declared_required_designated_init_here) + << attr->getRange(); + VDecl->setInvalidDecl(); + return; + } + } + } + } + // If the type of the declaration is a struct/class, we must check whether + // any of the fields have the required attribute. If any of them do, we must + // confirm that each of those fields are initialized with designated + // initializer syntax. + if (RecordDecl *RD = dyn_cast(TD)) { + // Iterate through all the fields of the record and add all of the + // required fields to a set. The field will be removed later if it is + // properly initialized. + std::set RequiredFields; + for (auto FD : RD->fields()) { + if (FD->hasAttr()) { + RequiredFields.insert(FD->getIdentifier()); + } + } + // Iterate through all the initializers and remove a field from the set if + // it is initialized correctly using designated initializer syntax. + if (RequiredFields.size() > 0) { + if (InitListExpr *ILE = dyn_cast(Init)) { + for (unsigned I = 0, E = ILE->getNumInits(); I != E; I++) { + Expr *init = ILE->getInit(I); + if (DesignatedInitExpr *DIE = dyn_cast(init)) { + DesignatedInitExpr::Designator *D = DIE->getDesignator(0); + if (D->isFieldDesignator()) { + IdentifierInfo *name = D->getFieldName(); + if (RequiredFields.count(name) != 0) + RequiredFields.erase(name); + } + } + } + } + // Iterate through all the remaining fields and emit a diagnostic for + // each field. + for (auto FD : RD->fields()) { + if (RequiredFields.count(FD->getIdentifier()) != 0) { + SourceRange SR(VDecl->getSourceRange().getBegin(), + Init->getSourceRange().getEnd()); + Diag(Init->getExprLoc(), diag::err_required_failed) + << SR << VDecl->getName() << FD->getName(); + auto attr = FD->getAttr(); + Diag(attr->getLocation(), diag::note_declared_required_here) + << attr->getRange(); + VDecl->setInvalidDecl(); + RequiredFields.erase(FD->getIdentifier()); + } + } + // Return here so all attribute violation errors get emitted. + if (VDecl->isInvalidDecl()) + return; + } + } + } + // Perform the initialization. ParenListExpr *CXXDirectInit = dyn_cast(Init); if (!VDecl->isInvalidDecl()) { @@ -11220,8 +11256,8 @@ MultiExprArg Args = Init; if (CXXDirectInit) - Args = MultiExprArg(CXXDirectInit->getExprs(), - CXXDirectInit->getNumExprs()); + Args = + MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); // Try to correct any TypoExprs in the initialization arguments. for (size_t Idx = 0; Idx < Args.size(); ++Idx) { @@ -11315,31 +11351,31 @@ if (VDecl->isInvalidDecl()) { // do nothing - // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. - // This is true even in OpenCL C++. + // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. + // This is true even in OpenCL C++. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { CheckForConstantInitializer(Init, DclT); - // Otherwise, C++ does not restrict the initializer. + // Otherwise, C++ does not restrict the initializer. } else if (getLangOpts().CPlusPlus) { // do nothing - // C99 6.7.8p4: All the expressions in an initializer for an object that has - // static storage duration shall be constant expressions or string literals. + // C99 6.7.8p4: All the expressions in an initializer for an object that + // has static storage duration shall be constant expressions or string + // literals. } else if (VDecl->getStorageClass() == SC_Static) { CheckForConstantInitializer(Init, DclT); - // C89 is stricter than C99 for aggregate initializers. - // C89 6.5.7p3: All the expressions [...] in an initializer list - // for an object that has aggregate or union type shall be - // constant expressions. + // C89 is stricter than C99 for aggregate initializers. + // C89 6.5.7p3: All the expressions [...] in an initializer list + // for an object that has aggregate or union type shall be + // constant expressions. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && isa(Init)) { const Expr *Culprit; if (!Init->isConstantInitializer(Context, false, &Culprit)) { - Diag(Culprit->getExprLoc(), - diag::ext_aggregate_init_not_constant) - << Culprit->getSourceRange(); + Diag(Culprit->getExprLoc(), diag::ext_aggregate_init_not_constant) + << Culprit->getSourceRange(); } } @@ -11373,18 +11409,18 @@ // Do nothing on dependent types. if (DclT->isDependentType()) { - // Allow any 'static constexpr' members, whether or not they are of literal - // type. We separately check that every constexpr variable is of literal - // type. + // Allow any 'static constexpr' members, whether or not they are of + // literal type. We separately check that every constexpr variable is of + // literal type. } else if (VDecl->isConstexpr()) { - // Require constness. + // Require constness. } else if (!DclT.isConstQualified()) { Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) - << Init->getSourceRange(); + << Init->getSourceRange(); VDecl->setInvalidDecl(); - // We allow integer constant expressions in all cases. + // We allow integer constant expressions in all cases. } else if (DclT->isIntegralOrEnumerationType()) { // Check whether the expression is a constant expression. SourceLocation Loc; @@ -11403,16 +11439,16 @@ // If we can constant fold the initializer through heroics, accept it, // but report this as a use of an extension for -pedantic. Diag(Loc, diag::ext_in_class_initializer_non_constant) - << Init->getSourceRange(); + << Init->getSourceRange(); } else { // Otherwise, this is some crazy unknown case. Report the issue at the // location provided by the isIntegerConstantExpr failed check. Diag(Loc, diag::err_in_class_initializer_non_constant) - << Init->getSourceRange(); + << Init->getSourceRange(); VDecl->setInvalidDecl(); } - // We allow foldable floating-point constants as an extension. + // We allow foldable floating-point constants as an extension. } else if (DclT->isFloatingType()) { // also permits complex, which is ok // In C++98, this is a GNU extension. In C++11, it is not, but we support // it anyway and provide a fixit to add the 'constexpr'. @@ -11425,16 +11461,16 @@ << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); } else { Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) - << DclT << Init->getSourceRange(); + << DclT << Init->getSourceRange(); if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) - << Init->getSourceRange(); + << Init->getSourceRange(); VDecl->setInvalidDecl(); } } - // Suggest adding 'constexpr' in C++11 for literal types. + // Suggest adding 'constexpr' in C++11 for literal types. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) << DclT << Init->getSourceRange() @@ -11443,7 +11479,7 @@ } else { Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) - << DclT << Init->getSourceRange(); + << DclT << Init->getSourceRange(); VDecl->setInvalidDecl(); } } else if (VDecl->isFileVarDecl()) { @@ -11505,10 +11541,12 @@ void Sema::ActOnInitializerError(Decl *D) { // Our main concern here is re-establishing invariants like "a // variable's type is either dependent or complete". - if (!D || D->isInvalidDecl()) return; + if (!D || D->isInvalidDecl()) + return; VarDecl *VD = dyn_cast(D); - if (!VD) return; + if (!VD) + return; // Bindings are not usable if we can't make sense of the initializer. if (auto *DD = dyn_cast(D)) @@ -11522,11 +11560,11 @@ } QualType Ty = VD->getType(); - if (Ty->isDependentType()) return; + if (Ty->isDependentType()) + return; // Require a complete type. - if (RequireCompleteType(VD->getLocation(), - Context.getBaseElementType(Ty), + if (RequireCompleteType(VD->getLocation(), Context.getBaseElementType(Ty), diag::err_typecheck_decl_incomplete_type)) { VD->setInvalidDecl(); return; @@ -11552,6 +11590,39 @@ if (VarDecl *Var = dyn_cast(RealDecl)) { QualType Type = Var->getType(); + if (TagDecl *TD = Type.getTypePtr()->getAsTagDecl()) { + // If the type of the declaration is a struct/class and that type has the + // require_designated_init attribute, an initializer is mandatory. + if (TD->hasAttr()) { + Diag(Var->getLocation(), diag::err_require_designated_init_failed) + << Var->getSourceRange(); + auto attr = TD->getAttr(); + Diag(attr->getLocation(), + diag::note_declared_required_designated_init_here) + << attr->getRange(); + Var->setInvalidDecl(); + return; + } + // If the type of the declaration is a struct/class, we must check whether + // any of the fields have the required attribute. For each that does, emit + // an error since it is not initialized with designated initializer + // syntax. + if (RecordDecl *RD = dyn_cast(TD)) { + for (auto FD : RD->fields()) { + if (FD->hasAttr()) { + Diag(Var->getLocation(), diag::err_required_failed) + << Var->getSourceRange() << Var->getName() << FD->getName(); + auto attr = FD->getAttr(); + Diag(attr->getLocation(), diag::note_declared_required_here) + << attr->getRange(); + Var->setInvalidDecl(); + } + } + if (Var->isInvalidDecl()) + return; + } + } + // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. if (isa(RealDecl)) { Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; @@ -11577,7 +11648,7 @@ if (!getLangOpts().CPlusPlus17) { Diag(Var->getLocation(), diag::err_constexpr_static_mem_var_requires_init) - << Var->getDeclName(); + << Var->getDeclName(); Var->setInvalidDecl(); return; } @@ -11642,10 +11713,9 @@ // constitutes a tentative definition. Note: A tentative definition with // external linkage is valid (C99 6.2.2p5). if (!Var->isInvalidDecl()) { - if (const IncompleteArrayType *ArrayT - = Context.getAsIncompleteArrayType(Type)) { - if (RequireCompleteType(Var->getLocation(), - ArrayT->getElementType(), + if (const IncompleteArrayType *ArrayT = + Context.getAsIncompleteArrayType(Type)) { + if (RequireCompleteType(Var->getLocation(), ArrayT->getElementType(), diag::err_illegal_decl_array_incomplete_type)) Var->setInvalidDecl(); } else if (Var->getStorageClass() == SC_Static) { @@ -11683,8 +11753,8 @@ // definitions with reference type. if (Type->isReferenceType()) { Diag(Var->getLocation(), diag::err_reference_var_requires_init) - << Var->getDeclName() - << SourceRange(Var->getLocation(), Var->getLocation()); + << Var->getDeclName() + << SourceRange(Var->getLocation(), Var->getLocation()); Var->setInvalidDecl(); return; } @@ -11727,8 +11797,8 @@ // version of one of these types, or an array of one of the preceding // types and is declared without an initializer. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { - if (const RecordType *Record - = Context.getBaseElementType(Type)->getAs()) { + if (const RecordType *Record = + Context.getBaseElementType(Type)->getAs()) { CXXRecordDecl *CXXRecord = cast(Record->getDecl()); // Mark the function (if we're in one) for further checking even if the // looser rules of C++11 do not require such checks, so that we can @@ -11757,8 +11827,8 @@ // If no initializer is specified for an object, the object is // default-initialized; [...]. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); - InitializationKind Kind - = InitializationKind::CreateDefault(Var->getLocation()); + InitializationKind Kind = + InitializationKind::CreateDefault(Var->getLocation()); InitializationSequence InitSeq(*this, Entity, Kind, None); ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); @@ -11811,16 +11881,15 @@ } if (Error != -1) { Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) - << VD->getDeclName() << Error; + << VD->getDeclName() << Error; D->setInvalidDecl(); } } -StmtResult -Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, - IdentifierInfo *Ident, - ParsedAttributes &Attrs, - SourceLocation AttrEnd) { +StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, + IdentifierInfo *Ident, + ParsedAttributes &Attrs, + SourceLocation AttrEnd) { // C++1y [stmt.iter]p1: // A range-based for statement of the form // for ( for-range-identifier : for-range-initializer ) statement @@ -11847,7 +11916,8 @@ } void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { - if (var->isInvalidDecl()) return; + if (var->isInvalidDecl()) + return; if (getLangOpts().OpenCL) { // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an @@ -11863,8 +11933,7 @@ // In Objective-C, don't allow jumps past the implicit initialization of a // local retaining variable. - if (getLangOpts().ObjC && - var->hasLocalStorage()) { + if (getLangOpts().ObjC && var->hasLocalStorage()) { switch (var->getType().getObjCLifetime()) { case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: @@ -11889,8 +11958,8 @@ // change if it's later given a typedef name. if (var->isThisDeclarationADefinition() && var->getDeclContext()->getRedeclContext()->isFileContext() && - var->isExternallyVisible() && var->hasLinkage() && - !var->isInline() && !var->getDescribedVarTemplate() && + var->isExternallyVisible() && var->hasLinkage() && !var->isInline() && + !var->getDescribedVarTemplate() && !isTemplateInstantiation(var->getTemplateSpecializationKind()) && !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, var->getLocation())) { @@ -11912,7 +11981,7 @@ auto checkConstInit = [&]() mutable { if (!CacheHasConstInit) CacheHasConstInit = var->getInit()->isConstantInitializer( - Context, var->getType()->isReferenceType(), &CacheCulprit); + Context, var->getType()->isReferenceType(), &CacheCulprit); return *CacheHasConstInit; }; @@ -11931,7 +12000,7 @@ // initialization. // FIXME: Need strict checking here. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) - << CacheCulprit->getSourceRange(); + << CacheCulprit->getSourceRange(); if (getLangOpts().CPlusPlus11) Diag(var->getLocation(), diag::note_use_thread_local); } @@ -11972,18 +12041,19 @@ // All the following checks are C++ only. if (!getLangOpts().CPlusPlus) { - // If this variable must be emitted, add it as an initializer for the - // current module. - if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) - Context.addModuleInitializer(ModuleScopes.back().Module, var); - return; + // If this variable must be emitted, add it as an initializer for the + // current module. + if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) + Context.addModuleInitializer(ModuleScopes.back().Module, var); + return; } if (auto *DD = dyn_cast(var)) CheckCompleteDecompositionDeclaration(DD); QualType type = var->getType(); - if (type->isDependentType()) return; + if (type->isDependentType()) + return; if (var->hasAttr()) getCurFunction()->addByrefBlockVar(var); @@ -12000,12 +12070,12 @@ // If the note doesn't add any useful information other than a source // location, fold it into the primary diagnostic. if (Notes.size() == 1 && Notes[0].second.getDiagID() == - diag::note_invalid_subexpr_in_const_expr) { + diag::note_invalid_subexpr_in_const_expr) { DiagLoc = Notes[0].first; Notes.clear(); } Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) - << var << Init->getSourceRange(); + << var << Init->getSourceRange(); for (unsigned I = 0, N = Notes.size(); I != N; ++I) Diag(Notes[I].first, Notes[I].second); } @@ -12019,16 +12089,17 @@ // Don't emit further diagnostics about constexpr globals since they // were just diagnosed. if (!var->isConstexpr() && GlobalStorage && - var->hasAttr()) { + var->hasAttr()) { // FIXME: Need strict checking in C++03 here. - bool DiagErr = getLangOpts().CPlusPlus11 - ? !var->checkInitIsICE() : !checkConstInit(); + bool DiagErr = getLangOpts().CPlusPlus11 ? !var->checkInitIsICE() + : !checkConstInit(); if (DiagErr) { auto attr = var->getAttr(); Diag(var->getLocation(), diag::err_require_constant_init_failed) - << Init->getSourceRange(); - Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) - << attr->getRange(); + << Init->getSourceRange(); + Diag(attr->getLocation(), + diag::note_declared_required_constant_init_here) + << attr->getRange(); if (getLangOpts().CPlusPlus11) { APValue Value; SmallVector Notes; @@ -12041,10 +12112,9 @@ << CacheCulprit->getSourceRange(); } } - } - else if (!var->isConstexpr() && IsGlobal && - !getDiagnostics().isIgnored(diag::warn_global_constructor, - var->getLocation())) { + } else if (!var->isConstexpr() && IsGlobal && + !getDiagnostics().isIgnored(diag::warn_global_constructor, + var->getLocation())) { // Warn about globals which don't have a constant initializer. Don't // warn about globals with a non-trivial destructor because we already // warned about them. @@ -12052,7 +12122,7 @@ if (!(RD && !RD->hasTrivialDestructor())) { if (!checkConstInit()) Diag(var->getLocation(), diag::warn_global_constructor) - << Init->getSourceRange(); + << Init->getSourceRange(); } } } @@ -12085,8 +12155,7 @@ auto *FD = dyn_cast_or_null(VD->getParentFunctionOrMethod()); // Find outermost function when VD is in lambda function. - while (FD && !getDLLAttr(FD) && - !FD->hasAttr() && + while (FD && !getDLLAttr(FD) && !FD->hasAttr() && !FD->hasAttr()) { FD = dyn_cast_or_null(FD->getParentFunctionOrMethod()); } @@ -12100,9 +12169,8 @@ NewAttr->setInherited(true); VD->addAttr(NewAttr); } else if (Attr *A = FD->getAttr()) { - auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), - getASTContext(), - A->getSpellingListIndex()); + auto *NewAttr = ::new (getASTContext()) DLLExportAttr( + A->getRange(), getASTContext(), A->getSpellingListIndex()); NewAttr->setInherited(true); VD->addAttr(NewAttr); @@ -12112,9 +12180,8 @@ FD->addAttr(NewAttr); } else if (Attr *A = FD->getAttr()) { - auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), - getASTContext(), - A->getSpellingListIndex()); + auto *NewAttr = ::new (getASTContext()) DLLImportAttr( + A->getRange(), getASTContext(), A->getSpellingListIndex()); NewAttr->setInherited(true); VD->addAttr(NewAttr); } @@ -12130,21 +12197,22 @@ if (!VD) return; - // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active + // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is + // active if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && !inTemplateInstantiation() && !VD->hasAttr()) { if (PragmaClangBSSSection.Valid) - VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, - PragmaClangBSSSection.SectionName, - PragmaClangBSSSection.PragmaLocation)); + VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( + Context, PragmaClangBSSSection.SectionName, + PragmaClangBSSSection.PragmaLocation)); if (PragmaClangDataSection.Valid) - VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, - PragmaClangDataSection.SectionName, - PragmaClangDataSection.PragmaLocation)); + VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( + Context, PragmaClangDataSection.SectionName, + PragmaClangDataSection.PragmaLocation)); if (PragmaClangRodataSection.Valid) - VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, - PragmaClangRodataSection.SectionName, - PragmaClangRodataSection.PragmaLocation)); + VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( + Context, PragmaClangRodataSection.SectionName, + PragmaClangRodataSection.PragmaLocation)); } if (auto *DD = dyn_cast(ThisDecl)) { @@ -12166,8 +12234,8 @@ CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); if (Context.getDeclAlign(VD) > MaxAlignChars) { Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) - << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD - << (unsigned)MaxAlignChars.getQuantity(); + << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD + << (unsigned)MaxAlignChars.getQuantity(); } } } @@ -12216,7 +12284,7 @@ // We allow definitions of dllimport class template static data members // with a warning. CXXRecordDecl *Context = - cast(VD->getFirstDecl()->getDeclContext()); + cast(VD->getFirstDecl()->getDeclContext()); bool IsClassTemplateMember = isa(Context) || Context->getDescribedClassTemplate(); @@ -12241,8 +12309,8 @@ // function will never be inlined, which means the var would never be // imported, so having it marked import/export is safe. } else { - Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD - << DLLAttr; + Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) + << VD << DLLAttr; VD->setInvalidDecl(); } } @@ -12277,22 +12345,18 @@ } llvm::APSInt MagicValueInt; if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { - Diag(I->getRange().getBegin(), - diag::err_type_tag_for_datatype_not_ice) - << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); + Diag(I->getRange().getBegin(), diag::err_type_tag_for_datatype_not_ice) + << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); continue; } if (MagicValueInt.getActiveBits() > 64) { - Diag(I->getRange().getBegin(), - diag::err_type_tag_for_datatype_too_large) - << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); + Diag(I->getRange().getBegin(), diag::err_type_tag_for_datatype_too_large) + << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); continue; } uint64_t MagicValue = MagicValueInt.getZExtValue(); - RegisterTypeTagForDatatype(I->getArgumentKind(), - MagicValue, - I->getMatchingCType(), - I->getLayoutCompatible(), + RegisterTypeTagForDatatype(I->getArgumentKind(), MagicValue, + I->getMatchingCType(), I->getLayoutCompatible(), I->getMustBeNull()); } } @@ -12304,7 +12368,7 @@ Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef Group) { - SmallVector Decls; + SmallVector Decls; if (DS.isTypeSpecOwned()) Decls.push_back(DS.getRepAsDecl()); @@ -12372,8 +12436,7 @@ /// BuildDeclaratorGroup - convert a list of declarations into a declaration /// group, performing any necessary semantic checking. -Sema::DeclGroupPtrTy -Sema::BuildDeclaratorGroup(MutableArrayRef Group) { +Sema::DeclGroupPtrTy Sema::BuildDeclaratorGroup(MutableArrayRef Group) { // C++14 [dcl.spec.auto]p7: (DR1347) // If the type that replaces the placeholder type is not the same in each // deduction, the program is ill-formed. @@ -12394,11 +12457,10 @@ auto *AT = dyn_cast(DT); Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), diag::err_auto_different_deductions) - << (AT ? (unsigned)AT->getKeyword() : 3) - << Deduced << DeducedDecl->getDeclName() - << DT->getDeducedType() << D->getDeclName() - << DeducedDecl->getInit()->getSourceRange() - << D->getInit()->getSourceRange(); + << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced + << DeducedDecl->getDeclName() << DT->getDeducedType() + << D->getDeclName() << DeducedDecl->getInit()->getSourceRange() + << D->getInit()->getSourceRange(); D->setInvalidDecl(); break; } @@ -12411,9 +12473,7 @@ DeclGroupRef::Create(Context, Group.data(), Group.size())); } -void Sema::ActOnDocumentableDecl(Decl *D) { - ActOnDocumentableDecls(D); -} +void Sema::ActOnDocumentableDecl(Decl *D) { ActOnDocumentableDecls(D); } void Sema::ActOnDocumentableDecls(ArrayRef Group) { // Don't parse the comment if Doxygen diagnostics are ignored. @@ -12442,8 +12502,7 @@ // See if there are any new comments that are not attached to a decl. ArrayRef Comments = Context.getRawCommentList().getComments(); - if (!Comments.empty() && - !Comments.back()->isAttached()) { + if (!Comments.empty() && !Comments.back()->isAttached()) { // There is at least one comment that not attached to a decl. // Maybe it should be attached to one of these decls? // @@ -12467,7 +12526,7 @@ // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). if (D.getCXXScopeSpec().isSet()) { Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getRange(); } // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a @@ -12484,7 +12543,7 @@ case UnqualifiedIdKind::IK_ImplicitSelfParam: case UnqualifiedIdKind::IK_DeductionGuideName: Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) - << GetNameForDeclarator(D).getName(); + << GetNameForDeclarator(D).getName(); break; case UnqualifiedIdKind::IK_TemplateId: @@ -12509,10 +12568,10 @@ // In C++11, the 'register' storage class specifier is deprecated. // In C++17, it is not allowed, but we tolerate it as an extension. if (getLangOpts().CPlusPlus11) { - Diag(DS.getStorageClassSpecLoc(), - getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class - : diag::warn_deprecated_register) - << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); + Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus17 + ? diag::ext_register_storage_class + : diag::warn_deprecated_register) + << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); } } else if (getLangOpts().CPlusPlus && DS.getStorageClassSpec() == DeclSpec::SCS_auto) { @@ -12525,7 +12584,7 @@ if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); if (DS.isInlineSpecified()) Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) << getLangOpts().CPlusPlus17; @@ -12589,9 +12648,9 @@ if (D.getDeclSpec().isModulePrivateSpecified()) Diag(New->getLocation(), diag::err_module_private_local) - << 1 << New->getDeclName() - << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) - << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); + << 1 << New->getDeclName() + << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) + << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); if (New->hasAttr()) { Diag(New->getLocation(), diag::err_block_on_nonlocal); @@ -12602,14 +12661,13 @@ /// Synthesizes a variable for a parameter arising from a /// typedef. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, - SourceLocation Loc, - QualType T) { + SourceLocation Loc, QualType T) { /* FIXME: setting StartLoc == Loc. Would it be worth to modify callers so as to provide proper source location for the unnamed parameters, embedding the parameter's type? */ - ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, - T, Context.getTrivialTypeSourceInfo(T, Loc), - SC_None, nullptr); + ParmVarDecl *Param = ParmVarDecl::Create( + Context, DC, Loc, Loc, nullptr, T, + Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); Param->setImplicit(); return Param; } @@ -12624,7 +12682,7 @@ if (!Parameter->isReferenced() && Parameter->getDeclName() && !Parameter->hasAttr()) { Diag(Parameter->getLocation(), diag::warn_unused_parameter) - << Parameter->getDeclName(); + << Parameter->getDeclName(); } } } @@ -12662,8 +12720,7 @@ StorageClass SC) { // In ARC, infer a lifetime qualifier for appropriate parameter types. if (getLangOpts().ObjCAutoRefCount && - T.getObjCLifetime() == Qualifiers::OCL_None && - T->isObjCLifetimeType()) { + T.getObjCLifetime() == Qualifiers::OCL_None && T->isObjCLifetimeType()) { Qualifiers::ObjCLifetime lifetime; @@ -12673,8 +12730,7 @@ if (T->isArrayType()) { if (!T.isConstQualified()) { if (DelayedDiagnostics.shouldDelayDiagnostics()) - DelayedDiagnostics.add( - sema::DelayedDiagnostic::makeForbiddenType( + DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType( NameLoc, diag::err_arc_array_param_no_ownership, T, false)); else Diag(NameLoc, diag::err_arc_array_param_no_ownership) @@ -12704,9 +12760,8 @@ if (T->isObjCObjectType()) { SourceLocation TypeEndLoc = getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); - Diag(NameLoc, - diag::err_object_cannot_be_passed_returned_by_value) << 1 << T - << FixItHint::CreateInsertion(TypeEndLoc, "*"); + Diag(NameLoc, diag::err_object_cannot_be_passed_returned_by_value) + << 1 << T << FixItHint::CreateInsertion(TypeEndLoc, "*"); T = Context.getObjCObjectPointerType(T); New->setType(T); } @@ -12748,8 +12803,8 @@ // type. AttributeFactory attrs; DeclSpec DS(attrs); - const char* PrevSpec; // unused - unsigned DiagID; // unused + const char *PrevSpec; // unused + unsigned DiagID; // unused DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, DiagID, Context.getPrintingPolicy()); // Use the identifier location for the type source range. @@ -12819,8 +12874,8 @@ if (FD->isDeleted()) return false; - for (const FunctionDecl *Prev = FD->getPreviousDecl(); - Prev; Prev = Prev->getPreviousDecl()) { + for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; + Prev = Prev->getPreviousDecl()) { // Ignore any declarations that occur in function or method // scope, because they aren't visible from the header. if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) @@ -12833,10 +12888,9 @@ return true; } -void -Sema::CheckForFunctionRedefinition(FunctionDecl *FD, - const FunctionDecl *EffectiveDefinition, - SkipBodyInfo *SkipBody) { +void Sema::CheckForFunctionRedefinition(FunctionDecl *FD, + const FunctionDecl *EffectiveDefinition, + SkipBodyInfo *SkipBody) { const FunctionDecl *Definition = EffectiveDefinition; if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { // If this is a friend function defined in a class template, it does not @@ -12888,7 +12942,7 @@ "More than one definition in redeclaration chain"); if (D->getFriendObjectKind() != Decl::FOK_None) if (FunctionTemplateDecl *FT = - D->getInstantiatedFromMemberTemplate()) { + D->getInstantiatedFromMemberTemplate()) { if (FT->isThisDeclarationADefinition()) { Definition = D->getTemplatedDecl(); break; @@ -12913,14 +12967,13 @@ // a template, skip the new definition. if (SkipBody && !hasVisibleDefinition(Definition) && (Definition->getFormalLinkage() == InternalLinkage || - Definition->isInlined() || - Definition->getDescribedFunctionTemplate() || + Definition->isInlined() || Definition->getDescribedFunctionTemplate() || Definition->getNumTemplateParameterLists())) { SkipBody->ShouldSkip = true; - SkipBody->Previous = const_cast(Definition); + SkipBody->Previous = const_cast(Definition); if (auto *TD = Definition->getDescribedFunctionTemplate()) makeMergedDefinitionVisible(TD); - makeMergedDefinitionVisible(const_cast(Definition)); + makeMergedDefinitionVisible(const_cast(Definition)); return; } @@ -12935,8 +12988,7 @@ FD->setInvalidDecl(); } -static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, - Sema &S) { +static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S) { CXXRecordDecl *const LambdaClass = CallOperator->getParent(); LambdaScopeInfo *LSI = S.PushLambdaScope(); @@ -12966,11 +13018,12 @@ S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); QualType CaptureType = VD->getType(); const bool ByRef = C.getCaptureKind() == LCK_ByRef; - LSI->addCapture(VD, /*IsBlock*/false, ByRef, - /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), - /*EllipsisLoc*/C.isPackExpansion() - ? C.getEllipsisLoc() : SourceLocation(), - CaptureType, /*Invalid*/false); + LSI->addCapture(VD, /*IsBlock*/ false, ByRef, + /*RefersToEnclosingVariableOrCapture*/ true, + C.getLocation(), + /*EllipsisLoc*/ C.isPackExpansion() ? C.getEllipsisLoc() + : SourceLocation(), + CaptureType, /*Invalid*/ false); } else if (C.capturesThis()) { LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), @@ -13455,7 +13508,7 @@ if (!SuperD) return false; return SuperD->getIdentifier() == - NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); + NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); }; // Don't issue this warning for unavailable inits or direct subclasses // of NSObject. @@ -13499,8 +13552,7 @@ DiagnoseReturnInConstructorExceptionHandler(cast(Body)); // Verify that gotos and switch cases don't jump into scopes illegally. - if (getCurFunction()->NeedsScopeChecking() && - !PP.isCodeCompletionEnabled()) + if (getCurFunction()->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) DiagnoseInvalidJumps(Body); if (CXXDestructorDecl *Destructor = dyn_cast(dcl)) { @@ -13618,7 +13670,7 @@ if (ExternCPrev) { // We still need to inject the function into the enclosing block scope so // that later (non-call) uses can see it. - PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); + PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/ false); // C89 footnote 38: // If in fact it is not defined as having type "function returning int", @@ -13662,7 +13714,7 @@ CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, CCC, CTK_NonError))) diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), - /*ErrorRecovery*/false); + /*ErrorRecovery*/ false); } // Set a Declarator for the implicit definition: int foo(); @@ -13732,21 +13784,16 @@ if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) fmt = "NSString"; - FD->addAttr(FormatAttr::CreateImplicit(Context, - &Context.Idents.get(fmt), - FormatIdx+1, - HasVAListArg ? 0 : FormatIdx+2, - FD->getLocation())); + FD->addAttr(FormatAttr::CreateImplicit( + Context, &Context.Idents.get(fmt), FormatIdx + 1, + HasVAListArg ? 0 : FormatIdx + 2, FD->getLocation())); } } - if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, - HasVAListArg)) { - if (!FD->hasAttr()) - FD->addAttr(FormatAttr::CreateImplicit(Context, - &Context.Idents.get("scanf"), - FormatIdx+1, - HasVAListArg ? 0 : FormatIdx+2, - FD->getLocation())); + if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, HasVAListArg)) { + if (!FD->hasAttr()) + FD->addAttr(FormatAttr::CreateImplicit( + Context, &Context.Idents.get("scanf"), FormatIdx + 1, + HasVAListArg ? 0 : FormatIdx + 2, FD->getLocation())); } // Handle automatically recognized callbacks. @@ -13785,8 +13832,7 @@ if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && !FD->hasAttr()) - FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, - FD->getLocation())); + FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, FD->getLocation())); if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr()) FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr()) @@ -13819,11 +13865,10 @@ IdentifierInfo *Name = FD->getIdentifier(); if (!Name) return; - if ((!getLangOpts().CPlusPlus && - FD->getDeclContext()->isTranslationUnit()) || + if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || (isa(FD->getDeclContext()) && cast(FD->getDeclContext())->getLanguage() == - LinkageSpecDecl::lang_c)) { + LinkageSpecDecl::lang_c)) { // Okay: this could be a libc/libm/Objective-C function we know // about. } else @@ -13833,10 +13878,9 @@ // FIXME: asprintf and vasprintf aren't C99 functions. Should they be // target-specific builtins, perhaps? if (!FD->hasAttr()) - FD->addAttr(FormatAttr::CreateImplicit(Context, - &Context.Idents.get("printf"), 2, - Name->isStr("vasprintf") ? 0 : 3, - FD->getLocation())); + FD->addAttr(FormatAttr::CreateImplicit( + Context, &Context.Idents.get("printf"), 2, + Name->isStr("vasprintf") ? 0 : 3, FD->getLocation())); } if (Name->isStr("__CFStringMakeConstantString")) { @@ -13872,9 +13916,10 @@ if (D.getDeclSpec().isModulePrivateSpecified()) { if (CurContext->isFunctionOrMethod()) Diag(NewTD->getLocation(), diag::err_module_private_local) - << 2 << NewTD->getDeclName() - << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) - << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); + << 2 << NewTD->getDeclName() + << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) + << FixItHint::CreateRemoval( + D.getDeclSpec().getModulePrivateSpecLoc()); else NewTD->setModulePrivate(); } @@ -13925,8 +13970,7 @@ QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev) { if (IsScoped != Prev->isScoped()) { - Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) - << Prev->isScoped(); + Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) << Prev->isScoped(); Diag(Prev->getLocation(), diag::note_previous_declaration); return true; } @@ -13938,14 +13982,13 @@ Prev->getIntegerType())) { // TODO: Highlight the underlying type of the redeclaration. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) - << EnumUnderlyingTy << Prev->getIntegerType(); + << EnumUnderlyingTy << Prev->getIntegerType(); Diag(Prev->getLocation(), diag::note_previous_declaration) << Prev->getIntegerTypeRange(); return true; } } else if (IsFixed != Prev->isFixed()) { - Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) - << Prev->isFixed(); + Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) << Prev->isFixed(); Diag(Prev->getLocation(), diag::note_previous_declaration); return true; } @@ -13960,10 +14003,14 @@ /// \returns diagnostic %select index. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { switch (Tag) { - case TTK_Struct: return 0; - case TTK_Interface: return 1; - case TTK_Class: return 2; - default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); + case TTK_Struct: + return 0; + case TTK_Interface: + return 1; + case TTK_Class: + return 2; + default: + llvm_unreachable("Invalid tag kind for redecl diagnostic!"); } } @@ -13971,8 +14018,7 @@ /// class for redeclaration (class, struct, or __interface). /// /// \returns true iff the tag kind is compatible. -static bool isClassCompatTagKind(TagTypeKind Tag) -{ +static bool isClassCompatTagKind(TagTypeKind Tag) { return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; } @@ -14063,8 +14109,8 @@ // In a template instantiation, do not offer fix-its for tag mismatches // since they usually mess up the template instead of fixing the problem. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) - << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name - << getRedeclDiagFromTagKind(OldTag); + << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name + << getRedeclDiagFromTagKind(OldTag); // FIXME: Note previous location? } return true; @@ -14088,13 +14134,14 @@ if (!previousMismatch) { previousMismatch = true; Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) - << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name - << getRedeclDiagFromTagKind(I->getTagKind()); + << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name + << getRedeclDiagFromTagKind(I->getTagKind()); } Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) - << getRedeclDiagFromTagKind(NewTag) - << FixItHint::CreateReplacement(I->getInnerLocStart(), - TypeWithKeyword::getTagTypeKindName(NewTag)); + << getRedeclDiagFromTagKind(NewTag) + << FixItHint::CreateReplacement( + I->getInnerLocStart(), + TypeWithKeyword::getTagTypeKindName(NewTag)); } } return true; @@ -14109,16 +14156,17 @@ const TagDecl *Redecl = PrevDef ? PrevDef : Previous; if (Redecl->getTagKind() != NewTag) { Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) - << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name - << getRedeclDiagFromTagKind(OldTag); + << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name + << getRedeclDiagFromTagKind(OldTag); Diag(Redecl->getLocation(), diag::note_previous_use); // If there is a previous definition, suggest a fix-it. if (PrevDef) { Diag(NewTagLoc, diag::note_struct_class_suggestion) - << getRedeclDiagFromTagKind(Redecl->getTagKind()) - << FixItHint::CreateReplacement(SourceRange(NewTagLoc), - TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); + << getRedeclDiagFromTagKind(Redecl->getTagKind()) + << FixItHint::CreateReplacement( + SourceRange(NewTagLoc), + TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); } } @@ -14254,7 +14302,7 @@ } else { // The "template<>" header is extraneous. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) - << TypeWithKeyword::getTagTypeKindName(Kind) << Name; + << TypeWithKeyword::getTagTypeKindName(Kind) << Name; isMemberSpecialization = true; } } @@ -14263,7 +14311,7 @@ // Figure out the underlying type if this a enum declaration. We need to do // this early, because it's needed to detect if this is an incompatible // redeclaration. - llvm::PointerUnion EnumUnderlying; + llvm::PointerUnion EnumUnderlying; bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; if (Kind == TTK_Enum) { @@ -14376,7 +14424,7 @@ DC = computeDeclContext(SS, true); if (!DC) { Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) - << SS.getRange(); + << SS.getRange(); return nullptr; } } @@ -14406,7 +14454,7 @@ // A tag 'foo::bar' must already exist. Diag(NameLoc, diag::err_not_tag_in_scope) - << Kind << Name << DC << SS.getRange(); + << Kind << Name << DC << SS.getRange(); Name = nullptr; Invalid = true; goto CreateNewDecl; @@ -14526,7 +14574,8 @@ // there's a shadow friend decl. if (Name && Previous.empty() && (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { - if (Invalid) goto CreateNewDecl; + if (Invalid) + goto CreateNewDecl; assert(SS.isEmpty()); if (TUK == TUK_Reference || IsTemplateParamOrArg) { @@ -14608,8 +14657,8 @@ if (const TagType *TT = TD->getUnderlyingType()->getAs()) { TagDecl *Tag = TT->getDecl(); if (Tag->getDeclName() == Name && - Tag->getDeclContext()->getRedeclContext() - ->Equals(TD->getDeclContext()->getRedeclContext())) { + Tag->getDeclContext()->getRedeclContext()->Equals( + TD->getDeclContext()->getRedeclContext())) { PrevDecl = Tag; Previous.clear(); Previous.addDecl(Tag); @@ -14631,8 +14680,7 @@ Diag(KWLoc, diag::err_using_decl_conflict_reverse); Diag(Shadow->getTargetDecl()->getLocation(), diag::note_using_decl_target); - Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) - << 0; + Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; // Recover by ignoring the old declaration. Previous.clear(); goto CreateNewDecl; @@ -14649,16 +14697,14 @@ // Make sure that this wasn't declared as an enum and now used as a // struct or something similar. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, - TUK == TUK_Definition, KWLoc, - Name)) { - bool SafeToContinue - = (PrevTagDecl->getTagKind() != TTK_Enum && - Kind != TTK_Enum); + TUK == TUK_Definition, KWLoc, Name)) { + bool SafeToContinue = + (PrevTagDecl->getTagKind() != TTK_Enum && Kind != TTK_Enum); if (SafeToContinue) Diag(KWLoc, diag::err_use_with_wrong_tag) - << Name - << FixItHint::CreateReplacement(SourceRange(KWLoc), - PrevTagDecl->getKindName()); + << Name + << FixItHint::CreateReplacement(SourceRange(KWLoc), + PrevTagDecl->getKindName()); else Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; Diag(PrevTagDecl->getLocation(), diag::note_previous_use); @@ -14681,23 +14727,23 @@ if (TUK == TUK_Reference || TUK == TUK_Friend) { if (ScopedEnum) Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) - << PrevEnum->isScoped() - << FixItHint::CreateRemoval(ScopedEnumKWLoc); + << PrevEnum->isScoped() + << FixItHint::CreateRemoval(ScopedEnumKWLoc); return PrevTagDecl; } QualType EnumUnderlyingTy; - if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast()) + if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast()) EnumUnderlyingTy = TI->getType().getUnqualifiedType(); - else if (const Type *T = EnumUnderlying.dyn_cast()) + else if (const Type *T = EnumUnderlying.dyn_cast()) EnumUnderlyingTy = QualType(T, 0); // All conflicts with previous declarations are recovered by // returning the previous declaration, unless this is a definition, // in which case we want the caller to bail out. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, - ScopedEnum, EnumUnderlyingTy, - IsFixed, PrevEnum)) + ScopedEnum, EnumUnderlyingTy, IsFixed, + PrevEnum)) return TUK == TUK_Declaration ? PrevTagDecl : nullptr; } @@ -14730,7 +14776,8 @@ // the declaration would have meant the same thing if no prior // declaration were found, that is, if it was found in the same // scope where we would have injected a declaration. - if (!getTagInjectionContext(CurContext)->getRedeclContext() + if (!getTagInjectionContext(CurContext) + ->getRedeclContext() ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) return PrevTagDecl; // This is in the injected scope, create a new declaration in @@ -14751,12 +14798,12 @@ if (isMemberSpecialization) { if (CXXRecordDecl *RD = dyn_cast(Def)) IsExplicitSpecializationAfterInstantiation = - RD->getTemplateSpecializationKind() != - TSK_ExplicitSpecialization; + RD->getTemplateSpecializationKind() != + TSK_ExplicitSpecialization; else if (EnumDecl *ED = dyn_cast(Def)) IsExplicitSpecializationAfterInstantiation = - ED->getTemplateSpecializationKind() != - TSK_ExplicitSpecialization; + ED->getTemplateSpecializationKind() != + TSK_ExplicitSpecialization; } // Note that clang allows ODR-like semantics for ObjC/C, i.e., do @@ -14841,9 +14888,9 @@ // is non-NULL, it's a definition of the tag declared by // PrevDecl. If it's NULL, we have a new definition. - // Otherwise, PrevDecl is not a tag, but was found with tag - // lookup. This is only actually possible in C++, where a few - // things like templates still live in the tag namespace. + // Otherwise, PrevDecl is not a tag, but was found with tag + // lookup. This is only actually possible in C++, where a few + // things like templates still live in the tag namespace. } else { // Use a better diagnostic if an elaborated-type-specifier // found the wrong kind of type on the first @@ -14851,34 +14898,35 @@ if ((TUK == TUK_Reference || TUK == TUK_Friend) && !Previous.isForRedeclaration()) { NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); - Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK - << Kind; + Diag(NameLoc, diag::err_tag_reference_non_tag) + << PrevDecl << NTK << Kind; Diag(PrevDecl->getLocation(), diag::note_declared_at); Invalid = true; - // Otherwise, only diagnose if the declaration is in scope. + // Otherwise, only diagnose if the declaration is in scope. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, SS.isNotEmpty() || isMemberSpecialization)) { // do nothing - // Diagnose implicit declarations introduced by elaborated types. + // Diagnose implicit declarations introduced by elaborated types. } else if (TUK == TUK_Reference || TUK == TUK_Friend) { NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; Invalid = true; - // Otherwise it's a declaration. Call out a particularly common - // case here. + // Otherwise it's a declaration. Call out a particularly common + // case here. } else if (TypedefNameDecl *TND = dyn_cast(PrevDecl)) { unsigned Kind = 0; - if (isa(PrevDecl)) Kind = 1; + if (isa(PrevDecl)) + Kind = 1; Diag(NameLoc, diag::err_tag_definition_of_typedef) - << Name << Kind << TND->getUnderlyingType(); + << Name << Kind << TND->getUnderlyingType(); Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; Invalid = true; - // Otherwise, diagnose. + // Otherwise, diagnose. } else { // The tag name clashes with something else in the target scope, // issue an error and recover by making this tag be anonymous. @@ -14926,10 +14974,9 @@ if (IsFixed && cast(New)->isFixed()) { // C++0x: 7.2p2: opaque-enum-declaration. // Conflicts are diagnosed above. Do nothing. - } - else if (PrevDecl && (Def = cast(PrevDecl)->getDefinition())) { - Diag(Loc, diag::ext_forward_ref_enum_def) - << New; + } else if (PrevDecl && + (Def = cast(PrevDecl)->getDefinition())) { + Diag(Loc, diag::ext_forward_ref_enum_def) << New; Diag(Def->getLocation(), diag::note_previous_definition); } else { unsigned DiagID = diag::ext_forward_ref_enum; @@ -14943,10 +14990,10 @@ if (EnumUnderlying) { EnumDecl *ED = cast(New); - if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast()) + if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast()) ED->setIntegerTypeSourceInfo(TI); else - ED->setIntegerType(QualType(EnumUnderlying.get(), 0)); + ED->setIntegerType(QualType(EnumUnderlying.get(), 0)); ED->setPromotionType(ED->getIntegerType()); assert(ED->isComplete() && "enum with type should be complete"); } @@ -14972,14 +15019,14 @@ if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) { Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) - << Context.getTagDeclType(New); + << Context.getTagDeclType(New); Invalid = true; } if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) { Diag(New->getLocation(), diag::err_type_defined_in_enum) - << Context.getTagDeclType(New); + << Context.getTagDeclType(New); Invalid = true; } @@ -14997,8 +15044,7 @@ if (TemplateParameterLists.size() > 0) { New->setTemplateParameterListsInfo(Context, TemplateParameterLists); } - } - else + } else Invalid = true; } @@ -15021,8 +15067,7 @@ if (ModulePrivateLoc.isValid()) { if (isMemberSpecialization) Diag(New->getLocation(), diag::err_module_private_specialization) - << 2 - << FixItHint::CreateRemoval(ModulePrivateLoc); + << 2 << FixItHint::CreateRemoval(ModulePrivateLoc); // __module_private__ does not apply to local classes. However, we only // diagnose this as an error when the declaration specifiers are // freestanding. Here, we just ignore the __module_private__. @@ -15044,8 +15089,7 @@ // C++ [dcl.fct]p6: // Types shall not be defined in return or parameter types. if (TUK == TUK_Definition && !IsTypeSpecifier) { - Diag(Loc, diag::err_type_defined_in_param_type) - << Name; + Diag(Loc, diag::err_type_defined_in_param_type) << Name; Invalid = true; } } else if (!PrevDecl) { @@ -15159,7 +15203,8 @@ assert(isa(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); DeclContext *OCD = cast(IDecl); - assert(getContainingDC(OCD) == CurContext && + assert( + getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one."); CurContext = OCD; return IDecl; @@ -15179,7 +15224,7 @@ if (FinalLoc.isValid()) Record->addAttr(new (Context) - FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); + FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); // C++ [class]p2: // [...] The class-name is also inserted into the scope of the @@ -15195,7 +15240,7 @@ InjectedClassName->setImplicit(); InjectedClassName->setAccess(AS_public); if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) - InjectedClassName->setDescribedClassTemplate(Template); + InjectedClassName->setDescribedClassTemplate(Template); PushOnScopeChains(InjectedClassName, S); assert(InjectedClassName->isInjectedClassName() && "Broken injected-class-name"); @@ -15266,9 +15311,9 @@ // Note that FieldName may be null for anonymous bitfields. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, - IdentifierInfo *FieldName, - QualType FieldTy, bool IsMsStruct, - Expr *BitWidth, bool *ZeroWidth) { + IdentifierInfo *FieldName, QualType FieldTy, + bool IsMsStruct, Expr *BitWidth, + bool *ZeroWidth) { // Default to true; that shouldn't confuse checks for emptiness if (ZeroWidth) *ZeroWidth = true; @@ -15281,9 +15326,9 @@ return ExprError(); if (FieldName) return Diag(FieldLoc, diag::err_not_integral_type_bitfield) - << FieldName << FieldTy << BitWidth->getSourceRange(); + << FieldName << FieldTy << BitWidth->getSourceRange(); return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) - << FieldTy << BitWidth->getSourceRange(); + << FieldTy << BitWidth->getSourceRange(); } else if (DiagnoseUnexpandedParameterPack(const_cast(BitWidth), UPPC_BitFieldWidth)) return ExprError(); @@ -15309,9 +15354,9 @@ if (Value.isSigned() && Value.isNegative()) { if (FieldName) return Diag(FieldLoc, diag::err_bitfield_has_negative_width) - << FieldName << Value.toString(10); + << FieldName << Value.toString(10); return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) - << Value.toString(10); + << Value.toString(10); } if (!FieldTy->isDependentType()) { @@ -15360,8 +15405,8 @@ /// to create a FieldDecl object for it. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth) { - FieldDecl *Res = HandleField(S, cast_or_null(TagD), - DeclStart, D, static_cast(BitfieldWidth), + FieldDecl *Res = HandleField(S, cast_or_null(TagD), DeclStart, D, + static_cast(BitfieldWidth), /*InitStyle=*/ICIS_NoInit, AS_public); return Res; } @@ -15369,20 +15414,20 @@ /// HandleField - Analyze a field of a C struct or a C++ data member. /// FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, - SourceLocation DeclStart, - Declarator &D, Expr *BitWidth, - InClassInitStyle InitStyle, + SourceLocation DeclStart, Declarator &D, + Expr *BitWidth, InClassInitStyle InitStyle, AccessSpecifier AS) { if (D.isDecompositionDeclarator()) { const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) - << Decomp.getSourceRange(); + << Decomp.getSourceRange(); return nullptr; } IdentifierInfo *II = D.getIdentifier(); SourceLocation Loc = DeclStart; - if (II) Loc = D.getIdentifierLoc(); + if (II) + Loc = D.getIdentifierLoc(); TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); QualType T = TInfo->getType(); @@ -15405,7 +15450,7 @@ if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), diag::err_invalid_thread) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); // Check to see if this name was declared as a member previously NamedDecl *PrevDecl = nullptr; @@ -15413,19 +15458,19 @@ ForVisibleRedeclaration); LookupName(Previous, S); switch (Previous.getResultKind()) { - case LookupResult::Found: - case LookupResult::FoundUnresolvedValue: - PrevDecl = Previous.getAsSingle(); - break; + case LookupResult::Found: + case LookupResult::FoundUnresolvedValue: + PrevDecl = Previous.getAsSingle(); + break; - case LookupResult::FoundOverloaded: - PrevDecl = Previous.getRepresentativeDecl(); - break; + case LookupResult::FoundOverloaded: + PrevDecl = Previous.getRepresentativeDecl(); + break; - case LookupResult::NotFound: - case LookupResult::NotFoundInCurrentInstantiation: - case LookupResult::Ambiguous: - break; + case LookupResult::NotFound: + case LookupResult::NotFoundInCurrentInstantiation: + case LookupResult::Ambiguous: + break; } Previous.suppressDiagnostics(); @@ -15439,11 +15484,11 @@ if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) PrevDecl = nullptr; - bool Mutable - = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); + bool Mutable = + (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); SourceLocation TSSL = D.getBeginLoc(); - FieldDecl *NewFD - = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, + FieldDecl *NewFD = + CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, TSSL, AS, PrevDecl, &D); if (NewFD->isInvalidDecl()) @@ -15474,16 +15519,15 @@ /// /// \todo The Declarator argument is a hack. It will be removed once FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, - TypeSourceInfo *TInfo, - RecordDecl *Record, SourceLocation Loc, - bool Mutable, Expr *BitWidth, - InClassInitStyle InitStyle, - SourceLocation TSSL, - AccessSpecifier AS, NamedDecl *PrevDecl, - Declarator *D) { + TypeSourceInfo *TInfo, RecordDecl *Record, + SourceLocation Loc, bool Mutable, + Expr *BitWidth, InClassInitStyle InitStyle, + SourceLocation TSSL, AccessSpecifier AS, + NamedDecl *PrevDecl, Declarator *D) { IdentifierInfo *II = Name.getAsIdentifierInfo(); bool InvalidDecl = false; - if (D) InvalidDecl = D->isInvalidType(); + if (D) + InvalidDecl = D->isInvalidType(); // If we receive a broken type, recover by assuming 'int' and // marking this declaration as invalid. @@ -15545,10 +15589,8 @@ bool SizeIsNegative; llvm::APSInt Oversized; - TypeSourceInfo *FixedTInfo = - TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, - SizeIsNegative, - Oversized); + TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( + TInfo, Context, SizeIsNegative, Oversized); if (FixedTInfo) { Diag(Loc, diag::warn_illegal_constant_array_size); TInfo = FixedTInfo; @@ -15557,8 +15599,7 @@ if (SizeIsNegative) Diag(Loc, diag::err_typecheck_negative_array_size); else if (Oversized.getBoolValue()) - Diag(Loc, diag::err_array_too_large) - << Oversized.toString(10); + Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); else Diag(Loc, diag::err_typecheck_field_variable_size); InvalidDecl = true; @@ -15566,9 +15607,9 @@ } // Fields can not have abstract class types - if (!InvalidDecl && RequireNonAbstractType(Loc, T, - diag::err_abstract_type_in_decl, - AbstractFieldType)) + if (!InvalidDecl && + RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl, + AbstractFieldType)) InvalidDecl = true; bool ZeroWidth = false; @@ -15577,7 +15618,8 @@ // If this is declared as a bit-field, check the bit-field. if (BitWidth) { BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, - &ZeroWidth).get(); + &ZeroWidth) + .get(); if (!BitWidth) { InvalidDecl = true; BitWidth = nullptr; @@ -15626,7 +15668,7 @@ if (!InvalidDecl && getLangOpts().CPlusPlus) { if (Record->isUnion()) { if (const RecordType *RT = EltTy->getAs()) { - CXXRecordDecl* RDecl = cast(RT->getDecl()); + CXXRecordDecl *RDecl = cast(RT->getDecl()); if (RDecl->getDefinition()) { // C++ [class.union]p1: An object of a class with a non-trivial // constructor, a non-trivial copy constructor, a non-trivial @@ -15642,10 +15684,11 @@ // the program is ill-formed, except when compiling with MSVC extensions // enabled. if (EltTy->isReferenceType()) { - Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? - diag::ext_union_member_of_reference_type : - diag::err_union_member_of_reference_type) - << NewFD->getDeclName() << EltTy; + Diag(NewFD->getLocation(), + getLangOpts().MicrosoftExt + ? diag::ext_union_member_of_reference_type + : diag::err_union_member_of_reference_type) + << NewFD->getDeclName() << EltTy; if (!getLangOpts().MicrosoftExt) NewFD->setInvalidDecl(); } @@ -15705,8 +15748,8 @@ member = CXXDestructor; if (member != CXXInvalid) { - if (!getLangOpts().CPlusPlus11 && - getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { + if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount && + RDecl->hasObjectMember()) { // Objective-C++ ARC: it is an error to have a non-trivial field of // a union. However, system headers in Objective-C programs // occasionally have Objective-C lifetime objects within unions, @@ -15715,16 +15758,18 @@ SourceLocation Loc = FD->getLocation(); if (getSourceManager().isInSystemHeader(Loc)) { if (!FD->hasAttr()) - FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", - UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); + FD->addAttr(UnavailableAttr::CreateImplicit( + Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); return false; } } - Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? - diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : - diag::err_illegal_union_or_anon_struct_member) - << FD->getParent()->isUnion() << FD->getDeclName() << member; + Diag( + FD->getLocation(), + getLangOpts().CPlusPlus11 + ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member + : diag::err_illegal_union_or_anon_struct_member) + << FD->getParent()->isUnion() << FD->getDeclName() << member; DiagnoseNontrivial(RDecl, member); return !getLangOpts().CPlusPlus11; } @@ -15739,25 +15784,29 @@ static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { switch (ivarVisibility) { - default: llvm_unreachable("Unknown visitibility kind"); - case tok::objc_private: return ObjCIvarDecl::Private; - case tok::objc_public: return ObjCIvarDecl::Public; - case tok::objc_protected: return ObjCIvarDecl::Protected; - case tok::objc_package: return ObjCIvarDecl::Package; + default: + llvm_unreachable("Unknown visitibility kind"); + case tok::objc_private: + return ObjCIvarDecl::Private; + case tok::objc_public: + return ObjCIvarDecl::Public; + case tok::objc_protected: + return ObjCIvarDecl::Protected; + case tok::objc_package: + return ObjCIvarDecl::Package; } } /// ActOnIvar - Each ivar field of an objective-c class is passed into this /// in order to create an IvarDecl object for it. -Decl *Sema::ActOnIvar(Scope *S, - SourceLocation DeclStart, - Declarator &D, Expr *BitfieldWidth, - tok::ObjCKeywordKind Visibility) { +Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, + Expr *BitfieldWidth, tok::ObjCKeywordKind Visibility) { IdentifierInfo *II = D.getIdentifier(); - Expr *BitWidth = (Expr*)BitfieldWidth; + Expr *BitWidth = (Expr *)BitfieldWidth; SourceLocation Loc = DeclStart; - if (II) Loc = D.getIdentifierLoc(); + if (II) + Loc = D.getIdentifierLoc(); // FIXME: Unnamed fields can be handled in various different ways, for // example, unnamed unions inject all members into the struct namespace! @@ -15767,14 +15816,13 @@ if (BitWidth) { // 6.7.2.1p3, 6.7.2.1p4 - BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); + BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/ false, BitWidth).get(); if (!BitWidth) D.setInvalidType(); } else { // Not a bitfield. // validate II. - } if (T->isReferenceType()) { Diag(Loc, diag::err_ivar_reference_type); @@ -15788,26 +15836,25 @@ } // Get the visibility (access control) for this ivar. - ObjCIvarDecl::AccessControl ac = - Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) - : ObjCIvarDecl::None; + ObjCIvarDecl::AccessControl ac = Visibility != tok::objc_not_keyword + ? TranslateIvarVisibility(Visibility) + : ObjCIvarDecl::None; // Must set ivar's DeclContext to its enclosing interface. ObjCContainerDecl *EnclosingDecl = cast(CurContext); if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) return nullptr; ObjCContainerDecl *EnclosingContext; if (ObjCImplementationDecl *IMPDecl = - dyn_cast(EnclosingDecl)) { + dyn_cast(EnclosingDecl)) { if (LangOpts.ObjCRuntime.isFragile()) { - // Case of ivar declared in an implementation. Context is that of its class. + // Case of ivar declared in an implementation. Context is that of its + // class. EnclosingContext = IMPDecl->getClassInterface(); assert(EnclosingContext && "Implementation has no class interface!"); - } - else + } else EnclosingContext = EnclosingDecl; } else { - if (ObjCCategoryDecl *CDecl = - dyn_cast(EnclosingDecl)) { + if (ObjCCategoryDecl *CDecl = dyn_cast(EnclosingDecl)) { if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); return nullptr; @@ -15817,15 +15864,15 @@ } // Construct the decl. - ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, - DeclStart, Loc, II, T, - TInfo, ac, (Expr *)BitfieldWidth); + ObjCIvarDecl *NewID = + ObjCIvarDecl::Create(Context, EnclosingContext, DeclStart, Loc, II, T, + TInfo, ac, (Expr *)BitfieldWidth); if (II) { - NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, - ForVisibleRedeclaration); - if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) - && !isa(PrevDecl)) { + NamedDecl *PrevDecl = + LookupSingleName(S, II, Loc, LookupMemberName, ForVisibleRedeclaration); + if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) && + !isa(PrevDecl)) { Diag(Loc, diag::err_duplicate_member) << II; Diag(PrevDecl->getLocation(), diag::note_previous_declaration); NewID->setInvalidDecl(); @@ -15852,8 +15899,8 @@ IdResolver.AddDecl(NewID); } - if (LangOpts.ObjCRuntime.isNonFragile() && - !NewID->isInvalidDecl() && isa(EnclosingDecl)) + if (LangOpts.ObjCRuntime.isNonFragile() && !NewID->isInvalidDecl() && + isa(EnclosingDecl)) Diag(Loc, diag::warn_ivars_in_interface); return NewID; @@ -15868,7 +15915,7 @@ if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) return; - Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; + Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size() - 1]; ObjCIvarDecl *Ivar = cast(ivarDecl); if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) @@ -15885,15 +15932,12 @@ } // All conditions are met. Add a new bitfield to the tail end of ivars. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); - Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); - - Ivar = ObjCIvarDecl::Create(Context, cast(CurContext), - DeclLoc, DeclLoc, nullptr, - Context.CharTy, - Context.getTrivialTypeSourceInfo(Context.CharTy, - DeclLoc), - ObjCIvarDecl::Private, BW, - true); + Expr *BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); + + Ivar = ObjCIvarDecl::Create( + Context, cast(CurContext), DeclLoc, DeclLoc, nullptr, + Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc), + ObjCIvarDecl::Private, BW, true); AllIvarDecls.push_back(Ivar); } @@ -15909,13 +15953,14 @@ if (!Fields.empty() && isa(EnclosingDecl)) { ObjCContainerDecl *DC = cast(EnclosingDecl); switch (DC->getKind()) { - default: break; + default: + break; case Decl::ObjCCategory: Context.ResetObjCLayout(cast(DC)->getClassInterface()); break; case Decl::ObjCImplementation: - Context. - ResetObjCLayout(cast(DC)->getClassInterface()); + Context.ResetObjCLayout( + cast(DC)->getClassInterface()); break; } } @@ -15935,7 +15980,7 @@ } // Verify that all the fields are okay. - SmallVector RecFields; + SmallVector RecFields; bool ObjCFieldLifetimeErrReported = false; for (ArrayRef::iterator i = Fields.begin(), end = Fields.end(); @@ -15971,7 +16016,7 @@ if (FDTy->isFunctionType()) { // Field declared as a function. Diag(FD->getLocation(), diag::err_field_declared_as_function) - << FD->getDeclName(); + << FD->getDeclName(); FD->setInvalidDecl(); EnclosingDecl->setInvalidDecl(); continue; @@ -15985,7 +16030,7 @@ unsigned DiagID = 0; if (!Record->isUnion() && !IsLastField) { Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) - << FD->getDeclName() << FD->getType() << Record->getTagKind(); + << FD->getDeclName() << FD->getType() << Record->getTagKind(); Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); FD->setInvalidDecl(); EnclosingDecl->setInvalidDecl(); @@ -16004,8 +16049,8 @@ : diag::err_flexible_array_empty_aggregate; if (DiagID) - Diag(FD->getLocation(), DiagID) << FD->getDeclName() - << Record->getTagKind(); + Diag(FD->getLocation(), DiagID) + << FD->getDeclName() << Record->getTagKind(); // While the layout of types that contain virtual bases is not specified // by the C++ standard, both the Itanium and Microsoft C++ ABIs place // virtual bases after the derived members. This would make a flexible @@ -16016,7 +16061,7 @@ << FD->getDeclName() << Record->getTagKind(); if (!getLangOpts().C99) Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) - << FD->getDeclName() << Record->getTagKind(); + << FD->getDeclName() << Record->getTagKind(); // If the element type has a non-trivial destructor, we would not // implicitly destroy the elements, so disallow it for now. @@ -16026,7 +16071,7 @@ QualType BaseElem = Context.getBaseElementType(FD->getType()); if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) - << FD->getDeclName() << FD->getType(); + << FD->getDeclName() << FD->getType(); FD->setInvalidDecl(); EnclosingDecl->setInvalidDecl(); continue; @@ -16056,12 +16101,12 @@ // structures. if (!IsLastField) Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) - << FD->getDeclName() << FD->getType(); + << FD->getDeclName() << FD->getType(); else { // We support flexible arrays at the end of structs in // other structs as an extension. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) - << FD->getDeclName(); + << FD->getDeclName(); } } } @@ -16078,12 +16123,11 @@ Record->setHasVolatileMember(true); if (Record && Record->isUnion() && FD->getType().isNonTrivialPrimitiveCType(Context)) - Diag(FD->getLocation(), - diag::err_nontrivial_primitive_type_in_union); + Diag(FD->getLocation(), diag::err_nontrivial_primitive_type_in_union); } else if (FDTy->isObjCObjectType()) { /// A field cannot be an Objective-c object Diag(FD->getLocation(), diag::err_statically_allocated_object) - << FixItHint::CreateInsertion(FD->getLocation(), "*"); + << FixItHint::CreateInsertion(FD->getLocation(), "*"); QualType T = Context.getObjCObjectPointerType(FD->getType()); FD->setType(T); } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && @@ -16099,18 +16143,18 @@ SourceLocation loc = FD->getLocation(); if (getSourceManager().isInSystemHeader(loc)) { if (!FD->hasAttr()) { - FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", - UnavailableAttr::IR_ARCFieldWithOwnership, loc)); + FD->addAttr(UnavailableAttr::CreateImplicit( + Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, loc)); } } else { Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) - << T->isBlockPointerType() << Record->getTagKind(); + << T->isBlockPointerType() << Record->getTagKind(); } ObjCFieldLifetimeErrReported = true; } } else if (getLangOpts().ObjC && - getLangOpts().getGC() != LangOptions::NonGC && - Record && !Record->hasObjectMember()) { + getLangOpts().getGC() != LangOptions::NonGC && Record && + !Record->hasObjectMember()) { if (FD->getType()->isObjCObjectPointerType() || FD->getType().isObjCGCStrong()) Record->setHasObjectMember(true); @@ -16121,7 +16165,7 @@ Record->setHasObjectMember(true); else if (BaseType->isObjCObjectPointerType() || BaseType.isObjCGCStrong()) - Record->setHasObjectMember(true); + Record->setHasObjectMember(true); } } @@ -16159,8 +16203,9 @@ if (!CXXRecord->isInvalidDecl()) { // Set access bits correctly on the directly-declared conversions. for (CXXRecordDecl::conversion_iterator - I = CXXRecord->conversion_begin(), - E = CXXRecord->conversion_end(); I != E; ++I) + I = CXXRecord->conversion_begin(), + E = CXXRecord->conversion_end(); + I != E; ++I) I.setAccess((*I)->getAccess()); } @@ -16177,10 +16222,10 @@ CXXRecord->getFinalOverriders(FinalOverriders); for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), - MEnd = FinalOverriders.end(); + MEnd = FinalOverriders.end(); M != MEnd; ++M) { for (OverridingMethods::iterator SO = M->second.begin(), - SOEnd = M->second.end(); + SOEnd = M->second.end(); SO != SOEnd; ++SO) { assert(SO->second.size() > 0 && "Virtual function without overriding functions?"); @@ -16192,15 +16237,15 @@ // class subobject has more than one final overrider the // program is ill-formed. Diag(Record->getLocation(), diag::err_multiple_final_overriders) - << (const NamedDecl *)M->first << Record; + << (const NamedDecl *)M->first << Record; Diag(M->first->getLocation(), diag::note_overridden_virtual_function); for (OverridingMethods::overriding_iterator - OM = SO->second.begin(), - OMEnd = SO->second.end(); + OM = SO->second.begin(), + OMEnd = SO->second.end(); OM != OMEnd; ++OM) Diag(OM->Method->getLocation(), diag::note_final_overrider) - << (const NamedDecl *)M->first << OM->Method->getParent(); + << (const NamedDecl *)M->first << OM->Method->getParent(); Record->setInvalidDecl(); } @@ -16248,8 +16293,7 @@ CXXRecordDecl *CXXRecord = cast(Record); CheckForZeroSize = CXXRecord->getLexicalDeclContext()->isExternCContext() && - !CXXRecord->isDependentType() && - CXXRecord->isCLike(); + !CXXRecord->isDependentType() && CXXRecord->isCLike(); } if (CheckForZeroSize) { bool ZeroSize = true; @@ -16275,23 +16319,23 @@ // allowed in C++, but warn if its declaration is inside // extern "C" block. if (ZeroSize) { - Diag(RecLoc, getLangOpts().CPlusPlus ? - diag::warn_zero_size_struct_union_in_extern_c : - diag::warn_zero_size_struct_union_compat) - << IsEmpty << Record->isUnion() << (NonBitFields > 1); + Diag(RecLoc, getLangOpts().CPlusPlus + ? diag::warn_zero_size_struct_union_in_extern_c + : diag::warn_zero_size_struct_union_compat) + << IsEmpty << Record->isUnion() << (NonBitFields > 1); } // Structs without named members are extension in C (C99 6.7.2.1p7), // but are accepted by GCC. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { - Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : - diag::ext_no_named_members_in_struct_union) - << Record->isUnion(); + Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union + : diag::ext_no_named_members_in_struct_union) + << Record->isUnion(); } } } else { ObjCIvarDecl **ClsFields = - reinterpret_cast(RecFields.data()); + reinterpret_cast(RecFields.data()); if (ObjCInterfaceDecl *ID = dyn_cast(EnclosingDecl)) { ID->setEndOfDefinitionLoc(RBrac); // Add ivar's to class's DeclContext. @@ -16304,7 +16348,7 @@ if (ID->getSuperClass()) DiagnoseDuplicateIvars(ID, ID->getSuperClass()); } else if (ObjCImplementationDecl *IMPDecl = - dyn_cast(EnclosingDecl)) { + dyn_cast(EnclosingDecl)) { assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); for (unsigned I = 0, N = RecFields.size(); I != N; ++I) // Ivar declared in @implementation never belongs to the implementation. @@ -16314,7 +16358,7 @@ IMPDecl->setIvarLBraceLoc(LBrac); IMPDecl->setIvarRBraceLoc(RBrac); } else if (ObjCCategoryDecl *CDecl = - dyn_cast(EnclosingDecl)) { + dyn_cast(EnclosingDecl)) { // case of ivars in class extension; all other cases have been // reported as errors elsewhere. // FIXME. Class extension does not have a LocEnd field. @@ -16325,15 +16369,15 @@ for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { if (IDecl) { if (const ObjCIvarDecl *ClsIvar = - IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { + IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { Diag(ClsFields[i]->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsIvar->getLocation(), diag::note_previous_definition); continue; } for (const auto *Ext : IDecl->known_extensions()) { - if (const ObjCIvarDecl *ClsExtIvar - = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { + if (const ObjCIvarDecl *ClsExtIvar = + Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { Diag(ClsFields[i]->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); @@ -16353,8 +16397,7 @@ /// Determine whether the given integral value is representable within /// the given type T. static bool isRepresentableIntegerValue(ASTContext &Context, - llvm::APSInt &Value, - QualType T) { + llvm::APSInt &Value, QualType T) { assert((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!"); unsigned BitWidth = Context.getIntWidth(T); @@ -16372,20 +16415,19 @@ static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { // FIXME: Int128/UInt128 support, which also needs to be introduced into // enum checking below. - assert((T->isIntegralType(Context) || - T->isEnumeralType()) && "Integral type required!"); + assert((T->isIntegralType(Context) || T->isEnumeralType()) && + "Integral type required!"); const unsigned NumTypes = 4; - QualType SignedIntegralTypes[NumTypes] = { - Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy - }; + QualType SignedIntegralTypes[NumTypes] = {Context.ShortTy, Context.IntTy, + Context.LongTy, Context.LongLongTy}; QualType UnsignedIntegralTypes[NumTypes] = { - Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, - Context.UnsignedLongLongTy - }; + Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, + Context.UnsignedLongLongTy}; unsigned BitWidth = Context.getTypeSize(T); - QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes - : UnsignedIntegralTypes; + QualType *Types = T->isSignedIntegerOrEnumerationType() + ? SignedIntegralTypes + : UnsignedIntegralTypes; for (unsigned I = 0; I != NumTypes; ++I) if (Context.getTypeSize(Types[I]) > BitWidth) return Types[I]; @@ -16396,8 +16438,7 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, - IdentifierInfo *Id, - Expr *Val) { + IdentifierInfo *Id, Expr *Val) { unsigned IntWidth = Context.getTargetInfo().getIntWidth(); llvm::APSInt EnumVal(IntWidth); QualType EltTy; @@ -16418,16 +16459,15 @@ // constant-expression in the enumerator-definition shall be a converted // constant expression of the underlying type. EltTy = Enum->getIntegerType(); - ExprResult Converted = - CheckConvertedConstantExpression(Val, EltTy, EnumVal, - CCEK_Enumerator); + ExprResult Converted = CheckConvertedConstantExpression( + Val, EltTy, EnumVal, CCEK_Enumerator); if (Converted.isInvalid()) Val = nullptr; else Val = Converted.get(); } else if (!Val->isValueDependent() && - !(Val = VerifyIntegerConstantExpression(Val, - &EnumVal).get())) { + !(Val = + VerifyIntegerConstantExpression(Val, &EnumVal).get())) { // C99 6.7.2.2p2: Make sure we have an integer constant expression. } else { if (Enum->isComplete()) { @@ -16444,9 +16484,10 @@ } else Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; } else - Val = ImpCastExprToType(Val, EltTy, - EltTy->isBooleanType() ? - CK_IntegralToBoolean : CK_IntegralCast) + Val = + ImpCastExprToType(Val, EltTy, + EltTy->isBooleanType() ? CK_IntegralToBoolean + : CK_IntegralCast) .get(); } else if (getLangOpts().CPlusPlus) { // C++11 [dcl.enum]p5: @@ -16464,8 +16505,8 @@ // Complain if the value is not representable in an int. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) Diag(IdLoc, diag::ext_enum_value_not_int) - << EnumVal.toString(10) << Val->getSourceRange() - << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); + << EnumVal.toString(10) << Val->getSourceRange() + << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { // Force the type of the expression to 'int'. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); @@ -16490,8 +16531,7 @@ // C99 6.7.2.2p3. if (Enum->isFixed()) { EltTy = Enum->getIntegerType(); - } - else { + } else { EltTy = Context.IntTy; } } else { @@ -16522,11 +16562,10 @@ if (Enum->isFixed()) // When the underlying type is fixed, this is ill-formed. Diag(IdLoc, diag::err_enumerator_wrapped) - << EnumVal.toString(10) - << EltTy; + << EnumVal.toString(10) << EltTy; else Diag(IdLoc, diag::ext_enumerator_increment_too_large) - << EnumVal.toString(10); + << EnumVal.toString(10); } else { EltTy = T; } @@ -16549,8 +16588,7 @@ } else if (!getLangOpts().CPlusPlus && !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { // Enforce C99 6.7.2.2p2 even when we compute the next value. - Diag(IdLoc, diag::ext_enum_value_not_int) - << EnumVal.toString(10) << 1; + Diag(IdLoc, diag::ext_enum_value_not_int) << EnumVal.toString(10) << 1; } } } @@ -16562,8 +16600,8 @@ EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); } - return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, - Val, EnumVal); + return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, Val, + EnumVal); } Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, @@ -16598,7 +16636,7 @@ SourceLocation EqualLoc, Expr *Val) { EnumDecl *TheEnumDecl = cast(theEnumDecl); EnumConstantDecl *LastEnumConst = - cast_or_null(lastEnumConst); + cast_or_null(lastEnumConst); // The scope passed in may not be a decl scope. Zip up the scope tree until // we find one that is. @@ -16627,7 +16665,7 @@ DeclarationNameInfo(Id, IdLoc)); EnumConstantDecl *New = - CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); + CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); if (!New) return nullptr; @@ -16722,7 +16760,7 @@ typedef SmallVector ECDVector; typedef SmallVector, 3> DuplicatesVector; - typedef llvm::PointerUnion DeclOrVector; + typedef llvm::PointerUnion DeclOrVector; typedef std::unordered_map ValueToVectorMap; // Use int64_t as a key to avoid needing special handling for DenseMap keys. @@ -16767,8 +16805,8 @@ if (Iter == EnumMap.end()) continue; - DeclOrVector& Entry = Iter->second; - if (EnumConstantDecl *D = Entry.dyn_cast()) { + DeclOrVector &Entry = Iter->second; + if (EnumConstantDecl *D = Entry.dyn_cast()) { // Ensure constants are different. if (D == ECD) continue; @@ -16787,7 +16825,7 @@ continue; } - ECDVector *Vec = Entry.get(); + ECDVector *Vec = Entry.get(); // Make sure constants are not added more than once. if (*Vec->begin() == ECD) continue; @@ -16802,15 +16840,14 @@ // Emit warning for one enum constant. auto *FirstECD = Vec->front(); S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) - << FirstECD << FirstECD->getInitVal().toString(10) - << FirstECD->getSourceRange(); + << FirstECD << FirstECD->getInitVal().toString(10) + << FirstECD->getSourceRange(); // Emit one note for each of the remaining enum constants with // the same value. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) S.Diag(ECD->getLocation(), diag::note_duplicate_element) - << ECD << ECD->getInitVal().toString(10) - << ECD->getSourceRange(); + << ECD << ECD->getInitVal().toString(10) << ECD->getSourceRange(); } } @@ -16853,9 +16890,9 @@ if (Enum->isDependentType()) { for (unsigned i = 0, e = Elements.size(); i != e; ++i) { - EnumConstantDecl *ECD = - cast_or_null(Elements[i]); - if (!ECD) continue; + EnumConstantDecl *ECD = cast_or_null(Elements[i]); + if (!ECD) + continue; ECD->setType(EnumType); } @@ -16880,19 +16917,19 @@ bool AllElementsInt = true; for (unsigned i = 0, e = Elements.size(); i != e; ++i) { - EnumConstantDecl *ECD = - cast_or_null(Elements[i]); - if (!ECD) continue; // Already issued a diagnostic. + EnumConstantDecl *ECD = cast_or_null(Elements[i]); + if (!ECD) + continue; // Already issued a diagnostic. const llvm::APSInt &InitVal = ECD->getInitVal(); // Keep track of the size of positive and negative values. if (InitVal.isUnsigned() || InitVal.isNonNegative()) - NumPositiveBits = std::max(NumPositiveBits, - (unsigned)InitVal.getActiveBits()); + NumPositiveBits = + std::max(NumPositiveBits, (unsigned)InitVal.getActiveBits()); else - NumNegativeBits = std::max(NumNegativeBits, - (unsigned)InitVal.getMinSignedBits()); + NumNegativeBits = + std::max(NumNegativeBits, (unsigned)InitVal.getMinSignedBits()); // Keep track of whether every enum element has type int (very common). if (AllElementsInt) @@ -16930,8 +16967,7 @@ BestPromotionType = BestType; BestWidth = Context.getIntWidth(BestType); - } - else if (NumNegativeBits) { + } else if (NumNegativeBits) { // If there is a negative value, figure out the smallest integer type (of // int/long/longlong) that fits. // If it's packed, check also if it fits a char or a short. @@ -16974,23 +17010,26 @@ } else if (NumPositiveBits <= IntWidth) { BestType = Context.UnsignedIntTy; BestWidth = IntWidth; - BestPromotionType - = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) - ? Context.UnsignedIntTy : Context.IntTy; + BestPromotionType = + (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) + ? Context.UnsignedIntTy + : Context.IntTy; } else if (NumPositiveBits <= (BestWidth = Context.getTargetInfo().getLongWidth())) { BestType = Context.UnsignedLongTy; - BestPromotionType - = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) - ? Context.UnsignedLongTy : Context.LongTy; + BestPromotionType = + (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) + ? Context.UnsignedLongTy + : Context.LongTy; } else { BestWidth = Context.getTargetInfo().getLongLongWidth(); assert(NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"); BestType = Context.UnsignedLongLongTy; - BestPromotionType - = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) - ? Context.UnsignedLongLongTy : Context.LongLongTy; + BestPromotionType = + (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) + ? Context.UnsignedLongLongTy + : Context.LongLongTy; } } @@ -16998,7 +17037,8 @@ // the type of the enum if needed. for (auto *D : Elements) { auto *ECD = cast_or_null(D); - if (!ECD) continue; // Already issued a diagnostic. + if (!ECD) + continue; // Already issued a diagnostic. // Standard C says the enumerators have int type, but we allow, as an // extension, the enumerators to be larger than int size. If each @@ -17014,8 +17054,7 @@ QualType NewTy; unsigned NewWidth; bool NewSign; - if (!getLangOpts().CPlusPlus && - !Enum->isFixed() && + if (!getLangOpts().CPlusPlus && !Enum->isFixed() && isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { NewTy = Context.IntTy; NewWidth = IntWidth; @@ -17042,11 +17081,9 @@ // Adjust the Expr initializer and type. if (ECD->getInitExpr() && !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) - ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, - CK_IntegralCast, - ECD->getInitExpr(), - /*base paths*/ nullptr, - VK_RValue)); + ECD->setInitExpr(ImplicitCastExpr::Create( + Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), + /*base paths*/ nullptr, VK_RValue)); if (getLangOpts().CPlusPlus) // C++ [dcl.enum]p4: Following the closing brace of an // enum-specifier, each enumerator has the type of its @@ -17056,21 +17093,22 @@ ECD->setType(NewTy); } - Enum->completeDefinition(BestType, BestPromotionType, - NumPositiveBits, NumNegativeBits); + Enum->completeDefinition(BestType, BestPromotionType, NumPositiveBits, + NumNegativeBits); CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); if (Enum->isClosedFlag()) { for (Decl *D : Elements) { EnumConstantDecl *ECD = cast_or_null(D); - if (!ECD) continue; // Already issued a diagnostic. + if (!ECD) + continue; // Already issued a diagnostic. llvm::APSInt InitVal = ECD->getInitVal(); if (InitVal != 0 && !InitVal.isPowerOf2() && !IsValueInFlagEnum(Enum, InitVal, true)) Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) - << ECD << Enum; + << ECD << Enum; } } @@ -17079,25 +17117,23 @@ CheckAlignasUnderalignment(Enum); } -Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, - SourceLocation StartLoc, +Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc, SourceLocation EndLoc) { StringLiteral *AsmString = cast(expr); FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, - AsmString, StartLoc, - EndLoc); + AsmString, StartLoc, EndLoc); CurContext->addDecl(New); return New; } -void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, - IdentifierInfo* AliasName, +void Sema::ActOnPragmaRedefineExtname(IdentifierInfo *Name, + IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation NameLoc, SourceLocation AliasNameLoc) { - NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, - LookupOrdinaryName); + NamedDecl *PrevDecl = + LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); @@ -17110,14 +17146,13 @@ PrevDecl->addAttr(Attr); else Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) - << /*Variable*/(isa(PrevDecl) ? 0 : 1) << PrevDecl; - // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. + << /*Variable*/ (isa(PrevDecl) ? 0 : 1) << PrevDecl; + // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. } else (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); } -void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, - SourceLocation PragmaLoc, +void Sema::ActOnPragmaWeakID(IdentifierInfo *Name, SourceLocation PragmaLoc, SourceLocation NameLoc) { Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); @@ -17125,18 +17160,17 @@ PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); } else { (void)WeakUndeclaredIdentifiers.insert( - std::pair - (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); + std::pair( + Name, WeakInfo((IdentifierInfo *)nullptr, NameLoc))); } } -void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, - IdentifierInfo* AliasName, +void Sema::ActOnPragmaWeakAlias(IdentifierInfo *Name, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation NameLoc, SourceLocation AliasNameLoc) { - Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, - LookupOrdinaryName); + Decl *PrevDecl = + LookupSingleName(TUScope, AliasName, AliasNameLoc, LookupOrdinaryName); WeakInfo W = WeakInfo(Name, NameLoc); if (PrevDecl && (isa(PrevDecl) || isa(PrevDecl))) { @@ -17145,7 +17179,7 @@ DeclApplyPragmaWeak(TUScope, ND, W); } else { (void)WeakUndeclaredIdentifiers.insert( - std::pair(AliasName, W)); + std::pair(AliasName, W)); } } diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -40,11 +40,7 @@ using namespace sema; namespace AttributeLangSupport { - enum LANG { - C, - Cpp, - ObjC - }; +enum LANG { C, Cpp, ObjC }; } // end namespace AttributeLangSupport //===----------------------------------------------------------------------===// @@ -68,8 +64,8 @@ /// been processed by Sema::GetTypeForDeclarator. static bool hasDeclarator(const Decl *D) { // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. - return isa(D) || isa(D) || isa(D) || - isa(D); + return isa(D) || isa(D) || + isa(D) || isa(D); } /// hasFunctionProto - Return true if the given decl has a argument @@ -155,7 +151,7 @@ if (!Cls) return false; - IdentifierInfo* ClsName = Cls->getIdentifier(); + IdentifierInfo *ClsName = Cls->getIdentifier(); // FIXME: Should we walk the chain of classes? return ClsName == &Ctx.Idents.get("NSString") || @@ -207,9 +203,8 @@ /// output an error. static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) { - return checkAttributeNumArgsImpl(S, AL, Num, - diag::err_attribute_too_few_arguments, - std::less()); + return checkAttributeNumArgsImpl( + S, AL, Num, diag::err_attribute_too_few_arguments, std::less()); } /// Check if the attribute has at most as many args as Num. May @@ -273,8 +268,9 @@ /// that the result will fit into a regular (signed) int. All args have the same /// purpose as they do in checkUInt32Argument. template -static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, - int &Val, unsigned Idx = UINT_MAX) { +static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, + const Expr *Expr, int &Val, + unsigned Idx = UINT_MAX) { uint32_t UVal; if (!checkUInt32Argument(S, AI, Expr, UVal, Idx)) return false; @@ -306,8 +302,8 @@ template static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) { if (const auto *A = D->getAttr()) { - S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL - << A; + S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) + << &AL << A; S.Diag(A->getLocation(), diag::note_conflicting_attribute); return true; } @@ -409,15 +405,14 @@ AL.getAttributeSpellingListIndex()); } - template -static const Sema::SemaDiagnosticBuilder& +static const Sema::SemaDiagnosticBuilder & appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) { return Bldr; } template -static const Sema::SemaDiagnosticBuilder& +static const Sema::SemaDiagnosticBuilder & appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg, DiagnosticArgs &&... ExtraArgs) { return appendDiagnostics(Bldr << std::forward(ExtraArg), @@ -429,11 +424,10 @@ /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters /// specified in {@code ExtraArgs}. template -static void -handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR, - unsigned SpellingIndex, - bool PassesCheck, - unsigned DiagID, DiagnosticArgs&&... ExtraArgs) { +static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR, + unsigned SpellingIndex, + bool PassesCheck, unsigned DiagID, + DiagnosticArgs &&... ExtraArgs) { if (!PassesCheck) { Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID); appendDiagnostics(DB, std::forward(ExtraArgs)...); @@ -443,11 +437,10 @@ } template -static void -handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL, - bool PassesCheck, - unsigned DiagID, - DiagnosticArgs&&... ExtraArgs) { +static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, + const ParsedAttr &AL, + bool PassesCheck, unsigned DiagID, + DiagnosticArgs &&... ExtraArgs) { return handleSimpleAttributeOrDiagnose( S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck, DiagID, std::forward(ExtraArgs)...); @@ -477,10 +470,9 @@ return QT->isBooleanType() || QT->isIntegerType(); } - // Check to see if the type is a smart pointer of some kind. We assume // it's a smart pointer if it defines both operator-> and operator*. -static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { +static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType *RT) { auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record, OverloadedOperatorKind Op) { DeclContextLookupResult Result = @@ -707,10 +699,10 @@ const RecordType *RT = getRecordType(ArgTy); // Now check if we index into a record type function param. - if(!RT && ParamIdxOk) { + if (!RT && ParamIdxOk) { const auto *FD = dyn_cast(D); const auto *IL = dyn_cast(ArgExp); - if(FD && IL) { + if (FD && IL) { unsigned int NumParams = FD->getNumParams(); llvm::APInt ArgValue = IL->getValue(); uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); @@ -745,9 +737,8 @@ if (!threadSafetyCheckIsPointer(S, D, AL)) return; - D->addAttr(::new (S.Context) - PtGuardedVarAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) PtGuardedVarAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, @@ -942,7 +933,7 @@ static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - SmallVector Args; + SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; @@ -953,26 +944,25 @@ static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - SmallVector Args; + SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( - AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), - Args.size(), AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), + AL.getAttributeSpellingListIndex())); } static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // check that the argument is lockable object - SmallVector Args; + SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); unsigned Size = Args.size(); if (Size == 0) return; - D->addAttr(::new (S.Context) - LockReturnedAttr(AL.getRange(), S.Context, Args[0], - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) LockReturnedAttr( + AL.getRange(), S.Context, Args[0], AL.getAttributeSpellingListIndex())); } static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -980,7 +970,7 @@ return; // check that all arguments are lockable objects - SmallVector Args; + SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); unsigned Size = Args.size(); if (Size == 0) @@ -988,8 +978,8 @@ Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) - LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size, - AL.getAttributeSpellingListIndex())); + LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size, + AL.getAttributeSpellingListIndex())); } static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL, @@ -1075,7 +1065,7 @@ return true; } }; -} +} // namespace static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if); @@ -1144,8 +1134,8 @@ IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), DefaultState)) { - S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL - << IL->Ident; + S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) + << AL << IL->Ident; return; } } else { @@ -1155,8 +1145,8 @@ } D->addAttr(::new (S.Context) - ConsumableAttr(AL.getRange(), S.Context, DefaultState, - AL.getAttributeSpellingListIndex())); + ConsumableAttr(AL.getRange(), S.Context, DefaultState, + AL.getAttributeSpellingListIndex())); } static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, @@ -1165,8 +1155,8 @@ if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { if (!RD->hasAttr()) { - S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << - RD->getNameAsString(); + S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) + << RD->getNameAsString(); return false; } @@ -1206,9 +1196,9 @@ States.push_back(CallableState); } - D->addAttr(::new (S.Context) - CallableWhenAttr(AL.getRange(), S.Context, States.data(), - States.size(), AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) CallableWhenAttr( + AL.getRange(), S.Context, States.data(), States.size(), + AL.getAttributeSpellingListIndex())); } static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1233,18 +1223,18 @@ // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. - //QualType ReturnType = cast(D)->getType(); - //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); + // QualType ReturnType = cast(D)->getType(); + // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // - //if (!RD || !RD->hasAttr()) { + // if (!RD || !RD->hasAttr()) { // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; //} D->addAttr(::new (S.Context) - ParamTypestateAttr(AL.getRange(), S.Context, ParamState, - AL.getAttributeSpellingListIndex())); + ParamTypestateAttr(AL.getRange(), S.Context, ParamState, + AL.getAttributeSpellingListIndex())); } static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1254,8 +1244,8 @@ IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), ReturnState)) { - S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL - << IL->Ident; + S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) + << AL << IL->Ident; return; } } else { @@ -1267,9 +1257,9 @@ // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. - //QualType ReturnType; + // QualType ReturnType; // - //if (const ParmVarDecl *Param = dyn_cast(D)) { + // if (const ParmVarDecl *Param = dyn_cast(D)) { // ReturnType = Param->getType(); // //} else if (const CXXConstructorDecl *Constructor = @@ -1281,9 +1271,9 @@ // ReturnType = cast(D)->getCallResultType(); //} // - //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); + // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // - //if (!RD || !RD->hasAttr()) { + // if (!RD || !RD->hasAttr()) { // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; @@ -1303,8 +1293,8 @@ IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { - S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL - << Param; + S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) + << AL << Param; return; } } else { @@ -1313,9 +1303,8 @@ return; } - D->addAttr(::new (S.Context) - SetTypestateAttr(AL.getRange(), S.Context, NewState, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) SetTypestateAttr( + AL.getRange(), S.Context, NewState, AL.getAttributeSpellingListIndex())); } static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1327,8 +1316,8 @@ IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { - S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL - << Param; + S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) + << AL << Param; return; } } else { @@ -1337,9 +1326,8 @@ return; } - D->addAttr(::new (S.Context) - TestTypestateAttr(AL.getRange(), S.Context, TestState, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) TestTypestateAttr( + AL.getRange(), S.Context, TestState, AL.getAttributeSpellingListIndex())); } static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1349,13 +1337,13 @@ static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (auto *TD = dyn_cast(D)) - TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + TD->addAttr(::new (S.Context) PackedAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); else if (auto *FD = dyn_cast(D)) { - bool BitfieldByteAligned = (!FD->getType()->isDependentType() && - !FD->getType()->isIncompleteType() && - FD->isBitField() && - S.Context.getTypeAlign(FD->getType()) <= 8); + bool BitfieldByteAligned = + (!FD->getType()->isDependentType() && + !FD->getType()->isIncompleteType() && FD->isBitField() && + S.Context.getTypeAlign(FD->getType()) <= 8); if (S.getASTContext().getTargetInfo().getTriple().isPS4()) { if (BitfieldByteAligned) @@ -1364,14 +1352,14 @@ << AL << FD->getType(); else FD->addAttr(::new (S.Context) PackedAttr( - AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } else { // Report warning about changed offset in the newer compiler versions. if (BitfieldByteAligned) S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield); FD->addAttr(::new (S.Context) PackedAttr( - AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } } else @@ -1388,15 +1376,13 @@ << AL << VD->getType() << 0; return false; } - } - else if (const auto *PD = dyn_cast(D)) { + } else if (const auto *PD = dyn_cast(D)) { if (!PD->getType()->getAs()) { S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) << AL << PD->getType() << 1; return false; } - } - else { + } else { S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL; return false; } @@ -1408,9 +1394,8 @@ if (!checkIBOutletCommon(S, D, AL)) return; - D->addAttr(::new (S.Context) - IBOutletAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) IBOutletAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1447,15 +1432,15 @@ // attributes. So, __attribute__((iboutletcollection(char))) will be // treated as __attribute__((iboutletcollection())). if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { - S.Diag(AL.getLoc(), - QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype - : diag::err_iboutletcollection_type) << QT; + S.Diag(AL.getLoc(), QT->isBuiltinType() + ? diag::err_iboutletcollection_builtintype + : diag::err_iboutletcollection_type) + << QT; return; } - D->addAttr(::new (S.Context) - IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) IBOutletCollectionAttr( + AL.getRange(), S.Context, QTLoc, AL.getAttributeSpellingListIndex())); } bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { @@ -1550,7 +1535,7 @@ handleNonNullAttr(S, D, AL); } else { S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args) - << D->getSourceRange(); + << D->getSourceRange(); } return; } @@ -1560,9 +1545,8 @@ D->getSourceRange())) return; - D->addAttr(::new (S.Context) - NonNullAttr(AL.getRange(), S.Context, nullptr, 0, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) NonNullAttr(AL.getRange(), S.Context, nullptr, 0, + AL.getAttributeSpellingListIndex())); } static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1572,9 +1556,8 @@ /* isReturnValue */ true)) return; - D->addAttr(::new (S.Context) - ReturnsNonNullAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ReturnsNonNullAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1615,7 +1598,7 @@ if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) - << &TmpAttr << AttrRange << SR; + << &TmpAttr << AttrRange << SR; return; } @@ -1624,18 +1607,17 @@ if (!E->isIntegerConstantExpr(I, Context)) { if (OE) Diag(AttrLoc, diag::err_attribute_argument_n_type) - << &TmpAttr << 1 << AANT_ArgumentIntegerConstant - << E->getSourceRange(); + << &TmpAttr << 1 << AANT_ArgumentIntegerConstant + << E->getSourceRange(); else Diag(AttrLoc, diag::err_attribute_argument_type) - << &TmpAttr << AANT_ArgumentIntegerConstant - << E->getSourceRange(); + << &TmpAttr << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } if (!I.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) - << E->getSourceRange(); + << E->getSourceRange(); return; } } @@ -1645,15 +1627,15 @@ llvm::APSInt I(64); if (!OE->isIntegerConstantExpr(I, Context)) { Diag(AttrLoc, diag::err_attribute_argument_n_type) - << &TmpAttr << 2 << AANT_ArgumentIntegerConstant - << OE->getSourceRange(); + << &TmpAttr << 2 << AANT_ArgumentIntegerConstant + << OE->getSourceRange(); return; } } } - D->addAttr(::new (Context) - AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); + D->addAttr(::new (Context) AssumeAlignedAttr(AttrRange, Context, E, OE, + SpellingListIndex)); } void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, @@ -1717,7 +1699,8 @@ // Figure out our Kind. OwnershipAttr::OwnershipKind K = OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, - AL.getAttributeSpellingListIndex()).getOwnKind(); + AL.getAttributeSpellingListIndex()) + .getOwnKind(); // Check arguments. switch (K) { @@ -1752,21 +1735,21 @@ // Is the function argument a pointer type? QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex()); - int Err = -1; // No error + int Err = -1; // No error switch (K) { - case OwnershipAttr::Takes: - case OwnershipAttr::Holds: - if (!T->isAnyPointerType() && !T->isBlockPointerType()) - Err = 0; - break; - case OwnershipAttr::Returns: - if (!T->isIntegerType()) - Err = 1; - break; + case OwnershipAttr::Takes: + case OwnershipAttr::Holds: + if (!T->isAnyPointerType() && !T->isBlockPointerType()) + Err = 0; + break; + case OwnershipAttr::Returns: + if (!T->isIntegerType()) + Err = 1; + break; } if (-1 != Err) { - S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err - << Ex->getSourceRange(); + S.Diag(AL.getLoc(), diag::err_ownership_type) + << AL << Err << Ex->getSourceRange(); return; } @@ -1774,8 +1757,8 @@ for (const auto *I : D->specific_attrs()) { // Cannot have two ownership attributes of different kinds for the same // index. - if (I->getOwnKind() != K && I->args_end() != - std::find(I->args_begin(), I->args_end(), Idx)) { + if (I->getOwnKind() != K && + I->args_end() != std::find(I->args_begin(), I->args_end(), Idx)) { S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I; return; } else if (K == OwnershipAttr::Returns && @@ -1857,11 +1840,10 @@ // GCC will accept anything as the argument of weakref. Should we // check for an existing decl? D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str, - AL.getAttributeSpellingListIndex())); + AL.getAttributeSpellingListIndex())); - D->addAttr(::new (S.Context) - WeakRefAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) WeakRefAttr(AL.getRange(), S.Context, + AL.getAttributeSpellingListIndex())); } static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -1930,15 +1912,14 @@ return; // Check that the value. - if (Model != "global-dynamic" && Model != "local-dynamic" - && Model != "initial-exec" && Model != "local-exec") { + if (Model != "global-dynamic" && Model != "local-dynamic" && + Model != "initial-exec" && Model != "local-exec") { S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); return; } - D->addAttr(::new (S.Context) - TLSModelAttr(AL.getRange(), S.Context, Model, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) TLSModelAttr( + AL.getRange(), S.Context, Model, AL.getAttributeSpellingListIndex())); } static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2036,7 +2017,8 @@ } static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { - if (hasDeclarator(D)) return; + if (hasDeclarator(D)) + return; if (!isa(D)) { S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type) @@ -2091,9 +2073,8 @@ } } - D->addAttr(::new (S.Context) - AnalyzerNoReturnAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AnalyzerNoReturnAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } // PS3 PPU-specific. @@ -2158,15 +2139,13 @@ // [[carries_dependency]] can only be applied to a parameter if it is a // parameter of a function declaration or lambda. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { - S.Diag(AL.getLoc(), - diag::err_carries_dependency_param_not_function_decl); + S.Diag(AL.getLoc(), diag::err_carries_dependency_param_not_function_decl); return; } } D->addAttr(::new (S.Context) CarriesDependencyAttr( - AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2177,8 +2156,8 @@ if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; - D->addAttr(::new (S.Context) UnusedAttr( - AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) UnusedAttr(AL.getRange(), S.Context, + AL.getAttributeSpellingListIndex())); } static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2187,9 +2166,8 @@ !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) return; - D->addAttr(::new (S.Context) - ConstructorAttr(AL.getRange(), S.Context, priority, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ConstructorAttr( + AL.getRange(), S.Context, priority, AL.getAttributeSpellingListIndex())); } static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2198,9 +2176,8 @@ !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) return; - D->addAttr(::new (S.Context) - DestructorAttr(AL.getRange(), S.Context, priority, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) DestructorAttr( + AL.getRange(), S.Context, priority, AL.getAttributeSpellingListIndex())); } template @@ -2222,9 +2199,8 @@ return; } - D->addAttr(::new (S.Context) - ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static bool checkAvailabilityAttr(Sema &S, SourceRange Range, @@ -2232,8 +2208,8 @@ VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted) { - StringRef PlatformName - = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); + StringRef PlatformName = + AvailabilityAttr::getPrettyPlatformName(Platform->getName()); if (PlatformName.empty()) PlatformName = Platform->getName(); @@ -2242,24 +2218,22 @@ if (!Introduced.empty() && !Deprecated.empty() && !(Introduced <= Deprecated)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) - << 1 << PlatformName << Deprecated.getAsString() - << 0 << Introduced.getAsString(); + << 1 << PlatformName << Deprecated.getAsString() << 0 + << Introduced.getAsString(); return true; } - if (!Introduced.empty() && !Obsoleted.empty() && - !(Introduced <= Obsoleted)) { + if (!Introduced.empty() && !Obsoleted.empty() && !(Introduced <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) - << 2 << PlatformName << Obsoleted.getAsString() - << 0 << Introduced.getAsString(); + << 2 << PlatformName << Obsoleted.getAsString() << 0 + << Introduced.getAsString(); return true; } - if (!Deprecated.empty() && !Obsoleted.empty() && - !(Deprecated <= Obsoleted)) { + if (!Deprecated.empty() && !Obsoleted.empty() && !(Deprecated <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) - << 2 << PlatformName << Obsoleted.getAsString() - << 1 << Deprecated.getAsString(); + << 2 << PlatformName << Obsoleted.getAsString() << 1 + << Deprecated.getAsString(); return true; } @@ -2355,7 +2329,8 @@ Which = 0; FirstVersion = OldIntroduced; SecondVersion = Introduced; - } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { + } else if (!versionsMatch(Deprecated, OldDeprecated, + OverrideOrImpl)) { Which = 1; FirstVersion = Deprecated; SecondVersion = OldDeprecated; @@ -2368,15 +2343,15 @@ if (Which == -1) { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override_unavail) - << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) - << (AMK == AMK_Override); + << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) + << (AMK == AMK_Override); } else { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override) - << Which - << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) - << FirstVersion.getAsString() << SecondVersion.getAsString() - << (AMK == AMK_Override); + << Which + << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) + << FirstVersion.getAsString() << SecondVersion.getAsString() + << (AMK == AMK_Override); } if (AMK == AMK_Override) Diag(Range.getBegin(), diag::note_overridden_method); @@ -2418,10 +2393,8 @@ } } - if (FoundAny && - MergedIntroduced == Introduced && - MergedDeprecated == Deprecated && - MergedObsoleted == Obsoleted) + if (FoundAny && MergedIntroduced == Introduced && + MergedDeprecated == Deprecated && MergedObsoleted == Obsoleted) return nullptr; // Only create a new attribute if !OverrideOrImpl, but we want to do @@ -2448,7 +2421,7 @@ IdentifierInfo *II = Platform->Ident; if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) - << Platform->Ident; + << Platform->Ident; auto *ND = dyn_cast(D); if (!ND) // We warned about this already, so just return. @@ -2495,37 +2468,37 @@ NewII = &S.Context.Idents.get("watchos_app_extension"); if (NewII) { - auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { - if (Version.empty()) - return Version; - auto Major = Version.getMajor(); - auto NewMajor = Major >= 9 ? Major - 7 : 0; - if (NewMajor >= 2) { - if (Version.getMinor().hasValue()) { - if (Version.getSubminor().hasValue()) - return VersionTuple(NewMajor, Version.getMinor().getValue(), - Version.getSubminor().getValue()); - else - return VersionTuple(NewMajor, Version.getMinor().getValue()); - } - return VersionTuple(NewMajor); + auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { + if (Version.empty()) + return Version; + auto Major = Version.getMajor(); + auto NewMajor = Major >= 9 ? Major - 7 : 0; + if (NewMajor >= 2) { + if (Version.getMinor().hasValue()) { + if (Version.getSubminor().hasValue()) + return VersionTuple(NewMajor, Version.getMinor().getValue(), + Version.getSubminor().getValue()); + else + return VersionTuple(NewMajor, Version.getMinor().getValue()); } + return VersionTuple(NewMajor); + } - return VersionTuple(2, 0); - }; + return VersionTuple(2, 0); + }; - auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); - auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); - auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); - - AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( - ND, AL.getRange(), NewII, true /*Implicit*/, NewIntroduced, - NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict, - Replacement, Sema::AMK_None, - PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index); - if (NewAttr) - D->addAttr(NewAttr); - } + auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); + auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); + auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); + + AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( + ND, AL.getRange(), NewII, true /*Implicit*/, NewIntroduced, + NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict, + Replacement, Sema::AMK_None, + PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index); + if (NewAttr) + D->addAttr(NewAttr); + } } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning // matches before the start of the tvOS platform. @@ -2543,7 +2516,7 @@ PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index); if (NewAttr) D->addAttr(NewAttr); - } + } } } @@ -2590,9 +2563,10 @@ AttrSpellingListIndex); } -TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, - TypeVisibilityAttr::VisibilityType Vis, - unsigned AttrSpellingListIndex) { +TypeVisibilityAttr * +Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, + TypeVisibilityAttr::VisibilityType Vis, + unsigned AttrSpellingListIndex) { return ::mergeVisibilityAttr(*this, D, Range, Vis, AttrSpellingListIndex); } @@ -2606,10 +2580,8 @@ } // 'type_visibility' can only go on a type or namespace. - if (isTypeVisibility && - !(isa(D) || - isa(D) || - isa(D))) { + if (isTypeVisibility && !(isa(D) || isa(D) || + isa(D))) { S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) << AL << ExpectedTypeOrNamespace; return; @@ -2623,8 +2595,8 @@ VisibilityAttr::VisibilityType type; if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { - S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL - << TypeStr; + S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) + << AL << TypeStr; return; } @@ -2639,9 +2611,8 @@ unsigned Index = AL.getAttributeSpellingListIndex(); Attr *newAttr; if (isTypeVisibility) { - newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(), - (TypeVisibilityAttr::VisibilityType) type, - Index); + newAttr = S.mergeTypeVisibilityAttr( + D, AL.getRange(), (TypeVisibilityAttr::VisibilityType)type, Index); } else { newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index); } @@ -2683,15 +2654,13 @@ S.Diag(TD->getLocation(), diag::err_nsobject_attribute); return; } - } - else if (const auto *PD = dyn_cast(D)) { + } else if (const auto *PD = dyn_cast(D)) { QualType T = PD->getType(); if (!T->isCARCBridgableType()) { S.Diag(PD->getLocation(), diag::err_nsobject_attribute); return; } - } - else { + } else { // It is okay to include this attribute on properties, e.g.: // // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); @@ -2700,9 +2669,8 @@ // case. S.Diag(D->getLocation(), diag::warn_nsobject_attribute); } - D->addAttr(::new (S.Context) - ObjCNSObjectAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ObjCNSObjectAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2716,9 +2684,8 @@ S.Diag(D->getLocation(), diag::warn_independentclass_attribute); return; } - D->addAttr(::new (S.Context) - ObjCIndependentClassAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ObjCIndependentClassAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2735,9 +2702,8 @@ return; } - D->addAttr(::new (S.Context) - BlocksAttr(AL.getRange(), S.Context, type, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) BlocksAttr(AL.getRange(), S.Context, type, + AL.getAttributeSpellingListIndex())); } static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2754,7 +2720,7 @@ if (Idx.isSigned() && Idx.isNegative()) { S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) - << E->getSourceRange(); + << E->getSourceRange(); return; } @@ -2777,7 +2743,7 @@ // FIXME: This error message could be improved, it would be nice // to say what the bounds actually are. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) - << E->getSourceRange(); + << E->getSourceRange(); return; } } @@ -2807,8 +2773,10 @@ QualType Ty = V->getType(); if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { const FunctionType *FT = Ty->isFunctionPointerType() - ? D->getFunctionType() - : Ty->getAs()->getPointeeType()->getAs(); + ? D->getFunctionType() + : Ty->getAs() + ->getPointeeType() + ->getAs(); if (!cast(FT)->isVariadic()) { int m = Ty->isFunctionPointerType() ? 0 : 1; S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; @@ -2825,8 +2793,8 @@ return; } D->addAttr(::new (S.Context) - SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos, - AL.getAttributeSpellingListIndex())); + SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos, + AL.getAttributeSpellingListIndex())); } static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2847,9 +2815,8 @@ !AL.getScopeName()) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; - D->addAttr(::new (S.Context) - WarnUnusedResultAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) WarnUnusedResultAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2858,7 +2825,7 @@ if (!D->canBeWeakImported(isDef)) { if (isDef) S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) - << "weak_import"; + << "weak_import"; else if (isa(D) || isa(D) || (S.Context.getTargetInfo().getTriple().isOSDarwin() && (isa(D) || isa(D)))) { @@ -2870,9 +2837,8 @@ return; } - D->addAttr(::new (S.Context) - WeakImportAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) WeakImportAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } // Handles reqd_work_group_size and work_group_size_hint. @@ -2892,14 +2858,14 @@ } WorkGroupAttr *Existing = D->getAttr(); - if (Existing && !(Existing->getXDim() == WGSize[0] && - Existing->getYDim() == WGSize[1] && - Existing->getZDim() == WGSize[2])) + if (Existing && + !(Existing->getXDim() == WGSize[0] && Existing->getYDim() == WGSize[1] && + Existing->getZDim() == WGSize[2])) S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; - D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context, - WGSize[0], WGSize[1], WGSize[2], - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) + WorkGroupAttr(AL.getRange(), S.Context, WGSize[0], WGSize[1], + WGSize[2], AL.getAttributeSpellingListIndex())); } // Handles intel_reqd_sub_group_size. @@ -2920,8 +2886,7 @@ S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr( - AL.getRange(), S.Context, SGSize, - AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, SGSize, AL.getAttributeSpellingListIndex())); } static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -2937,8 +2902,7 @@ if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && (ParmType->isBooleanType() || !ParmType->isIntegralType(S.getASTContext()))) { - S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint) - << ParmType; + S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint) << ParmType; return; } @@ -2949,13 +2913,11 @@ } } - D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context, - ParmTSI, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) VecTypeHintAttr( + AL.getLoc(), S.Context, ParmTSI, AL.getAttributeSpellingListIndex())); } -SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, - StringRef Name, +SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex) { // Explicit or partial specializations do not inherit // the section attribute from the primary template. @@ -2968,19 +2930,19 @@ if (ExistingAttr->getName() == Name) return nullptr; Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) - << 1 /*section*/; + << 1 /*section*/; Diag(Range.getBegin(), diag::note_previous_attribute); return nullptr; } - return ::new (Context) SectionAttr(Range, Context, Name, - AttrSpellingListIndex); + return ::new (Context) + SectionAttr(Range, Context, Name, AttrSpellingListIndex); } bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); if (!Error.empty()) { - Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error - << 1 /*'section'*/; + Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) + << Error << 1 /*'section'*/; return false; } return true; @@ -3000,8 +2962,7 @@ // If the target wants to validate the section specifier, make it happen. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); if (!Error.empty()) { - S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) - << Error; + S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; return; } @@ -3011,18 +2972,19 @@ D->addAttr(NewAttr); } -static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) { - std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName); +static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc, + StringRef CodeSegName) { + std::string Error = + S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName); if (!Error.empty()) { - S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error - << 0 /*'code-seg'*/; + S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) + << Error << 0 /*'code-seg'*/; return false; } return true; } -CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range, - StringRef Name, +CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex) { // Explicit or partial specializations do not inherit // the code_seg attribute from the primary template. @@ -3034,12 +2996,12 @@ if (ExistingAttr->getName() == Name) return nullptr; Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) - << 0 /*codeseg*/; + << 0 /*codeseg*/; Diag(Range.getBegin(), diag::note_previous_attribute); return nullptr; } - return ::new (Context) CodeSegAttr(Range, Context, Name, - AttrSpellingListIndex); + return ::new (Context) + CodeSegAttr(Range, Context, Name, AttrSpellingListIndex); } static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -3051,10 +3013,9 @@ return; if (const auto *ExistingAttr = D->getAttr()) { if (!ExistingAttr->isImplicit()) { - S.Diag(AL.getLoc(), - ExistingAttr->getName() == Str - ? diag::warn_duplicate_codeseg_attribute - : diag::err_conflicting_codeseg_attribute); + S.Diag(AL.getLoc(), ExistingAttr->getName() == Str + ? diag::warn_duplicate_codeseg_attribute + : diag::err_conflicting_codeseg_attribute); return; } D->dropAttr(); @@ -3122,9 +3083,8 @@ return; } - D->addAttr(::new (S.Context) - MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) MinVectorWidthAttr( + AL.getRange(), S.Context, VecWidth, AL.getAttributeSpellingListIndex())); } static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -3141,8 +3101,8 @@ FD = dyn_cast(DRE->getDecl()); NI = DRE->getNameInfo(); if (!FD) { - S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 - << NI.getName(); + S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) + << 1 << NI.getName(); return; } } else if (auto *ULE = dyn_cast(E)) { @@ -3151,8 +3111,8 @@ FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); NI = ULE->getNameInfo(); if (!FD) { - S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 - << NI.getName(); + S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) + << 2 << NI.getName(); if (ULE->getType() == S.Context.OverloadTy) S.NoteAllOverloadCandidates(ULE); return; @@ -3164,7 +3124,7 @@ if (FD->getNumParams() != 1) { S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) - << NI.getName(); + << NI.getName(); return; } @@ -3172,16 +3132,15 @@ // If this ever proves to be a problem it should be easy to fix. QualType Ty = S.Context.getPointerType(cast(D)->getType()); QualType ParamTy = FD->getParamDecl(0)->getType(); - if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), - ParamTy, Ty) != Sema::Compatible) { + if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), ParamTy, + Ty) != Sema::Compatible) { S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) - << NI.getName() << ParamTy << Ty; + << NI.getName() << ParamTy << Ty; return; } - D->addAttr(::new (S.Context) - CleanupAttr(AL.getRange(), S.Context, FD, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) CleanupAttr(AL.getRange(), S.Context, FD, + AL.getAttributeSpellingListIndex())); } static void handleEnumExtensibilityAttr(Sema &S, Decl *D, @@ -3217,8 +3176,7 @@ QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); bool NotNSStringTy = !isNSStringType(Ty, S.Context); - if (NotNSStringTy && - !isCFStringType(Ty, S.Context) && + if (NotNSStringTy && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType())) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) @@ -3227,8 +3185,7 @@ return; } Ty = getFunctionOrMethodResultType(D); - if (!isNSStringType(Ty, S.Context) && - !isCFStringType(Ty, S.Context) && + if (!isNSStringType(Ty, S.Context) && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType())) { S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) @@ -3307,8 +3264,8 @@ return; } D->addAttr(::new (S.Context) - InitPriorityAttr(AL.getRange(), S.Context, prioritynum, - AL.getAttributeSpellingListIndex())); + InitPriorityAttr(AL.getRange(), S.Context, prioritynum, + AL.getAttributeSpellingListIndex())); } FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, @@ -3317,8 +3274,7 @@ unsigned AttrSpellingListIndex) { // Check whether we already have an equivalent format attribute. for (auto *F : D->specific_attrs()) { - if (F->getType() == Format && - F->getFormatIdx() == FormatIdx && + if (F->getType() == Format && F->getFormatIdx() == FormatIdx && F->getFirstArg() == FirstArg) { // If we don't have a valid location for this attribute, adopt the // location. @@ -3328,8 +3284,8 @@ } } - return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, - FirstArg, AttrSpellingListIndex); + return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, FirstArg, + AttrSpellingListIndex); } /// Handle __attribute__((format(type,idx,firstarg))) attributes based on @@ -3385,7 +3341,7 @@ if (ArgIdx == 0) { S.Diag(AL.getLoc(), diag::err_format_attribute_implicit_this_format_string) - << IdxExpr->getSourceRange(); + << IdxExpr->getSourceRange(); return; } ArgIdx--; @@ -3397,8 +3353,8 @@ if (Kind == CFStringFormat) { if (!isCFStringType(Ty, S.Context)) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) - << "a CFString" << IdxExpr->getSourceRange() - << getFunctionOrMethodParamRange(D, ArgIdx); + << "a CFString" << IdxExpr->getSourceRange() + << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (Kind == NSStringFormat) { @@ -3406,15 +3362,15 @@ // semantics? if (!isNSStringType(Ty, S.Context)) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) - << "an NSString" << IdxExpr->getSourceRange() - << getFunctionOrMethodParamRange(D, ArgIdx); + << "an NSString" << IdxExpr->getSourceRange() + << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType()) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) - << "a string type" << IdxExpr->getSourceRange() - << getFunctionOrMethodParamRange(D, ArgIdx); + << "a string type" << IdxExpr->getSourceRange() + << getFunctionOrMethodParamRange(D, ArgIdx); return; } @@ -3439,18 +3395,17 @@ if (Kind == StrftimeFormat) { if (FirstArg != 0) { S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) - << FirstArgExpr->getSourceRange(); + << FirstArgExpr->getSourceRange(); return; } - // if 0 it disables parameter checking (to use with e.g. va_list) + // if 0 it disables parameter checking (to use with e.g. va_list) } else if (FirstArg != 0 && FirstArg != NumArgs) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) << AL << 3 << FirstArgExpr->getSourceRange(); return; } - FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II, - Idx, FirstArg, + FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II, Idx, FirstArg, AL.getAttributeSpellingListIndex()); if (NewAttr) D->addAttr(NewAttr); @@ -3606,8 +3561,8 @@ RD = dyn_cast(D); if (!RD || !RD->isUnion()) { - S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL - << ExpectedUnion; + S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) + << AL << ExpectedUnion; return; } @@ -3619,7 +3574,7 @@ } RecordDecl::field_iterator Field = RD->field_begin(), - FieldEnd = RD->field_end(); + FieldEnd = RD->field_end(); if (Field == FieldEnd) { S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); return; @@ -3630,7 +3585,7 @@ if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { S.Diag(FirstField->getLocation(), diag::warn_transparent_union_attribute_floating) - << FirstType->isVectorType() << FirstType; + << FirstType->isVectorType() << FirstType; return; } @@ -3651,22 +3606,21 @@ S.Context.getTypeAlign(FieldType) > FirstAlign) { // Warn if we drop the attribute. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; - unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) - : S.Context.getTypeAlign(FieldType); + unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType) + : S.Context.getTypeAlign(FieldType); S.Diag(Field->getLocation(), - diag::warn_transparent_union_attribute_field_size_align) - << isSize << Field->getDeclName() << FieldBits; - unsigned FirstBits = isSize? FirstSize : FirstAlign; + diag::warn_transparent_union_attribute_field_size_align) + << isSize << Field->getDeclName() << FieldBits; + unsigned FirstBits = isSize ? FirstSize : FirstAlign; S.Diag(FirstField->getLocation(), diag::note_transparent_union_first_field_size_align) - << isSize << FirstBits; + << isSize << FirstBits; return; } } - RD->addAttr(::new (S.Context) - TransparentUnionAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + RD->addAttr(::new (S.Context) TransparentUnionAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -3682,9 +3636,8 @@ return; } - D->addAttr(::new (S.Context) - AnnotateAttr(AL.getRange(), S.Context, Str, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AnnotateAttr( + AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -3708,28 +3661,26 @@ if (!T->isDependentType() && !T->isAnyPointerType() && !T->isReferenceType() && !T->isMemberPointerType()) { Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) - << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); + << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); return; } if (!E->isValueDependent()) { llvm::APSInt Alignment; - ExprResult ICE - = VerifyIntegerConstantExpression(E, &Alignment, - diag::err_align_value_attribute_argument_not_int, - /*AllowFold*/ false); + ExprResult ICE = VerifyIntegerConstantExpression( + E, &Alignment, diag::err_align_value_attribute_argument_not_int, + /*AllowFold*/ false); if (ICE.isInvalid()) return; if (!Alignment.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) - << E->getSourceRange(); + << E->getSourceRange(); return; } - D->addAttr(::new (Context) - AlignValueAttr(AttrRange, Context, ICE.get(), - SpellingListIndex)); + D->addAttr(::new (Context) AlignValueAttr(AttrRange, Context, ICE.get(), + SpellingListIndex)); return; } @@ -3745,8 +3696,9 @@ } if (AL.getNumArgs() == 0) { - D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context, - true, nullptr, AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) + AlignedAttr(AL.getRange(), S.Context, true, nullptr, + AL.getAttributeSpellingListIndex())); return; } @@ -3794,14 +3746,15 @@ if (FD->isBitField()) DiagKind = 3; } else if (!isa(D)) { - Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr - << (TmpAttr.isC11() ? ExpectedVariableOrField - : ExpectedVariableFieldOrTag); + Diag(AttrLoc, diag::err_attribute_wrong_decl_type) + << &TmpAttr + << (TmpAttr.isC11() ? ExpectedVariableOrField + : ExpectedVariableFieldOrTag); return; } if (DiagKind != -1) { Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) - << &TmpAttr << DiagKind; + << &TmpAttr << DiagKind; return; } } @@ -3827,10 +3780,9 @@ // FIXME: Cache the number on the AL object? llvm::APSInt Alignment; - ExprResult ICE - = VerifyIntegerConstantExpression(E, &Alignment, - diag::err_aligned_attribute_argument_not_int, - /*AllowFold*/ false); + ExprResult ICE = VerifyIntegerConstantExpression( + E, &Alignment, diag::err_aligned_attribute_argument_not_int, + /*AllowFold*/ false); if (ICE.isInvalid()) return; @@ -3844,7 +3796,7 @@ if (!(TmpAttr.isAlignas() && !Alignment)) { if (!llvm::isPowerOf2_64(AlignVal)) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) - << E->getSourceRange(); + << E->getSourceRange(); return; } } @@ -3854,8 +3806,8 @@ Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 : 268435456; if (AlignVal > MaxValidAlignment) { - Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment - << E->getSourceRange(); + Diag(AttrLoc, diag::err_attribute_aligned_too_great) + << MaxValidAlignment << E->getSourceRange(); return; } @@ -3872,8 +3824,8 @@ } } - AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, - ICE.get(), SpellingListIndex); + AlignedAttr *AA = ::new (Context) + AlignedAttr(AttrRange, Context, true, ICE.get(), SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } @@ -3882,8 +3834,8 @@ unsigned SpellingListIndex, bool IsPackExpansion) { // FIXME: Cache the number on the AL object if non-dependent? // FIXME: Perform checking of type validity - AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, - SpellingListIndex); + AlignedAttr *AA = ::new (Context) + AlignedAttr(AttrRange, Context, false, TS, SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } @@ -3921,7 +3873,7 @@ CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); if (NaturalAlign > RequestedAlign) Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) - << DiagTy << (unsigned)NaturalAlign.getQuantity(); + << DiagTy << (unsigned)NaturalAlign.getQuantity(); } } @@ -4086,7 +4038,7 @@ if (OldTy->isDependentType()) { D->addAttr(::new (Context) - ModeAttr(AttrRange, Context, Name, SpellingListIndex)); + ModeAttr(AttrRange, Context, Name, SpellingListIndex)); return; } @@ -4169,13 +4121,12 @@ cast(D)->setType(NewTy); D->addAttr(::new (Context) - ModeAttr(AttrRange, Context, Name, SpellingListIndex)); + ModeAttr(AttrRange, Context, Name, SpellingListIndex)); } static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - D->addAttr(::new (S.Context) - NoDebugAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) NoDebugAttr(AL.getRange(), S.Context, + AL.getAttributeSpellingListIndex())); } AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, @@ -4190,8 +4141,8 @@ if (D->hasAttr()) return nullptr; - return ::new (Context) AlwaysInlineAttr(Range, Context, - AttrSpellingListIndex); + return ::new (Context) + AlwaysInlineAttr(Range, Context, AttrSpellingListIndex); } CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) { @@ -4217,8 +4168,9 @@ // ImplicitParm or VarTemplateSpecialization). if (VD->getKind() != Decl::Var) { Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) - << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass - : ExpectedVariableOrFunction); + << AL + << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass + : ExpectedVariableOrFunction); return nullptr; } // Attribute does not apply to non-static local variables. @@ -4241,8 +4193,9 @@ // ImplicitParm or VarTemplateSpecialization). if (VD->getKind() != Decl::Var) { Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type) - << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass - : ExpectedVariableOrFunction); + << &AL + << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass + : ExpectedVariableOrFunction); return nullptr; } // Attribute does not apply to non-static local variables. @@ -4298,8 +4251,8 @@ if (D->hasAttr()) return nullptr; - return ::new (Context) OptimizeNoneAttr(Range, Context, - AttrSpellingListIndex); + return ::new (Context) + OptimizeNoneAttr(Range, Context, AttrSpellingListIndex); } SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr( @@ -4316,8 +4269,7 @@ return; if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( - D, AL.getRange(), AL.getName(), - AL.getAttributeSpellingListIndex())) + D, AL.getRange(), AL.getName(), AL.getAttributeSpellingListIndex())) D->addAttr(Inline); } @@ -4390,9 +4342,8 @@ if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD; - D->addAttr(::new (S.Context) - CUDAGlobalAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) CUDAGlobalAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -4402,18 +4353,18 @@ return; } - D->addAttr(::new (S.Context) - GNUInlineAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) GNUInlineAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - if (hasDeclarator(D)) return; + if (hasDeclarator(D)) + return; // Diagnostic is emitted elsewhere: here we store the (valid) AL // in the Decl node for syntactic reasoning, e.g., pretty-printing. CallingConv CC; - if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) + if (S.CheckCallingConvAttr(AL, CC, /*FD*/ nullptr)) return; if (!isa(D)) { @@ -4424,49 +4375,40 @@ switch (AL.getKind()) { case ParsedAttr::AT_FastCall: - D->addAttr(::new (S.Context) - FastCallAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) FastCallAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_StdCall: - D->addAttr(::new (S.Context) - StdCallAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) StdCallAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_ThisCall: - D->addAttr(::new (S.Context) - ThisCallAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ThisCallAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_CDecl: - D->addAttr(::new (S.Context) - CDeclAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) CDeclAttr(AL.getRange(), S.Context, + AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_Pascal: - D->addAttr(::new (S.Context) - PascalAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) PascalAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_SwiftCall: - D->addAttr(::new (S.Context) - SwiftCallAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) SwiftCallAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_VectorCall: - D->addAttr(::new (S.Context) - VectorCallAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) VectorCallAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_MSABI: - D->addAttr(::new (S.Context) - MSABIAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) MSABIAttr(AL.getRange(), S.Context, + AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_SysVABI: - D->addAttr(::new (S.Context) - SysVABIAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) SysVABIAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_RegCall: D->addAttr(::new (S.Context) RegCallAttr( @@ -4485,20 +4427,17 @@ llvm_unreachable("unexpected calling convention in pcs attribute"); } - D->addAttr(::new (S.Context) - PcsAttr(AL.getRange(), S.Context, PCS, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) PcsAttr(AL.getRange(), S.Context, PCS, + AL.getAttributeSpellingListIndex())); return; } case ParsedAttr::AT_AArch64VectorPcs: - D->addAttr(::new(S.Context) - AArch64VectorPcsAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AArch64VectorPcsAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_IntelOclBicc: - D->addAttr(::new (S.Context) - IntelOclBiccAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) IntelOclBiccAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_PreserveMost: D->addAttr(::new (S.Context) PreserveMostAttr( @@ -4539,7 +4478,7 @@ return true; if (Attrs.hasProcessingCache()) { - CC = (CallingConv) Attrs.getProcessingCache(); + CC = (CallingConv)Attrs.getProcessingCache(); return false; } @@ -4579,12 +4518,11 @@ CC = CC_X86RegCall; break; case ParsedAttr::AT_MSABI: - CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : - CC_Win64; + CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : CC_Win64; break; case ParsedAttr::AT_SysVABI: - CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : - CC_C; + CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV + : CC_C; break; case ParsedAttr::AT_Pcs: { StringRef StrRef; @@ -4613,7 +4551,8 @@ case ParsedAttr::AT_PreserveAll: CC = CC_PreserveAll; break; - default: llvm_unreachable("unexpected attribute kind"); + default: + llvm_unreachable("unexpected attribute kind"); } TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK; @@ -4665,7 +4604,7 @@ CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); } - Attrs.setProcessingCache((unsigned) CC); + Attrs.setProcessingCache((unsigned)CC); return false; } @@ -4716,7 +4655,7 @@ if (auto existingAttr = D->getAttr()) { if (existingAttr->getABI() != abi) { Diag(range.getBegin(), diag::err_attributes_are_not_compatible) - << getParameterABISpelling(abi) << existingAttr; + << getParameterABISpelling(abi) << existingAttr; Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); return; } @@ -4729,31 +4668,27 @@ case ParameterABI::SwiftContext: if (!isValidSwiftContextType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) - << getParameterABISpelling(abi) - << /*pointer to pointer */ 0 << type; + << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; } - D->addAttr(::new (Context) - SwiftContextAttr(range, Context, spellingIndex)); + D->addAttr(::new (Context) SwiftContextAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftErrorResult: if (!isValidSwiftErrorResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) - << getParameterABISpelling(abi) - << /*pointer to pointer */ 1 << type; + << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; } D->addAttr(::new (Context) - SwiftErrorResultAttr(range, Context, spellingIndex)); + SwiftErrorResultAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftIndirectResult: if (!isValidSwiftIndirectResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) - << getParameterABISpelling(abi) - << /*pointer*/ 0 << type; + << getParameterABISpelling(abi) << /*pointer*/ 0 << type; } D->addAttr(::new (Context) - SwiftIndirectResultAttr(range, Context, spellingIndex)); + SwiftIndirectResultAttr(range, Context, spellingIndex)); return; } llvm_unreachable("bad parameter ABI attribute"); @@ -4779,7 +4714,7 @@ if (Context.getTargetInfo().getRegParmMax() == 0) { Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) - << NumParamsExpr->getSourceRange(); + << NumParamsExpr->getSourceRange(); AL.setInvalid(); return true; } @@ -4787,7 +4722,8 @@ numParams = NP; if (numParams > Context.getTargetInfo().getRegParmMax()) { Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) - << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); + << Context.getTargetInfo().getRegParmMax() + << NumParamsExpr->getSourceRange(); AL.setInvalid(); return true; } @@ -4818,8 +4754,8 @@ } // Make sure we can fit it in 32 bits. if (!I.isIntN(32)) { - S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) - << 32 << /* Unsigned */ 1; + S.Diag(E->getExprLoc(), diag::err_ice_too_large) + << I.toString(10, false) << 32 << /* Unsigned */ 1; return nullptr; } if (I < 0) @@ -4918,12 +4854,10 @@ S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); assert(MatchingCTypeLoc && "no type source info for attribute argument"); - D->addAttr(::new (S.Context) - TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind, - MatchingCTypeLoc, - AL.getLayoutCompatible(), - AL.getMustBeNull(), - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) TypeTagForDatatypeAttr( + AL.getRange(), S.Context, PointerKind, MatchingCTypeLoc, + AL.getLayoutCompatible(), AL.getMustBeNull(), + AL.getAttributeSpellingListIndex())); } static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -4971,13 +4905,15 @@ switch (K) { case RetainOwnershipKind::OS: handleSimpleAttributeOrDiagnose( - *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()), + *this, VD, SR, SpellingIndex, + isValidSubjectOfOSAttribute(VD->getType()), diag::warn_ns_attribute_wrong_parameter_type, /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1); return; case RetainOwnershipKind::NS: handleSimpleAttributeOrDiagnose( - *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()), + *this, VD, SR, SpellingIndex, + isValidSubjectOfNSAttribute(VD->getType()), // These attributes are normally just advisory, but in ARC, ns_consumed // is significant. Allow non-dependent code to contain inappropriate @@ -4993,7 +4929,7 @@ *this, VD, SR, SpellingIndex, isValidSubjectOfCFAttribute(VD->getType()), diag::warn_ns_attribute_wrong_parameter_type, - /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1); + /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/ 1); return; } } @@ -5060,8 +4996,8 @@ // Attributes on parameters are used for out-parameters, // passed as pointers-to-pointers. unsigned DiagID = K == Sema::RetainOwnershipKind::CF - ? /*pointer-to-CF-pointer*/2 - : /*pointer-to-OSObject-pointer*/3; + ? /*pointer-to-CF-pointer*/ 2 + : /*pointer-to-OSObject-pointer*/ 3; ReturnType = Param->getType()->getPointeeType(); if (ReturnType.isNull()) { S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) @@ -5073,7 +5009,8 @@ } else { AttributeDeclKind ExpectedDeclKind; switch (AL.getKind()) { - default: llvm_unreachable("invalid ownership attribute"); + default: + llvm_unreachable("invalid ownership attribute"); case ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NSReturnsAutoreleased: case ParsedAttr::AT_NSReturnsNotRetained: @@ -5096,7 +5033,8 @@ bool Cf; unsigned ParmDiagID = 2; // Pointer-to-CF-pointer switch (AL.getKind()) { - default: llvm_unreachable("invalid ownership attribute"); + default: + llvm_unreachable("invalid ownership attribute"); case ParsedAttr::AT_NSReturnsRetained: TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); Cf = false; @@ -5131,11 +5069,7 @@ << AL << ParmDiagID << AL.getRange(); } else { // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. - enum : unsigned { - Function, - Method, - Property - } SubjectKind = Function; + enum : unsigned { Function, Method, Property } SubjectKind = Function; if (isa(D)) SubjectKind = Method; else if (isa(D)) @@ -5147,29 +5081,29 @@ } switch (AL.getKind()) { - default: - llvm_unreachable("invalid ownership attribute"); - case ParsedAttr::AT_NSReturnsAutoreleased: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_CFReturnsNotRetained: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_NSReturnsNotRetained: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_CFReturnsRetained: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_NSReturnsRetained: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_OSReturnsRetained: - handleSimpleAttribute(S, D, AL); - return; - case ParsedAttr::AT_OSReturnsNotRetained: - handleSimpleAttribute(S, D, AL); - return; + default: + llvm_unreachable("invalid ownership attribute"); + case ParsedAttr::AT_NSReturnsAutoreleased: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_CFReturnsNotRetained: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_NSReturnsNotRetained: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_CFReturnsRetained: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_NSReturnsRetained: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_OSReturnsRetained: + handleSimpleAttribute(S, D, AL); + return; + case ParsedAttr::AT_OSReturnsNotRetained: + handleSimpleAttribute(S, D, AL); + return; }; } @@ -5206,14 +5140,14 @@ const DeclContext *DC = Method->getDeclContext(); if (const auto *PDecl = dyn_cast_or_null(DC)) { - S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs - << 0; + S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) + << Attrs << 0; S.Diag(PDecl->getLocation(), diag::note_protocol_decl); return; } if (Method->getMethodFamily() == OMF_dealloc) { - S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs - << 1; + S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) + << Attrs << 1; return; } @@ -5245,8 +5179,8 @@ } D->addAttr(::new (S.Context) - ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, - AL.getAttributeSpellingListIndex())); + ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, + AL.getAttributeSpellingListIndex())); } static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, @@ -5259,8 +5193,8 @@ } D->addAttr(::new (S.Context) - ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, - AL.getAttributeSpellingListIndex())); + ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, + AL.getAttributeSpellingListIndex())); } static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, @@ -5272,13 +5206,12 @@ return; } IdentifierInfo *ClassMethod = - AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; + AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; IdentifierInfo *InstanceMethod = - AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; - D->addAttr(::new (S.Context) - ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass, - ClassMethod, InstanceMethod, - AL.getAttributeSpellingListIndex())); + AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; + D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr( + AL.getRange(), S.Context, RelatedClass, ClassMethod, InstanceMethod, + AL.getAttributeSpellingListIndex())); } static void handleObjCDesignatedInitializer(Sema &S, Decl *D, @@ -5304,9 +5237,25 @@ return; IFace->setHasDesignatedInitializers(); - D->addAttr(::new (S.Context) - ObjCDesignatedInitializerAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); +} + +static void handleRequireDesignatedInit(Sema &S, Decl *D, + const ParsedAttr &AL) { + if (TagDecl *TD = dyn_cast(D)) + TD->addAttr(::new (S.Context) RequireDesignatedInitAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); + else + S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); +} + +static void handleRequired(Sema &S, Decl *D, const ParsedAttr &AL) { + if (FieldDecl *FD = dyn_cast(D)) + FD->addAttr(::new (S.Context) RequiredAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); + else + S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); } static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -5314,9 +5263,8 @@ if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) return; D->addAttr(::new (S.Context) - ObjCRuntimeNameAttr(AL.getRange(), S.Context, - MetaDataName, - AL.getAttributeSpellingListIndex())); + ObjCRuntimeNameAttr(AL.getRange(), S.Context, MetaDataName, + AL.getAttributeSpellingListIndex())); } // When a user wants to use objc_boxable with a union or struct @@ -5333,9 +5281,8 @@ } if (RD) { - ObjCBoxableAttr *BoxableAttr = ::new (S.Context) - ObjCBoxableAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex()); + ObjCBoxableAttr *BoxableAttr = ::new (S.Context) ObjCBoxableAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()); RD->addAttr(BoxableAttr); if (notify) { // we need to notify ASTReader/ASTWriter about @@ -5347,7 +5294,8 @@ } static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - if (hasDeclarator(D)) return; + if (hasDeclarator(D)) + return; S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type) << AL.getRange() << AL << ExpectedVariable; @@ -5358,10 +5306,8 @@ const auto *VD = cast(D); QualType QT = VD->getType(); - if (!QT->isDependentType() && - !QT->isObjCLifetimeType()) { - S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) - << QT; + if (!QT->isDependentType() && !QT->isObjCLifetimeType()) { + S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) << QT; return; } @@ -5389,9 +5335,8 @@ break; } - D->addAttr(::new (S.Context) - ObjCPreciseLifetimeAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// @@ -5468,8 +5413,7 @@ return; } MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( - D, AL.getRange(), /*BestCase=*/true, - AL.getAttributeSpellingListIndex(), + D, AL.getRange(), /*BestCase=*/true, AL.getAttributeSpellingListIndex(), (MSInheritanceAttr::Spelling)AL.getSemanticSpelling()); if (IA) { D->addAttr(IA); @@ -5523,8 +5467,8 @@ Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); D->addAttr(::new (S.Context) - AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(), - AL.getAttributeSpellingListIndex())); + AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(), + AL.getAttributeSpellingListIndex())); } static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -5544,14 +5488,14 @@ ARMInterruptAttr::InterruptType Kind; if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { - S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str - << ArgLoc; + S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) + << AL << Str << ArgLoc; return; } unsigned Index = AL.getAttributeSpellingListIndex(); D->addAttr(::new (S.Context) - ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index)); + ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index)); } static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -5602,9 +5546,8 @@ return; } - D->addAttr(::new (S.Context) - MSP430InterruptAttr(AL.getLoc(), S.Context, Num, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) MSP430InterruptAttr( + AL.getLoc(), S.Context, Num, AL.getAttributeSpellingListIndex())); D->addAttr(UsedAttr::CreateImplicit(S.Context)); } @@ -5755,7 +5698,8 @@ handleSimpleAttribute(S, D, AL); } -static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { +static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, + const ParsedAttr &AL) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'import_module'" << ExpectedFunction; @@ -5774,11 +5718,11 @@ return; FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr( - AL.getRange(), S.Context, Str, - AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } -static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { +static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, + const ParsedAttr &AL) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'import_name'" << ExpectedFunction; @@ -5797,16 +5741,14 @@ return; FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr( - AL.getRange(), S.Context, Str, - AL.getAttributeSpellingListIndex())); + AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } -static void handleRISCVInterruptAttr(Sema &S, Decl *D, - const ParsedAttr &AL) { +static void handleRISCVInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Warn about repeated attributes. if (const auto *A = D->getAttr()) { S.Diag(AL.getRange().getBegin(), - diag::warn_riscv_repeated_interrupt_attribute); + diag::warn_riscv_repeated_interrupt_attribute); S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute); return; } @@ -5833,31 +5775,31 @@ if (D->getFunctionType() == nullptr) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) - << "'interrupt'" << ExpectedFunction; + << "'interrupt'" << ExpectedFunction; return; } if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) - << /*RISC-V*/ 2 << 0; + << /*RISC-V*/ 2 << 0; return; } if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) - << /*RISC-V*/ 2 << 1; + << /*RISC-V*/ 2 << 1; return; } RISCVInterruptAttr::InterruptType Kind; if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { - S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str - << ArgLoc; + S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) + << AL << Str << ArgLoc; return; } D->addAttr(::new (S.Context) RISCVInterruptAttr( - AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex())); + AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex())); } static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -6004,9 +5946,8 @@ if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) return; - D->addAttr(::new (S.Context) - AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr( + AL.getLoc(), S.Context, NumSGPR, AL.getAttributeSpellingListIndex())); } static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -6015,9 +5956,8 @@ if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) return; - D->addAttr(::new (S.Context) - AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr( + AL.getLoc(), S.Context, NumVGPR, AL.getAttributeSpellingListIndex())); } static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, @@ -6031,7 +5971,7 @@ // Also don't warn on function pointer typedefs. const auto *TD = dyn_cast(D); if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || - TD->getUnderlyingType()->isFunctionType())) + TD->getUnderlyingType()->isFunctionType())) return; // Attribute can only be applied to function types. if (!isa(D)) { @@ -6040,9 +5980,8 @@ return; } - D->addAttr(::new (S.Context) - X86ForceAlignArgPointerAttr(AL.getRange(), S.Context, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr( + AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -6063,9 +6002,8 @@ // have to multiply by 100 now. Version *= 100; - D->addAttr(::new (S.Context) - LayoutVersionAttr(AL.getRange(), S.Context, Version, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) LayoutVersionAttr( + AL.getRange(), S.Context, Version, AL.getAttributeSpellingListIndex())); } DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, @@ -6183,44 +6121,40 @@ if (!N.equals_lower("mutex") && !N.equals_lower("role")) S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; - D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N, - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) CapabilityAttr( + AL.getRange(), S.Context, N, AL.getAttributeSpellingListIndex())); } static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - SmallVector Args; + SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; - D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context, - Args.data(), Args.size(), - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AssertCapabilityAttr( + AL.getRange(), S.Context, Args.data(), Args.size(), + AL.getAttributeSpellingListIndex())); } static void handleAcquireCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - SmallVector Args; + SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; - D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(), - S.Context, - Args.data(), Args.size(), - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) AcquireCapabilityAttr( + AL.getRange(), S.Context, Args.data(), Args.size(), + AL.getAttributeSpellingListIndex())); } static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { - SmallVector Args; + SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; - D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(), - S.Context, - AL.getArgAsExpr(0), - Args.data(), - Args.size(), - AL.getAttributeSpellingListIndex())); + D->addAttr(::new (S.Context) TryAcquireCapabilityAttr( + AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), + AL.getAttributeSpellingListIndex())); } static void handleReleaseCapabilityAttr(Sema &S, Decl *D, @@ -6240,14 +6174,14 @@ return; // check that all arguments are lockable objects - SmallVector Args; + SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); if (Args.empty()) return; RequiresCapabilityAttr *RCA = ::new (S.Context) - RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(), - Args.size(), AL.getAttributeSpellingListIndex()); + RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(), Args.size(), + AL.getAttributeSpellingListIndex()); D->addAttr(RCA); } @@ -6356,8 +6290,8 @@ S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) << AL << "2.0" << 0; else - S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL - << "2.0"; + S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) + << AL << "2.0"; } /// Handles semantic checking for features that are common to all attributes, @@ -6421,11 +6355,10 @@ } } - // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an - // image object can be read and written. - // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe - // object. Using the read_write (or __read_write) qualifier with the pipe - // qualifier is a compilation error. + // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that + // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel + // cannot read from and write to the same pipe object. Using the read_write + // (or __read_write) qualifier with the pipe qualifier is a compilation error. if (const auto *PDecl = dyn_cast(D)) { const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); if (AL.getName()->getName().find("read_write") != StringRef::npos) { @@ -6452,9 +6385,11 @@ } if (A.getKind() == ParsedAttr::AT_AlwaysDestroy) - handleSimpleAttributeWithExclusions(S, D, A); + handleSimpleAttributeWithExclusions(S, D, + A); else - handleSimpleAttributeWithExclusions(S, D, A); + handleSimpleAttributeWithExclusions(S, D, + A); } static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { @@ -6914,8 +6849,8 @@ case ParsedAttr::AT_NSConsumed: case ParsedAttr::AT_OSConsumed: S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(), - parsedAttrToRetainOwnershipKind(AL), - /*IsTemplateInstantiation=*/false); + parsedAttrToRetainOwnershipKind(AL), + /*IsTemplateInstantiation=*/false); break; case ParsedAttr::AT_NSConsumesSelf: handleSimpleAttribute(S, D, AL); @@ -6959,6 +6894,12 @@ case ParsedAttr::AT_RequireConstantInit: handleSimpleAttribute(S, D, AL); break; + case ParsedAttr::AT_RequireDesignatedInit: + handleRequireDesignatedInit(S, D, AL); + break; + case ParsedAttr::AT_Required: + handleRequired(S, D, AL); + break; case ParsedAttr::AT_InitPriority: handleInitPriorityAttr(S, D, AL); break; @@ -7439,8 +7380,8 @@ S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL << AL.getRange(); } else { - S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL - << AL.getRange(); + S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) + << AL << AL.getRange(); } } } @@ -7457,8 +7398,8 @@ /// DeclClonePragmaWeak - clone existing decl (maybe definition), /// \#pragma weak needs a non-definition decl and source may not have one. -NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, - SourceLocation Loc) { +NamedDecl *Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, + SourceLocation Loc) { assert(isa(ND) || isa(ND)); NamedDecl *NewD = nullptr; if (auto *FD = dyn_cast(ND)) { @@ -7480,7 +7421,7 @@ // a typedef. QualType FDTy = FD->getType(); if (const auto *FT = FDTy->getAs()) { - SmallVector Params; + SmallVector Params; for (const auto &AI : FT->param_types()) { ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); Param->setScopeInfo(0, Params.size()); @@ -7502,13 +7443,14 @@ /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak /// applied to it, possibly with an alias. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { - if (W.getUsed()) return; // only do this once + if (W.getUsed()) + return; // only do this once W.setUsed(true); if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) IdentifierInfo *NDId = ND->getIdentifier(); NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); - NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), - W.getLocation())); + NewD->addAttr( + AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); WeakTopLevelDecl.push_back(NewD); // FIXME: "hideous" code from Sema::LazilyCreateBuiltin @@ -7581,8 +7523,7 @@ // Private ivars are always okay. Unfortunately, people don't // always properly make their ivars private, even in system headers. // Plus we need to make fields okay, too. - if (!isa(D) && !isa(D) && - !isa(D)) + if (!isa(D) && !isa(D) && !isa(D)) return false; // Silently accept unsupported uses of __weak in both user and system @@ -7710,8 +7651,8 @@ // For +new, infer availability from -init. if (const auto *MD = dyn_cast(D)) { if (S.NSAPIObj && ClassReceiver) { - ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod( - S.NSAPIObj->getInitSelector()); + ObjCMethodDecl *Init = + ClassReceiver->lookupInstanceMethod(S.NSAPIObj->getInitSelector()); if (Init && Result == AR_Available && MD->isClassMethod() && MD->getSelector() == S.NSAPIObj->getNewSelector() && MD->definedInNSObject(S.getASTContext())) { @@ -7724,7 +7665,6 @@ return {Result, D}; } - /// whether we should emit a diagnostic for \c K and \c DeclVersion in /// the context of \c Ctx. For example, we should emit an unavailable diagnostic /// in a deprecated context, but not the other way around. @@ -7919,14 +7859,11 @@ /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl /// and OffendingDecl is the EnumDecl. -static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, - Decl *Ctx, const NamedDecl *ReferringDecl, - const NamedDecl *OffendingDecl, - StringRef Message, - ArrayRef Locs, - const ObjCInterfaceDecl *UnknownObjCClass, - const ObjCPropertyDecl *ObjCProperty, - bool ObjCPropertyAccess) { +static void DoEmitAvailabilityWarning( + Sema &S, AvailabilityResult K, Decl *Ctx, const NamedDecl *ReferringDecl, + const NamedDecl *OffendingDecl, StringRef Message, + ArrayRef Locs, const ObjCInterfaceDecl *UnknownObjCClass, + const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Diagnostics for deprecated or unavailable. unsigned diag, diag_message, diag_fwdclass_message; unsigned diag_available_here = diag::note_availability_specified_here; @@ -8058,7 +7995,8 @@ }; switch (AL->getImplicitReason()) { - case UnavailableAttr::IR_None: break; + case UnavailableAttr::IR_None: + break; case UnavailableAttr::IR_ARCForbiddenType: flagARCError(); @@ -8105,8 +8043,7 @@ CharSourceRange UseRange; if (!Replacement.empty()) - UseRange = - CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); + UseRange = CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); if (UseRange.isValid()) { if (const auto *MethodDecl = dyn_cast(ReferringDecl)) { Selector Sel = MethodDecl->getSelector(); @@ -8148,7 +8085,7 @@ } S.Diag(NoteLocation, diag_available_here) - << OffendingDecl << available_here_select_kind; + << OffendingDecl << available_here_select_kind; } static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, @@ -8172,7 +8109,8 @@ // When delaying diagnostics to run in the context of a parsed // declaration, we only want to actually emit anything if parsing // succeeds. - if (!decl) return; + if (!decl) + return; // We emit all the active diagnostics in this pool or any of its // parents. In general, we'll get one pool for the decl spec @@ -8184,10 +8122,11 @@ const DelayedDiagnosticPool *pool = &poppedPool; do { bool AnyAccessFailures = false; - for (DelayedDiagnosticPool::pool_iterator - i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { + for (DelayedDiagnosticPool::pool_iterator i = pool->pool_begin(), + e = pool->pool_end(); + i != e; ++i) { // This const_cast is a bit lame. Really, Triggered should be mutable. - DelayedDiagnostic &diag = const_cast(*i); + DelayedDiagnostic &diag = const_cast(*i); if (diag.Triggered) continue; @@ -8227,26 +8166,22 @@ curPool->steal(pool); } -static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR, - const NamedDecl *ReferringDecl, - const NamedDecl *OffendingDecl, - StringRef Message, - ArrayRef Locs, - const ObjCInterfaceDecl *UnknownObjCClass, - const ObjCPropertyDecl *ObjCProperty, - bool ObjCPropertyAccess) { +static void EmitAvailabilityWarning( + Sema &S, AvailabilityResult AR, const NamedDecl *ReferringDecl, + const NamedDecl *OffendingDecl, StringRef Message, + ArrayRef Locs, const ObjCInterfaceDecl *UnknownObjCClass, + const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Delay if we're currently parsing a declaration. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { - S.DelayedDiagnostics.add( - DelayedDiagnostic::makeAvailability( - AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass, - ObjCProperty, Message, ObjCPropertyAccess)); + S.DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability( + AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass, ObjCProperty, + Message, ObjCPropertyAccess)); return; } Decl *Ctx = cast(S.getCurLexicalContext()); - DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl, - Message, Locs, UnknownObjCClass, ObjCProperty, + DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl, Message, + Locs, UnknownObjCClass, ObjCProperty, ObjCPropertyAccess); } @@ -8370,7 +8305,8 @@ bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) { if (PRE->isClassReceiver()) - DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation()); + DiagnoseDeclAvailability(PRE->getClassReceiver(), + PRE->getReceiverLocation()); return true; } @@ -8421,7 +8357,7 @@ return; const AvailabilityAttr *AA = - getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl); + getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl); VersionTuple Introduced = AA->getIntroduced(); if (AvailabilityStack.back() >= Introduced) @@ -8505,8 +8441,9 @@ const char *ExtraIndentation = " "; std::string FixItString; llvm::raw_string_ostream FixItOS(FixItString); - FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available" - : "__builtin_available") + FixItOS << "if (" + << (SemaRef.getLangOpts().ObjC ? "@available" + : "__builtin_available") << "(" << AvailabilityAttr::getPlatformNameSourceSpelling( SemaRef.getASTContext().getTargetInfo().getPlatformName()) @@ -8603,7 +8540,7 @@ ObjCInterfaceDecl *ClassReceiver) { std::string Message; AvailabilityResult Result; - const NamedDecl* OffendingDecl; + const NamedDecl *OffendingDecl; // See if this declaration is unavailable, deprecated, or partial. std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver); diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test --- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test +++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test @@ -122,6 +122,7 @@ // CHECK-NEXT: RenderScriptKernel (SubjectMatchRule_function) // CHECK-NEXT: ReqdWorkGroupSize (SubjectMatchRule_function) // CHECK-NEXT: RequireConstantInit (SubjectMatchRule_variable_is_global) +// CHECK-NEXT: Required (SubjectMatchRule_field) // CHECK-NEXT: Restrict (SubjectMatchRule_function) // CHECK-NEXT: ReturnTypestate (SubjectMatchRule_function, SubjectMatchRule_variable_is_parameter) // CHECK-NEXT: ReturnsNonNull (SubjectMatchRule_objc_method, SubjectMatchRule_function) diff --git a/clang/test/SemaCXX/attr-require-designated-init.cpp b/clang/test/SemaCXX/attr-require-designated-init.cpp new file mode 100644 --- /dev/null +++ b/clang/test/SemaCXX/attr-require-designated-init.cpp @@ -0,0 +1,104 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +#define ATTR __attribute__((require_designated_init)) + +// The require_designated_init attribute only applies to types. It will +// generate a warning when attached to variables, functions, arrays, etc. +int ATTR x; // expected-warning{{attribute only applies to types}} +void ATTR fun(int x) { // expected-warning{{attribute only applies to types}} + return; +} +int ATTR arr[10]; // expected-warning{{attribute only applies to types}} + +// Struct with one field with require_designated_init attribute +struct ATTR Foo { // expected-note 0+ {{required by 'require_designated_init' attribute here}} + int a; +}; + +// The following are invalid ways of initializing instances of this struct. +Foo f1; // expected-error{{variable declaration does not use designated initializer syntax}} +Foo f2{1}; // expected-error{{variable declaration does not use designated initializer syntax}} +Foo f3 = {1}; // expected-error{{variable declaration does not use designated initializer syntax}} +// The following are valid ways of initializing instances of this struct. +Foo f4{}; +Foo f5 = {}; +Foo f6{.a = 1}; +Foo f7 = {.a = 1}; + +// Struct with multiple fields wth require_designated_init attribute +struct ATTR Bar { // expected-note 0+ {{required by 'require_designated_init' attribute here}} + int b; + int c; +}; + +// The following are invalid ways of initializing instances of this struct. +Bar b1; // expected-error{{variable declaration does not use designated initializer syntax}} +Bar b2{1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Bar b3 = {1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Bar b4{.b = 1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Bar b5 = {.b = 1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +// The following are valid ways of initializing instances of this struct. +Bar b6{}; +Bar b7 = {}; +Bar b8{.b = 1}; +Bar b9 = {.b = 1}; +Bar b10{.b = 1, .c = 2}; +Bar b11 = {.b = 1, .c = 2}; +Bar b12 = {.c = 2, .b = 1}; + +// Struct without require_designated_init attribute +struct Baz { + int d; + int e; +}; + +// The following are all valid ways of initializing instances of this struct. +Baz z1; +Baz z2{}; +Baz z3 = {}; +Baz z4{1, 2}; +Baz z5 = {1, 2}; +Baz z6{.d = 1, .e = 2}; +Baz z7 = {.d = 1, .e = 2}; +Baz z8{1}; +Baz z9 = {1}; +Baz z10{.d = 1, 2}; +Baz z11 = {.d = 1, 2}; + +// The require_designated_init attribute can also be attached to unions. +union ATTR Uni { // expected-note 0+ {{required by 'require_designated_init' attribute here}} + int x; + int y; +}; + +// The following are invalid ways of initializing instances of this union. +Uni u1; // expected-error{{variable declaration does not use designated initializer syntax}} +Uni u2{1}; // expected-error{{variable declaration does not use designated initializer syntax}} +Uni u3 = {1}; // expected-error{{variable declaration does not use designated initializer syntax}} +// The following are valid ways of initializing instances of this union. +Uni u4{}; +Uni u5 = {}; +Uni u6{.x = 1}; +Uni u7 = {.x = 1}; + +// The require_designated_init attribute can also be attached to classes. +class ATTR Cla { // expected-note 0+ {{required by 'require_designated_init' attribute here}} +public: + int x; + int y; +}; + +// The following are invalid ways of initializing instances of this class. +Cla c1; // expected-error{{variable declaration does not use designated initializer syntax}} +Cla c2{1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Cla c3 = {1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Cla c4{.x = 1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +Cla c5 = {.x = 1, 2}; // expected-error{{variable declaration does not use designated initializer syntax}} +// The following are valid ways of initializing instances of this class. +Cla c6{}; +Cla c7 = {}; +Cla c8{.x = 1}; +Cla c9 = {.x = 1}; +Cla c10{.x = 1, .y = 2}; +Cla c11 = {.x = 1, .y = 2}; +Cla c12 = {.y = 2, .x = 1}; diff --git a/clang/test/SemaCXX/attr-required.cpp b/clang/test/SemaCXX/attr-required.cpp new file mode 100644 --- /dev/null +++ b/clang/test/SemaCXX/attr-required.cpp @@ -0,0 +1,63 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +#define ATTR __attribute__((required)) + +int ATTR x; // expected-warning{{'required' attribute only applies to non-static data members}} +void ATTR fun(int x) { // expected-warning{{'required' attribute only applies to non-static data members}} + return; +} +struct ATTR Foo { // expected-warning{{'required' attribute only applies to non-static data members}} + int x; +}; + +// Struct with one required field +struct Bar { + int ATTR y; // expected-note 0+ {{enforced by 'required' attribute here}} +}; + +// The following are invalid ways of initializing instances of this struct. +Bar b1; // expected-error{{initializer for variable b1 must explicitly initialize field y}} +Bar b2{}; // expected-error{{initializer for variable b2 must explicitly initialize field y}} +Bar b3{1}; // expected-error{{initializer for variable b3 must explicitly initialize field y}} + +// The following are valid ways of initializing instances of this struct. +Bar b6{.y = 1}; + +// Struct with multiple required fields +struct Baz { + int ATTR x; // expected-note 0+ {{enforced by 'required' attribute here}} + int y; + int ATTR z; // expected-note 0+ {{enforced by 'required' attribute here}} +}; + +// The following are invalid ways of initializing instances of this struct. +Baz z1; // expected-error{{initializer for variable z1 must explicitly initialize field x}} expected-error{{initializer for variable z1 must explicitly initialize field z}} +Baz z2{}; // expected-error{{initializer for variable z2 must explicitly initialize field x}} expected-error{{initializer for variable z2 must explicitly initialize field z}} +Baz z3{1, 2}; // expected-error{{initializer for variable z3 must explicitly initialize field x}} expected-error{{initializer for variable z3 must explicitly initialize field z}} +Baz z4{1, 2, 3}; // expected-error{{initializer for variable z4 must explicitly initialize field x}} expected-error{{initializer for variable z4 must explicitly initialize field z}} +Baz z5{.x = 1, 2}; // expected-error{{initializer for variable z5 must explicitly initialize field z}} +Baz z6{.x = 1, .y = 2}; // expected-error{{initializer for variable z6 must explicitly initialize field z}} + +// The following are valid ways of initializing instances of this struct. +Baz z7{.x = 1, .y = 2, .z = 3}; +Baz z8{.x = 1, .z = 3}; +Baz z9{.x = 1, 2, .z = 3}; + +// The required attribute can also be applied to public fields of classes. +class Cla { +public: + int ATTR x; // expected-note 0+ {{enforced by 'required' attribute here}} + int y; +}; + +// The following are invalid ways of initializing instances of this class. +Cla c1; // expected-error{{initializer for variable c1 must explicitly initialize field x}} +Cla c2{}; // expected-error{{initializer for variable c2 must explicitly initialize field x}} +Cla c3{1}; // expected-error{{initializer for variable c3 must explicitly initialize field x}} +Cla c4{1, 2}; // expected-error{{initializer for variable c4 must explicitly initialize field x}} +Cla c5{1, .y = 2}; // expected-error{{initializer for variable c5 must explicitly initialize field x}} + +// The following are valid ways of initializing instances of this class. +Cla c6{.x = 1}; +Cla c7{.x = 1, .y = 2}; +Cla c8{.x = 1, 2};