[clang-tools-extra] [clang-tidy] Detect redundant control flow in nested scopes (PR #242945)

via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 15 18:56:39 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clang-tidy

Author: Richard Thomson (LegalizeAdulthood)

<details>
<summary>Changes</summary>

Follow trailing blocks and final if branches when checking for redundant return and continue statements. Preserve semicolons in unbraced bodies so removing the keywords leaves valid null statements.

Add coverage for nested exits, all loop types, and necessary early exits. Verify that the rewritten code compiles.

Fixes #<!-- -->26965.

---
Full diff: https://github.com/llvm/llvm-project/pull/242945.diff


6 Files Affected:

- (modified) clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp (+48-23) 
- (modified) clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h (+4) 
- (modified) clang-tools-extra/docs/ReleaseNotes.md (+5) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/readability/redundant-control-flow.md (+8-3) 
- (added) clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow-nested.cpp (+260) 
- (modified) clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow.cpp (+16-2) 


``````````diff
diff --git a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
index 46cbaa1f703013..66f209832c5027 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
@@ -7,23 +7,14 @@
 //===----------------------------------------------------------------------===//
 
 #include "RedundantControlFlowCheck.h"
+#include "clang/AST/Stmt.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
 #include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::readability {
 
-namespace {
-
-AST_MATCHER_P(CompoundStmt, hasFinalStmt, StatementMatcher, InnerMatcher) {
-  return !Node.body_empty() &&
-         InnerMatcher.matches(*Node.body_back(), Finder, Builder);
-}
-
-} // namespace
-
 static constexpr StringRef RedundantReturnDiag =
     "redundant return statement at the end "
     "of a function with a void return type";
@@ -32,34 +23,68 @@ static constexpr StringRef RedundantContinueDiag =
     "end of loop statement";
 
 void RedundantControlFlowCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-      functionDecl(returns(voidType()),
-                   hasBody(compoundStmt(hasFinalStmt(
-                       returnStmt(unless(has(expr()))).bind("stmt"))))),
-      this);
+  Finder->addMatcher(functionDecl(returns(voidType()),
+                                  hasBody(compoundStmt().bind("return-body"))),
+                     this);
   Finder->addMatcher(mapAnyOf(forStmt, cxxForRangeStmt, whileStmt, doStmt)
-                         .with(hasBody(compoundStmt(
-                             hasFinalStmt(continueStmt().bind("stmt"))))),
+                         .with(hasBody(stmt().bind("continue-body"))),
                      this);
 }
 
 void RedundantControlFlowCheck::check(const MatchFinder::MatchResult &Result) {
-  const auto &RedundantStmt = *Result.Nodes.getNodeAs<Stmt>("stmt");
-  const SourceRange StmtRange = RedundantStmt.getSourceRange();
+  const auto *Body = Result.Nodes.getNodeAs<Stmt>("return-body");
+  const bool IsReturn = Body != nullptr;
+  if (!Body)
+    Body = Result.Nodes.getNodeAs<Stmt>("continue-body");
+  checkTrailingStmt(Result, Body, IsReturn, /*IsCompoundChild=*/false);
+}
+
+void RedundantControlFlowCheck::checkTrailingStmt(
+    const MatchFinder::MatchResult &Result, const Stmt *S, bool IsReturn,
+    bool IsCompoundChild) {
+  if (const auto *Block = dyn_cast<CompoundStmt>(S)) {
+    if (!Block->body_empty())
+      checkTrailingStmt(Result, Block->body_back(), IsReturn,
+                        /*IsCompoundChild=*/true);
+    return;
+  }
+  if (const auto *If = dyn_cast<IfStmt>(S)) {
+    checkTrailingStmt(Result, If->getThen(), IsReturn,
+                      /*IsCompoundChild=*/false);
+    if (const Stmt *Else = If->getElse())
+      checkTrailingStmt(Result, Else, IsReturn, /*IsCompoundChild=*/false);
+    return;
+  }
+
+  if (IsReturn) {
+    const auto *Return = dyn_cast<ReturnStmt>(S);
+    if (!Return || Return->getRetValue())
+      return;
+  } else if (!isa<ContinueStmt>(S)) {
+    return;
+  }
+
+  const SourceRange StmtRange = S->getSourceRange();
 
   if (StmtRange.getBegin().isMacroID())
     return;
 
+  const auto Diag =
+      diag(StmtRange.getBegin(),
+           IsReturn ? RedundantReturnDiag : RedundantContinueDiag);
+  if (!IsCompoundChild) {
+    // Keep a null statement as the body of an unbraced branch or loop.
+    Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(StmtRange));
+    return;
+  }
+
   const auto RemovedRange = CharSourceRange::getCharRange(
       StmtRange.getBegin(),
       Lexer::findLocationAfterToken(StmtRange.getEnd(), tok::semi,
                                     *Result.SourceManager, getLangOpts(),
                                     /*SkipTrailingWhitespaceAndNewLine=*/true));
 
