#338 Improve accessing structs on the stack using ix


In the attached code example, compiled using sdcc 3.0.6 #6966 using "sdcc -mz80 -c test.c", the struct regs is accessed using stack pointer manipulation. For example, we see the address first calculated and stored in bc:

79 ;test.c:55: regs.regs_pc = 0x100;
002F 21 03 00 80 ld hl,#0x0003
0032 39 81 add hl,sp
0033 4D 82 ld c,l
0034 44 83 ld b,h

followed by repeated 16-bit arithmetic to locate the individual fields:

0035 21 0C 00 84 ld hl,#0x000C
0038 09 85 add hl,bc
0039 36 00 86 ld (hl),#0x00
003B 23 87 inc hl
003C 36 01 88 ld (hl),#0x01


89 ;test.c:56: regs.reg_d = 0;
003E 21 06 00 90 ld hl,#0x0006
0041 09 91 add hl,bc

Surely, given that sdcc maintains a frame pointer in ix, we can use this to directly access this struct, rather than constantly re-calculating addresses based off %sp.

In a more complex example, where the assignments to the struct members are more spread out, I see the compiler generating the address and it appears to store this on the stack using -30(ix) and -31(ix) or similar, only to retrieve it later into hl to perform more 16-bit pointer addition to calculate the address of the member being assigned. These re-loads can somewhat eliminated by reorganising the code, but this requires the code writer to optimise the code for the backend compiler.

IMO, it would be be beneficial to use ix, as this would both potentially shrink complex code and possibly improve execution speed, but more importantly removes the coupling between how the code is written and the end result, and moves the struct offset calculations from runtime to compile time.


  • Brian Ruthven

    Brian Ruthven - 2011-10-17

    Example code

  • Brian Ruthven

    Brian Ruthven - 2011-10-17
    • summary: Interesting access of auto struct variables. --> Improve accessing structs on the stack using ix
  • Philipp Klaus Krause

    1) This is not a bug: The generated code is correnct, though inefficient.
    2) This is not Z80-specific, handling of aggregate types and unions is very inefficient in all of sdcc.
    3) There already is feature request #2870755 about this issue.


  • Philipp Klaus Krause

    • labels: 100692 -->
    • assigned_to: nobody --> spth
    • status: open --> closed-duplicate
  • Brian Ruthven

    Brian Ruthven - 2011-10-22

    Sorry - I forget there is a separate feature tracking database. I'm used to a single database for all types.


Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks