Loop optimised into div (?)

Hi all,

For the following code

int countHundred( int num )
{
int count = 0;
while ( num >= 100) { count++ ; num = num - 100; }
return count;
}

the loop shown above is optimised away and replaced by ‘udiv’ instruction like this

define i16 @countHundred(i16 %num) {
entry:
%cmp3 = icmp sgt i16 %num, 99
br i1 %cmp3, label %while.body.preheader, label %while.end

while.body.preheader: ; preds = %entry
%0 = add nsw i16 %num, -100
%1 = udiv i16 %0, 100
%2 = add nuw nsw i16 %1, 1
br label %while.end

while.end: ; preds = %while.body.preheader, %entry
%count.0.lcssa = phi i16 [ 0, %entry ], [ %2, %while.body.preheader ]
ret i16 %count.0.lcssa
}

The above was compiled for the MSP430 target with the -Os flag but similar results are obtained with the other options except -O0

Any pointers about where does that transform happen would be appreciated (I posted a similar question in cfe-dev).

Thanks in advance

John.

Hi Joan,

The above was compiled for the MSP430 target with the -Os flag but similar results are obtained with the other options except -O0

Any pointers about where does that transform happen would be appreciated (I posted a similar question in cfe-dev).

Running Clang with "-mllvm -print-after-all" is useful to answer this
question (though beware, some passes don't show up there for various
reasons). In this case it seems to be "Induction Variable
Simplification", which lives in
lib/Transforms/Scalar/IndVarSimplify.cpp.

Cheers.

Tim.