Arrays, Structures, and Unions
Distinguish packed and unpacked dimensions, group fields, and choose a representation that fits the hardware.
Packed and unpacked dimensions
A dimension before the name is packed. Its bits form a contiguous vector that supports arithmetic, comparisons, and part selects.
A dimension after the name is unpacked. It creates a collection of separate elements.
logic [7:0] bytes [0:3];Here, bytes is an unpacked array of four elements. Each element is a packed 8-bit vector. bytes[2] selects the third byte and bytes[2][7] selects its most significant bit.
The distinction matters for ports and memories:
module sum4 (
input logic [7:0] i_data [0:3],
output logic [9:0] o_sum
);
always_comb begin
o_sum = {2'b00, i_data[0]} + {2'b00, i_data[1]}
+ {2'b00, i_data[2]} + {2'b00, i_data[3]};
end
endmoduleThe explicit extension preserves the two extra bits required by the maximum sum.
Group related fields
A structure collects fields that travel together.
typedef struct packed {
logic [15:0] payload;
logic [2:0] channel;
logic last;
} packet_t;
packet_t packet;With struct packed, all fields form one vector. The structure can be copied, compared, passed through a port, or sliced as bits. Field order fixes bit positions, so document it when an external protocol is involved.
An unpacked structure is a collection of fields without the requirement to form one vector. It works well in test models, but synthesis and port support can vary.
Use unions carefully
A union lets several representations share the same storage.
typedef union packed {
logic [31:0] word;
logic [3:0][7:0] byte_lane;
} word_view_t;Writing word and reading byte_lane gives two views of the same 32 bits. A union tagged also tracks the active member and is mainly useful in higher-level models. Check synthesis support before using it in RTL.
Ports and tool compatibility
SystemVerilog allows ports that carry structures and arrays. They reduce repetition, but a boundary connected to an older tool or external IP may still require flat vectors.
A practical approach is to keep rich types inside the project and convert explicitly at boundaries that require a flat format.
Key points
- A packed dimension appears before the name, an unpacked dimension after it.
- An unpacked array describes a collection, often a memory or several lanes.
- A packed structure forms one contiguous vector with named fields.
- A union provides several views of the same storage.
- Language syntax and actual synthesis support are not always identical.
📝 Test your knowledge - Chapter quiz