-  diag(StmtRange.getBegin(), isa<ReturnStmt>(RedundantStmt)
-                                 ? RedundantReturnDiag
-                                 : RedundantContinueDiag)
-      << FixItHint::CreateRemoval(RemovedRange);
+  Diag << FixItHint::CreateRemoval(RemovedRange);
 }
 
 } // namespace clang::tidy::readability
diff --git a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h
index 028f9948f74abd..17256b1203f0eb 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h
@@ -30,6 +30,10 @@ class RedundantControlFlowCheck : public ClangTidyCheck {
   std::optional<TraversalKind> getCheckTraversalKind() const override {
     return TK_IgnoreUnlessSpelledInSource;
   }
+
+private:
+  void checkTrailingStmt(const ast_matchers::MatchFinder::MatchResult &Result,
+                         const Stmt *S, bool IsReturn, bool IsCompoundChild);
 };
 
 } // namespace clang::tidy::readability
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b6774370511feb..f8f06af37e3bd8 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -437,6 +437,11 @@ infrastructure are described first, followed by tool-specific sections.
   written to, such as the `expected` parameter of
   `atomic_compare_exchange_strong()`.
 
+- Improved {doc}`readability-redundant-control-flow
+  <clang-tidy/checks/readability/redundant-control-flow>` to detect
+  redundant `return` and `continue` statements in nested blocks and final
+  `if` branches.
+
 - Improved {doc}`readability-redundant-parentheses
   <clang-tidy/checks/readability/redundant-parentheses>` check:
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-control-flow.md b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-control-flow.md
index 4c10979bc1da1c..1370503341a8ad 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-control-flow.md
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-control-flow.md
@@ -3,13 +3,18 @@
 
 # readability-redundant-control-flow
 
-This check looks for procedures (functions returning no value) with `return`
-statements at the end of the function. Such `return` statements are
-redundant.
+This check looks for procedures (functions returning no value) with
+`return` statements at the end of the function. Such `return` statements
+are redundant.
 
 Loop statements (`for`, `while`, `do while`) are checked for redundant
 `continue` statements at the end of the loop body.
 
