diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index 5508890f12b58..9fedb230ce397 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -1712,6 +1712,19 @@ class CXXConstructExpr : public Expr { CXXConstructExprBits.IsImmediateEscalating = Set; } + /// Returns the WarnUnusedResultAttr that is declared on the callee + /// or its return type declaration, together with a NamedDecl that + /// refers to the declaration the attribute is attached to. + std::pair + getUnusedResultAttr(const ASTContext &Ctx) const { + return getUnusedResultAttrImpl(getConstructor(), getType()); + } + + /// Returns true if this call expression should warn on unused results. + bool hasUnusedResultAttr(const ASTContext &Ctx) const { + return getUnusedResultAttr(Ctx).second != nullptr; + } + SourceLocation getBeginLoc() const LLVM_READONLY; SourceLocation getEndLoc() const LLVM_READONLY; SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; } diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp index efc0b35792613..bc1ddb80961a2 100644 --- a/clang/lib/Sema/SemaStmt.cpp +++ b/clang/lib/Sema/SemaStmt.cpp @@ -316,17 +316,10 @@ void DiagnoseUnused(Sema &S, const Expr *E, std::optional DiagID) { } } } else if (const auto *CE = dyn_cast(E)) { - if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { - const NamedDecl *OffendingDecl = nullptr; - const auto *A = Ctor->getAttr(); - if (!A) { - OffendingDecl = Ctor->getParent(); - A = OffendingDecl->getAttr(); - } - if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2, - /*isCtor=*/true)) - return; - } + auto [OffendingDecl, A] = CE->getUnusedResultAttr(S.Context); + if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2, + /*isCtor=*/true)) + return; } else if (const auto *ILE = dyn_cast(E)) { if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {