[PATCH] D58134: [Analysis] -Wunreachable-code shouldn't fire on the increment of a foreach loop

Sam McCall via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 12 09:03:14 PST 2019


sammccall created this revision.
sammccall added reviewers: ilya-biryukov, ioeric.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The idea is that the code here isn't written, so doesn't indicate a bug.
Similar to code expanded from macros.

This means the warning no longer fires on this code:

  for (auto C : collection) {
    process(C);
    return;
  }
  handleEmptyCollection();

Unclear whether this is more often a bug or not in practice, I think it's a
reasonable idiom in some cases.
Either way, if we want to warn on "loop that doesn't loop", I think it should be
a separate warning, and catch `while(1) break;`


Repository:
  rC Clang

https://reviews.llvm.org/D58134

Files:
  lib/Analysis/ReachableCode.cpp
  test/SemaCXX/unreachable-code.cpp


Index: test/SemaCXX/unreachable-code.cpp
===================================================================
--- test/SemaCXX/unreachable-code.cpp
+++ test/SemaCXX/unreachable-code.cpp
@@ -52,6 +52,11 @@
   }
 }
 
+void test4() {
+  for (char c : "abc") // no-warning
+    break;
+}
+
 // PR 6130 - Don't warn about bogus unreachable code with throw's and
 // temporary objects.
 class PR6130 {
Index: lib/Analysis/ReachableCode.cpp
===================================================================
--- lib/Analysis/ReachableCode.cpp
+++ lib/Analysis/ReachableCode.cpp
@@ -631,6 +631,10 @@
     // a for/for-range loop.  This is the block that contains
     // the increment code.
     if (const Stmt *LoopTarget = B->getLoopTarget()) {
+      // The increment on a foreach statement is not written.
+      if (isa<CXXForRangeStmt>(LoopTarget))
+        return;
+
       SourceLocation Loc = LoopTarget->getBeginLoc();
       SourceRange R1(Loc, Loc), R2;
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D58134.186491.patch
Type: text/x-patch
Size: 960 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20190212/3c3c9194/attachment.bin>


More information about the cfe-commits mailing list