This is an archive of the discontinued LLVM Phabricator instance.

New warning on for-loops that never run because condition is false on the first iteration
Needs ReviewPublic

Authored by rtrieu on Dec 13 2019, 6:59 PM.
This revision needs review, but there are no reviewers specified.

Details

Reviewers
None
Summary

This is a proposed warning to be added to -Wfor-loop-analysis, which is part of -Wall. This warning will catch instances where the condition will be false on the first iteration and the loop body will never be run. The warning will be emitted when:

  1. The for-loop initializes or sets the value of a single variable to a constant value
  2. The condition is a simple comparison between the variable and another constant value
  3. If the initial value of the variable substituted into the comparison would cause the comparison to be false

In order to make step 3 work, the constant value from step 1 may need to be casted to a different type. The casts can be extracted from the comparison operand. This allows the warning to work with both integer and floating point types, as well as mixing types.

Two exceptions to this warning.

  1. Parentheses around the condition will silence this warning. This is suggested in a note.
  2. If the variable is used as an array index in the body, and the condition is less than a value the same as the array size.

Example:
https://reviews.llvm.org/D48498
This warning would have caught the issue that @lebedev.ri brought up about the loop not running.

Diff Detail

Event Timeline

rtrieu created this revision.Dec 13 2019, 6:59 PM
lebedev.ri edited the summary of this revision. (Show Details)Dec 14 2019, 3:12 AM
lebedev.ri added a subscriber: lebedev.ri.

Thank you for working on this!
This seems to be missing tests.

rtrieu updated this revision to Diff 234180.Dec 16 2019, 3:53 PM

Thank you for working on this!
This seems to be missing tests.

My bad, still getting used to git. Updated with a test now.