Incorrect code is produced for the following source with the O2 option. In particular, the assignment to the bitfield field2 is optimized out of the code entirely and regImage is left all zero. Correct code is produced with the O1 option and (at least) with gcc version 4.3.2.
==================== Source Code typedef struct hwreg { short field1 : 4; short field2 : 2; short field3 : 10; } hwreg_t; void foo(volatile short *hwPtr, short f2) { hwreg_t regImage; // Place to build reg image bit-by-bit *(short *) ®Image = 0; regImage.field2 = f2; *hwPtr = *((short *) ®Image); } ============================ Object dump /tmp/foo.o: file format elf32-littlearm Disassembly of section .text: 00000000 <foo>: 0: e3a03000 mov r3, #0 ; 0x0 4: e24dd004 sub sp, sp, #4 ; 0x4 8: e1c030b0 strh r3, [r0] c: e28dd004 add sp, sp, #4 ; 0x4 10: e12fff1e bx lr ============================ gcc -v output Configured with: ../gcc-4.4.1/configure --target=arm-elf --disable-__cxa_atexit --with-newlib --enable-languages=c,c++ --with-gnu-as --with-gnu-ld --with-gxx-include-dir=/home/jmb/arm-elf/include --prefix=/home/jmb/arm-elf : (reconfigured) ../gcc-4.4.1/configure --target=arm-elf --disable-__cxa_atexit --with-newlib --enable-languages=c,c++ --with-gnu-as --with-gnu-ld --with-gxx-include-dir=/home/jmb/arm-elf/include --prefix=/home/jmb/arm-elf Thread model: single gcc version 4.4.1 (GCC) -- Summary: O2 optimizes out assignment to bitfield Product: gcc Version: 4.4.1 Status: UNCONFIRMED Severity: critical Priority: P3 Component: tree-optimization AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: jim at bodwin dot us GCC build triplet: i486-pc-linux-gnu GCC host triplet: i486-pc-linux-gnu GCC target triplet: arm-elf http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40844