+The check also follows nested blocks and the branches of a final `if`
+statement. It preserves exits that skip subsequent statements, returns
+inside loops, and return expressions with side effects. For an unbraced
+branch or loop body, removing the keyword leaves a null statement.
+
 Examples:
 
 The following function `f` contains a redundant `return` statement:
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow-nested.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow-nested.cpp
new file mode 100644
index 00000000000000..8e7600cb357e31
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow-nested.cpp
@@ -0,0 +1,260 @@
+// RUN: %check_clang_tidy %s readability-redundant-control-flow %t
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only %t.cpp
+
+void work(int);
+
+void return_nested_scope() {
+  {
+    {
+      work(0);
+      return;
+    }
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: redundant return statement
+// CHECK-FIXES-LABEL: void return_nested_scope() {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: work(0);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void return_if(bool condition) {
+  if (condition) {
+    work(0);
+    return;
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: redundant return statement
+// CHECK-FIXES-LABEL: void return_if(bool condition) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: work(0);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void return_if_else(bool condition) {
+  if (condition) {
+    work(0);
+    return;
+  } else {
+    work(1);
+    return;
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-6]]:5: warning: redundant return statement
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: redundant return statement
+// CHECK-FIXES-LABEL: void return_if_else(bool condition) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: work(0);
+// CHECK-FIXES-NEXT: } else {
+// CHECK-FIXES-NEXT: work(1);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void continue_nested_scope(int n) {
+  for (int i = 0; i < n; ++i) {
+    {
+      {
+        work(i);
+        continue;
+      }
+    }
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: redundant continue statement
+// CHECK-FIXES-LABEL: void continue_nested_scope(int n) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i) {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: work(i);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void continue_if(int n, bool condition) {
+  for (int i = 0; i < n; ++i) {
+    if (condition) {
+      work(i);
+      continue;
+    }
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: redundant continue statement
+// CHECK-FIXES-LABEL: void continue_if(int n, bool condition) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: work(i);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void continue_if_else(int n, bool condition) {
+  for (int i = 0; i < n; ++i) {
+    if (condition) {
+      work(i);
+      continue;
+    } else {
+      work(-i);
+      continue;
+    }
+  }
+}
+// CHECK-MESSAGES: :[[@LINE-7]]:7: warning: redundant continue statement
+// CHECK-MESSAGES: :[[@LINE-5]]:7: warning: redundant continue statement
+// CHECK-FIXES-LABEL: void continue_if_else(int n, bool condition) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: work(i);
+// CHECK-FIXES-NEXT: } else {
+// CHECK-FIXES-NEXT: work(-i);
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void other_loops(bool condition) {
+  while (condition) {
+    if (condition) {
+      continue;
+    }
+  }
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: redundant continue statement
+  do {
+    {
+      continue;
+    }
+  } while (condition);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: redundant continue statement
+  int values[] = {1, 2};
+  for (int value : values) {
+    if (value) {
+      continue;
+    }
+  }
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: redundant continue statement
+}
+// CHECK-FIXES-LABEL: void other_loops(bool condition) {
+// CHECK-FIXES: while (condition) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES: do {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: } while (condition);
+// CHECK-FIXES: for (int value : values) {
+// CHECK-FIXES-NEXT: if (value) {
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+
+void unbraced_returns(bool first, bool second) {
+  if (first)
+    return;
+  else if (second)
+    return;
+  else
+    return;
+}
+// CHECK-MESSAGES: :[[@LINE-6]]:5: warning: redundant return statement
+// CHECK-MESSAGES: :[[@LINE-5]]:5: warning: redundant return statement
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: redundant return statement
+// CHECK-FIXES-LABEL: void unbraced_returns(bool first, bool second) {
+// CHECK-FIXES-NEXT: if (first)
+// CHECK-FIXES-NEXT: ;
+// CHECK-FIXES-NEXT: else if (second)
+// CHECK-FIXES-NEXT: ;
+// CHECK-FIXES-NEXT: else
+// CHECK-FIXES-NEXT: ;
+// CHECK-FIXES-NEXT: }
+
+void unbraced_continue(int n) {
+  for (int i = 0; i < n; ++i)
+    if (i)
+      continue;
+}
+// CHECK-MESSAGES: :[[@LINE-2]]:7: warning: redundant continue statement
+// CHECK-FIXES-LABEL: void unbraced_continue(int n) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i)
+// CHECK-FIXES-NEXT: if (i)
+// CHECK-FIXES-NEXT: ;
+// CHECK-FIXES-NEXT: }
+
+void non_tail_scope() {
+  {
+    return;
+  }
+  work(0);
+}
+// CHECK-FIXES-LABEL: void non_tail_scope() {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: return;
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: work(0);
+
+void non_tail_branch(bool condition) {
+  if (condition) {
+    return;
+  }
+  work(0);
+}
+// CHECK-FIXES-LABEL: void non_tail_branch(bool condition) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: return;
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: work(0);
+
+void return_in_loop(int n) {
+  for (int i = 0; i < n; ++i) {
+    if (i) {
+      return;
+    }
+  }
+}
+// CHECK-FIXES-LABEL: void return_in_loop(int n) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i) {
+// CHECK-FIXES-NEXT: if (i) {
+// CHECK-FIXES-NEXT: return;
+// CHECK-FIXES-NEXT: }
+
+void continue_before_statement(int n) {
+  for (int i = 0; i < n; ++i) {
+    {
+      continue;
+    }
+    work(i);
+  }
+}
+// CHECK-FIXES-LABEL: void continue_before_statement(int n) {
+// CHECK-FIXES-NEXT: for (int i = 0; i < n; ++i) {
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: continue;
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: work(i);
+
+void return_expression(bool condition) {
+  if (condition) {
+    return work(0);
+  } else {
+    return work(1);
+  }
+}
+// CHECK-FIXES-LABEL: void return_expression(bool condition) {
+// CHECK-FIXES-NEXT: if (condition) {
+// CHECK-FIXES-NEXT: return work(0);
+// CHECK-FIXES-NEXT: } else {
+// CHECK-FIXES-NEXT: return work(1);
+
+void switch_boundary(int n) {
+  for (int i = 0; i < n; ++i) {
+    switch (i) {
+    case 0:
+      continue;
+    default:
+      work(i);
+    }
+  }
+}
+// CHECK-FIXES-LABEL: void switch_boundary(int n) {
+// CHECK-FIXES: case 0:
+// CHECK-FIXES-NEXT: continue;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow.cpp
index e157e99c5bf0bb..1fa8f4f38b46c0 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-control-flow.cpp
@@ -115,21 +115,35 @@ void void_return() {
   return g();
 }
 
-void nested_return_unmolested() {
+void nested_return() {
   g();
   {
     g();
     return;
   }
 }
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: redundant return statement
+// CHECK-FIXES: void nested_return() {
+// CHECK-FIXES-NEXT: g();
+// CHECK-FIXES-NEXT: {
+// CHECK-FIXES-NEXT: g();
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
 
-void nested_continue_unmolested() {
+void nested_continue() {
   for (int i = 0; i < 10; ++i) {
     if (i < 5) {
       continue;
     }
   }
 }
+// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: redundant continue statement
+// CHECK-FIXES: void nested_continue() {
+// CHECK-FIXES-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-FIXES-NEXT: if (i < 5) {
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
+// CHECK-FIXES-NEXT: }
 
 #define MACRO_RETURN_UNMOLESTED(fn_)  \
   (fn_)();                            \

``````````

</details>


https://github.com/llvm/llvm-project/pull/242945


More information about the cfe-commits mailing list