sample code
struct S1 {
int a;
union {
int i1;
int i2;
} u;
long l;
};
struct S2 {
int a;
union {
int i1;
int i2;
};
long l;
};
struct S1 v1 = {0xaaaa, {0xb1b1}, 0x0b0c0d0f };
struct S2 v2 = {0xaaaa, {0xb1b1}, 0x0b0c0d0f };
resulting assembly:
IDD_test2_0 idata
_v1
db 0xaa, 0xaa ; -21846
db 0xb1, 0xb1 ; -20047
db 0x0f, 0x0d, 0x0c, 0x0b ; 185339151
IDD_test2_1 idata
_v2
db 0xaa, 0xaa ; -21846
db 0xb1, 0xb1 ; -20047
db 0x0f, 0x0d ; 3343
db 0x00, 0x00, 0x00, 0x00 ; 0
V1 is ok. V2 is incorrect.
Other ports generate the correct code in both cases.
Hi Gabriele,
I've prepared a patch for SDCC bug #4276, which concerns incorrect initialization of anonymous unions in the PIC16 backend.
Root cause:
SDCC promotes members of anonymous unions into the containing structure's field list. The common initializer implementation handles the union as a single storage object and skips inactive alternatives.
However, the PIC16-specific implementation in
pic16_printIvalStruct()processes those alternatives separately, incorrectly consuming additional initializer values. This can produce incorrect initialized data and, in some cases, emit more bytes than the actual structure size.Changes:
pic16_printIvalStruct()to follow the common initializer traversal logic.designatedAlternative()andfieldHasIval()helpers for reuse by PIC16.Validation:
PIC16 validation was performed by compiling the test cases and comparing the generated initialization data against the expected structure layouts.
PIC16 runtime simulation was not performed because GPSIM was unavailable in the test environment.
Files modified:
src/SDCCglue.csrc/SDCCglue.hsrc/SDCCval.csrc/pic16/glue.cNo PIC24-specific source files are modified. The changes to the common compiler sources are limited to exposing existing helper functions and related declarations or comments.
Attachment:
bug4276-pic16-anon-union-init_v11.patchBest regards
Last edit: zeynelsagcan 9 hours ago