PATCH: cp/class.c: force alignment of non-bitfields

Andrew Haley aph@pasanda.cygnus.co.uk
Wed Oct 13 09:34:00 GMT 1999


This bug is in the C++ compiler but not the C compiler: the result is
that in C++, packed nested structs mixed with bitfields don't get laid
out properly. and the compiler can't generate proper static
initialization data.

Here's the testcase:

---------------------------------------------------------------------------
typedef struct  {
  char  a;
  long  l;
  char  b;
} __attribute__ ((packed)) Z;  // Size: 6

typedef struct {
  char  a;
  char  b : 2; // Bitfield
  Z     z;
  long  l;
} __attribute__ ((packed)) Y ; // Size: 12

typedef struct {
  char  e;
  long  l;
  char  a : 1;  // Bitfield
  char  b : 6;  // Bitfield
  Y     y;
  long  m;
  Z     z ;
  char  c;
} __attribute__ ((packed)) X ; // Size: 29

// Generates 30 bytes with a padding before x.m
X globalX = {1,2,1,0xF,{1,2,{7,8,9},3},3,{10,11,12},4};  

int main()
{
    X lx = globalX;
    return  sizeof(X); // Reports 29
}
---------------------------------------------------------------------------

And here's the patch:

1999-10-13  Andrew Haley  <aph@cygnus.com>

	* class.c (finish_struct_1): Force alignment of non-bitfields to
	BITS_PER_UNIT.

Index: class.c
===================================================================
RCS file: /cvs/gcc/egcs/gcc/cp/class.c,v
retrieving revision 1.193
diff -p -r1.193 class.c
*** class.c	1999/10/12 01:15:02	1.193
--- class.c	1999/10/13 16:30:38
*************** finish_struct_1 (t)
*** 3654,3659 ****
--- 3654,3667 ----
  		cp_error_at ("multiple fields in union `%T' initialized");
  	      any_default_members = 1;
  	    }
+ 
+ 	  {
+ 	    unsigned int min_align = (DECL_PACKED (x) ? BITS_PER_UNIT
+ 				      : TYPE_ALIGN (TREE_TYPE (x)));
+ 	    /* Non-bit-fields are aligned for their type, except packed
+ 	       fields which require only BITS_PER_UNIT alignment.  */
+ 	    DECL_ALIGN (x) = MAX (DECL_ALIGN (x), min_align);
+ 	  }
  	}
      }
  


More information about the Gcc-patches mailing list