- Category: other --> MCS51
Version: SDCC 4.6.0 #16555 (MINGW64), Windows x64 (sdcc-4.6.0-x64-setup.exe).
Command: sdcc -mmcs51 --model-large --stack-auto --xstack -c repro.c, with and without --opt-code-size (two different wrong sequences, below). Correct without --xstack.
repro.c:
unsigned int table[4] = { 0x0100, 0, 0x0001, 0 };
unsigned int get(unsigned char k)
{
return table[k];
}
void use(unsigned int a, unsigned int b);
unsigned char test(unsigned int a, unsigned int b)
{
if (!get(1))
return 0;
use(a, b);
return 1;
}
get(1) returns 0, so test(0x1234, 0x5678) must return 0. a (R6:R7) is live across the call, so it is saved on the external stack before lcall _get and restored after it. The restore runs after the 16-bit result has been moved to A (low byte) and B (high byte) for the zero test orl a,b, and destroys them.
Without --opt-code-size, the inline restore goes through A:
mov dpl, #0x01
lcall _get
mov a, dpl ; result low byte in A
mov b, dph ; result high byte in B
mov r0,_spx
dec r0
movx a,@r0 ; restore r6 through A: the low byte is lost
mov r6,a
dec r0
movx a,@r0 ; restore r7 through A
mov r7,a
mov _spx,r0
orl a,b ; tests r7 | dph, not dpl | dph
jnz 00102$
With --opt-code-size, the restore is the library call, which takes its register mask in B and uses A (___sdcc_xpop_regs, lib/src/mcs51/crtxpop.asm, starts with mov a,r0). The high byte is never moved to B:
mov dpl, #0x01
lcall _get
mov a, dpl ; result low byte in A
mov b,#0x3f ; the pop mask in B: DPH is never used
lcall ___sdcc_xpop_regs ;(r6r7) ; overwrites A
orl a,b ; tests garbage | 0x3f: always non-zero
jnz 00102$
Result in the simulator (s51 -t 8052; repro.c plus void use(unsigned int a, unsigned int b) {} and void main(void) { result = test(0x1234, 0x5678); for (;;); }):
| Options | result |
|
|---|---|---|
--model-large --stack-auto |
0 | correct |
--model-large --stack-auto --xstack |
1 | wrong |
--model-large --stack-auto --xstack --opt-code-size |
1 | wrong |
(The --xstack builds were linked with --nostdlib -L lib/large-stack-auto -l mcs51 -l libsdcc, as the installer has no xstack library; the linker warns about mixed options, the startup code sets up _spx all the same.)
Expected: the result is tested before the restore, or kept out of A and B while the registers are restored (as the code does when no register has to be saved).
Related: #4253 (the same order fault with an 8-bit result in A: the restore through A, or ___sdcc_xpop_regs, runs between moving the result to A and jz/jnz).