llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

false positive in bugprone-too-small-loop-variable checker when using bitfield as upper bound

Open vabridgers opened this issue 4 years ago • 3 comments

The bugprone-too-small-loop-variable checker does not consider bitfields, not to ignore or flag them as poor programming practice (if that's desired) or consider their bitwidth, leading to false positives when this kind of code is analyzed. An example is below.

If I cast the upperbound in this case there's no warning, or if I assign the upper bound to an integral variable of equivalent or lower rank than the loop variable, then there's no warning either. So these seem to be suitable workarounds.

I suppose the checker could get the real bitfield width and use that

  1. const FieldDecl *FD = UpperBound->getSourceBitField()
  2. if FD; FD->getBitWidthValue(Context) or maybe just detect if the loop variable and/or upper bounds are a bitfield and skip the check
  3. const FieldDecl *FD = UpperBound->getSourceBitField()
  4. if FD; FD->isBitField()
struct xx {
    int x;
    int y:6;
} xx;

int foo(struct xx *pxx) {
    int sum = 0;
    for (char yy=0; yy<pxx->y; yy++)
        sum++;
    return sum;
}
$ clang-tidy --checks=bugprone-too-small-loop-variable loop.c --
loop.c:9:21: warning: loop variable has narrower type 'char' than iteration's upper bound 'int' [bugprone-too-small-loop-variable]
    for (char yy=0; yy<pxx->y; yy++)

vabridgers avatar Oct 26 '22 00:10 vabridgers

@llvm/issue-subscribers-clang-tidy

llvmbot avatar Oct 26 '22 00:10 llvmbot

Same issue when bitfield is used as an loop variable.

PiotrZSL avatar Jan 25 '23 12:01 PiotrZSL

https://reviews.llvm.org/D142587

PiotrZSL avatar Jan 25 '23 23:01 PiotrZSL