llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.62k stars 11.83k forks source link

Detect bugprone downcounting loops on unsigned loop variables #47319

Open LegalizeAdulthood opened 3 years ago

LegalizeAdulthood commented 3 years ago
Bugzilla Link 47975
Version unspecified
OS Windows NT

Extended Description

Suppose you have a loop like this:

for (int i = maxLevels; i >= 0; --i)
  doSomething(i);

This is perfectly fine as lone as i remains a signed quantity.

Now suppose someone changes the loop variable to unsigned, perhaps because doSomething takes an unsigned int argument and they think "static casts are ugly", so they change the loop to:

for (unsigned int i = maxLevels; i >= 0; --i)
  doSomething(i);

Now they have transformed a finite loop into an infinite loop. On the intended last iteration where i = 0, it will be "decremented", which could wraparound to MAX_UINT, resulting in the loop continuing to execute, possibly interminably.

Create a clang-tidy check that warns about downcounting loops on unsigned quantities where the loop termination test is >= 0.

LegalizeAdulthood commented 3 years ago

Does that check get reported by clang-tidy?

llvmbot commented 3 years ago

We already have the -Wtautological-unsigned-zero-compare flag (https://clang.llvm.org/docs/DiagnosticsReference.html#id763) that diagnoses cases where unsigned comparisons against zero always evaluate to a constant

LegalizeAdulthood commented 3 years ago

First pass on this check would be to just warn based on identifying the loop condition.

Second pass would be to not warn if the interior of the loop contains control flow that exits the loop when i == 0.