#206 Bad code generated for struct offsets

closed-fixed
5
2013-05-25
2001-11-02
No

For SDCC : mcs51/gbz80/z80/avr/ds390/pic14/i186/tlcs900h 2.3.1 (10/17/01) (UNIX)

The following program generates bad code:

typedef struct _STRUCT_ {
unsigned char SRC[100];
int FRAMETYPE;
} STRUCT;
xdata at 0x4000 unsigned char someData[];
extern void func(unsigned char *p);
#define offsetof(type, member) ((unsigned int)(&((type *)0)->member))

void main(void) {
func(&someData[offsetof(STRUCT,SRC)]);
func(&someData[offsetof(STRUCT,FRAMETYPE)]);
}

Notice that the first address calculation for the "func" call is correct, while the second one generates bad code:
; bug.c 10
mov r2,#_someData
mov r3,#(_someData >> 8)
mov r4,#0x01
mov dpl,r2
mov dph,r3
mov b,r4
lcall _func
; bug.c 11
; Peephole 181 used 16 bit load of dptr
mov dptr,#0x0000
mov b,#0x64
lcall __gptrget
mov r2,a
mov r3,#0x00
mov a,r2
add a,#_someData
mov r2,a
mov a,r3
addc a,#(_someData >> 8)
mov r3,a
mov r4,#0x01
mov dpl,r2
mov dph,r3
mov b,r4
lcall _func

The first function call correctly loads r2,r3 & r4. The second function call should also just load r2, r3 & r4. It, however, decides to call __gptrget with an invalid argument for b (#0x64). This is the offset into the structure. Register b needs to be a 1. On return a is 0xFF which is then used as an offset into the structure.

I've extracted this piece of code from some software I'm writing. Ideally the compiler should just load the constant offset of the structure into r2, r3 & r4.

This problem manifests itself when the structure element is a char or int. With that knowledge the current workaround is to create a union of the int with an array:

typedef union _INT_ {
int Int;
unsigned char x[2];
} INT;
typedef struct _STRUCT_ {
unsigned char SRC[100];
INT FRAMETYPE;
} STRUCT;

This generates the correct code:

; bug.c 14
mov r2,#_someData
mov r3,#(_someData >> 8)
mov r4,#0x01
mov dpl,r2
mov dph,r3
mov b,r4
lcall _func
; bug.c 15
mov r2,#(_someData + 0x0064)
mov r3,#((_someData + 0x0064) >> 8)
mov r4,#0x01
mov dpl,r2
mov dph,r3
mov b,r4
lcall _func

Thanks,

Alex Karahalios

Discussion

  • Johan Knol

    Johan Knol - 2001-11-02

    Logged In: YES
    user_id=63512

    fixed in SDCCast.c:1.104

     
  • Johan Knol

    Johan Knol - 2001-11-02
    • labels: 101550 --> C-Front End
    • milestone: --> fixed
    • assigned_to: nobody --> johanknol
    • status: open --> closed-fixed
     

Log in to post a comment.