Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

#92 reduce for loop to do{..}while(--i);

open
nobody
None
1
2004-12-04
2004-12-04
No

mcs51: If the index variable is not used within the
loop then the for loop could be reduced to a loop with
a djnz instruction (as SDCC does in function g())

#include <8051.h>

void f( )
{
unsigned char i;
for( i=0; i<8; i++ )
P0_0 = !P0_0;
}

void g( )
{
unsigned char i = 8;
do {
P0_0 = !P0_0;
} while( --i );
}

This could also work for an integer index <=256.

Discussion

  • Logged In: YES
    user_id=589052

    if a non-volatile bit is toggled SDCC already does the
    proposed optimization.

    The code snippet below shows SDCC is almost there but it
    also exposes a bug:

    bit my_bit; /* if volatile loop reversal is disabled */

    void f_opt ()
    {
    unsigned char i;
    for (i = 0; i < 256; i++)
    my_bit = !my_bit;
    }

    compiles to:

    mov r2,#0x00
    00103$:
    cpl _my_bit
    djnz r2,00103$

    which should have been:

    00103$:
    cpl _my_bit
    sjmp 00103$