[PATCH] D73762: New warning for for-loops where the iteration does not match the loop condition

Richard Trieu via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 30 18:41:25 PST 2020


rtrieu created this revision.

This is a warning for when the increment/decrement in a for loop does not match the condition in the loop.  If the condition has a relational operator, one operand can be deduced to be the larger value and the other operand the smaller value when the loop is run.  For the loop to terminate, the smaller value needs to increase or the larger value needs to decrease, while the opposite will cause the loop to not terminate.

Correct:

  for (...; x < y; ++x) {}
  for (...; x < y; --y) {}

Incorrect:

  for (...; x < y; --x) {}
  for (...; x < y; ++y) {}

The warning comes with two attached notes.  One is to flip the direction of the comparison (">" to "<", etc) and other is to change the increment decrement step ("--" to "++" or vice versa).

An exception is made for unsigned values, since some code uses the unsigned overflow/underflow characteristics.


https://reviews.llvm.org/D73762

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/warn-loop-analysis.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D73762.241625.patch
Type: text/x-patch
Size: 9165 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20200131/867f4f14/attachment-0001.bin>


More information about the cfe-commits mailing list