SDCC generates unnecessary division by zero

189 views Asked by At

I'm using SDCC to compile for a STM8 microcontroller. Compiling the following file results in a seemingly unnecessary div instruction - which is very slow on the STM8.

char a[1];
char b;

void foo() __interrupt(1) {
    char c = a[0];
    b = c >> 0;
}

void main() {
}

Compiling with sdcc -mstm8 file.c results in the following assembly:

_foo:
    clr a
    div x, a
    ld  a, _a+0
    ld  _b+0, a
    iret

The function seems to work as expected, however I can't see why the first two instructions are required.

1

There are 1 answers

1
phuclv On BEST ANSWER

Looks like that's a bug somewhere in the compiler because if b = c >> 0 is changed to b = c << 0, b = c + 0, b = a[0]... then no such thing happens. The behavior is observed on both optimized and unoptimized code. But if you optimize for size (--opt-code-size) then only the div is there, the clr instruction isn't emitted. You might want to report that to the developers

Demo on Compiler Explorer