module sv_learn_union;
// First union : untagged
// memory required : 40 bit for data
typedef union {
bit [23:0] a;
bit [39:0] b;
} UN_A;
// Second Union : tagged packed
// memory required : 1 bit for tag and 40 bit for data
typedef union tagged packed {
bit [23:0] x;
bit [39:0] y;
} UN_B;
UN_A u_a1;
UN_B u_b1;
endmodule : sv_learn_union
size() operator can not be used with the union so in the above code how to print the size of “u_a1” and “u_b1”.
I don’t know all the rules for unions. I think packed unions should work; tagged unions have other rules (allowing dynamic types) - but then you made UN_B taggged and packed…
I’m actually not sure here, but it should be a quick test.
The size() method is only defined for unpacked arrays. You want to use $bits. Note the size of the tag bits only has a minimum, and there is an undefined space between the tag bits and the member bits. (Section 7.3.2 Tagged unions)
But for the Packed unions must contain types that are all the same size (# of bits).so in above example
typedef union {
bit [23:0] a;
bit [39:0] b;
} UN_A;
both the size of a and b must be same if that is not same i am facing an FATAL error saying The members of packed union must be the same size.
How to get the size as 40 for this example ??
The members of a packed, untagged union shall all be the same size (in contrast to an unpacked union or a packed, tagged union, where the members can be different sizes).
module sv_learn_union;
// First union : unpacked and untagged
// memory required : 40 bit for data
typedef union {
bit [23:0] a;
bit [39:0] b;
} UN_A;
// Second Union : tagged packed
// memory required : 1 bit for tag and 40 bit for data
typedef union tagged packed {
bit [23:0] x;
bit [39:0] y;
} UN_B;
// Third union : packed and untagged
// memory required : 40 bit for data
typedef union packed {
bit [39:0] a;
bit [39:0] b;
} UN_C;
UN_A u_a1;
UN_B u_b1;
UN_C u_c1;
initial begin
$display("Number of bits for UN_A = %0d", $bits(u_a1));
$display("Number of bits for UN_B = %0d", $bits(u_b1));
$display("Number of bits for UN_C = %0d", $bits(u_c1));
end
endmodule : sv_learn_union
Union “UN_A” is an untagged unpacked union so it’s members (packed or unpacked) can be of different sizes.
Union “UN_B” is a tagged packed union so it’s members (packed) can be of different sizes.
Union “UN_C” is an untagged packed union so it’s members (packed) must be of the same size.