Structs, Unions and Arrays of Records
Name the fields of a word with a packed struct, overlay formats with a packed union, and keep a table of records. None of it costs a gate.
You Will Be Able To
- Write a packed struct whose members land on the bits the spec gives.
- Predict what a packed union shows when you write one view and read another.
- Choose between a packed and an unpacked struct for a port, a table and a bundle.
- Fix a decoder whose fields are wrong because of member order.
- Lesson
- R9.4
- Time
- 30 min
- Runs on
- Verilator
- Check
- 5 questions
A store instruction wrote to the wrong address. The decoder had no wrong index in it, because it had no index at all: it read fields by name. The names sat on the wrong bits.
- Neutral
- Data
- One word
The union holds 32 bits.
ins.raw,ins.r,ins.iandins.sare four names for those same bits. - The opcode picks a view
Bits 6:0 mean the same in every format, so the decoder reads them as
ins.r.opcode. - A store uses the S view
For opcode
0100011the decoder joinsins.s.imm_hiandins.s.imm_lo. If the S view names the wrong bits, only stores break.
Read the diagram as text
- ins.raw: 32 bits from the fetch stage
- ins.r: funct7 rs2 rs1 funct3 rd opcode
- ins.i: imm rs1 funct3 rd opcode
- ins.s: imm_hi rs2 rs1 funct3 imm_lo opcode
- opcode: bits 6:0 in every view
- fields: rd, rs1, rs2, imm
- ins.raw → ins.r: same bits
- ins.raw → ins.i: same bits
- ins.raw → ins.s: same bits
- ins.r → opcode: r.opcode
- ins.s → fields: a store
- ins.i → fields: addi, lw
A view costs nothing. It is a set of names for wires that already exist.
A Packed Struct Is a Named Vector
A struct groups several values under one name. With the word packed, the members sit side by side in one vector. The first member takes the top bits.
| 31:25 | 24:20 | 19:15 | 14:12 | 11:7 | 6:0 |
|---|---|---|---|---|---|
funct7 | rs2 | rs1 | funct3 | rd | opcode |
The R-type format of RISC-V as a ruler. r_type_t in the lab lists its members in this order, left to right.
| You write | It means |
|---|---|
ins.r.rd | bits 11:7, the same wires as ins.raw[11:7] |
r_type_t w = 32'h002081b3; | a vector fills the struct from the top member down |
$bits(r_type_t) | 32, the sum of the member widths |
w == other, w + 1, w[6:0] | legal: a packed struct is a vector in every expression |
a port of type r_type_t | connects to any 32-bit vector, as the lab bench does |
A Packed Union: Several Rulers on the Same Bits
A union holds one value that can be read in several forms. A packed union lays every member over the same bits. Write through one member and read through another: no logic runs between them.
| View | 31:25 | 24:20 | 19:15 | 14:12 | 11:7 | 6:0 |
|---|---|---|---|---|---|---|
ins.r | funct7 | rs2 | rs1 | funct3 | rd | opcode |
ins.i | imm[11:5] | imm[4:0] | rs1 | funct3 | rd | opcode |
ins.s | imm_hi | rs2 | rs1 | funct3 | imm_lo | opcode |
Three rulers over one word. The I view has one 12-bit imm across the first two columns. The S view splits its immediate around rs2, rs1 and funct3.
Two rules keep a union in hardware. Every member must have the same width. And only a packed union is safe for synthesis.
| Type | This flow | Tool message |
|---|---|---|
| packed union, members of equal width | builds | none |
| packed union, one member 17 bits and one 32 | refused | all members of a packed union must have the same width; 'short_v' has width of 17, previously seen width was 32 |
| tagged union | refused | Yosys: unsupported language feature. Lint: Unsupported: tagged union |
Measured on the pinned Yosys with the slang front end, and on the Lint button.
Fill a Whole Struct at Once
An assignment pattern, written '{ ... }, gives every member a value in one statement. Name the members, and let default cover the rest.
By position
f = '{ins.r.rd, ins.r.rs1, ins.r.rs2, 32'd0};
// values in the order the type declares:
// rd, rs1, rs2, imm
Short. It breaks without any message if someone reorders fields_t and the widths still match.
By name, with a default
f = '{rd: ins.r.rd, rs1: ins.r.rs1,
rs2: ins.r.rs2, default: '0};
f = '{default: '0}; // every member
Each value says where it goes. The lab uses this form on every line.
| Where a struct goes | Rule |
|---|---|
| A module port | put the typedef in a package and import it in the module header |
| A function argument or result | the same: function automatic fields_t decode(input instr_t ins); |
| A copy | f2 = f1; copies every member, packed or not |
| A flop | always_ff ... f_q <= f; registers the whole record |
Unpacked Structs: A Bundle
Leave out packed and the struct is a bundle of separate members. It has no bit order, so it is not a vector.
struct packed | struct (unpacked) | |
|---|---|---|
| Storage | one vector, first member on top | separate members |
| Members | bits, vectors, packed structs and unions | any type, including arrays and int |
| Assign to or from a vector | yes | no |
| Use in a union | yes | no |
| Connect to a port | any vector of the same width | only the very same typedef |
| Synthesis on this flow | builds | builds |
data=5a last=1 hops=3 for an input with hops at 2. Synthesize reports 6 cells: the 4-bit increment and nothing else.package beat_pkg;
typedef struct { // no "packed": a bundle of separate members
logic [7:0] data;
logic last;
logic [3:0] hops;
} beat_t;
endpackage
module bump
import beat_pkg::*;
(
input beat_t in,
output beat_t out
);
always_comb begin
out = in; // a whole-struct copy
out.hops = in.hops + 4'd1; // then one member
end
endmoduleAssign that 13-bit bundle to a 13-bit vector and Yosys stops: no implicit conversion from 'beat_t' to 'logic[12:0]'. Lint on this flow printed nothing for the same line.
Use a packed struct for anything that crosses a bus, sits in a register map or goes into a memory. Use an unpacked one for a bundle of signals that only travels between your own modules.
Arrays of Records
A table of records is an array whose element type is a struct. Each line below is a different kind of access.
$_MUX_ and 9 gates, 3 levels of logic.package chan_pkg;
typedef struct packed {
logic en;
logic [1:0] prio;
logic [4:0] len;
} chan_t; // 8 bits
endpackage
module chan_tab
import chan_pkg::*;
(
input logic clk, rst_n,
input logic we,
input logic [1:0] waddr,
input chan_t wdata,
input logic snap, // 1: copy the whole table
input logic [1:0] raddr,
output chan_t rdata,
output logic [2:0] len_hi
);
chan_t tab [4], shadow [4];
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) begin
tab <= '{default: '0}; // every member of every entry
shadow <= '{'0, '0, '0, '{en: 1'b1, default: '0}}; // a list: entries 0 to 3
end else begin
if (we) tab[waddr] <= wdata; // one record
if (snap) shadow <= tab; // an array copy
end
assign rdata = shadow[raddr];
assign len_hi = tab[raddr].len[4:2]; // entry, then member, then bits
endmodule| Line | What it does | Measured on Verilator |
|---|---|---|
tab <= '{default: '0}; | clears every member of every entry | len_hi=000 after reset |
shadow <= '{'0, '0, '0, '{en: 1'b1, default: '0}}; | a list, one item per entry, 0 to 3 | shadow[3]=10000000 after reset |
tab[waddr] <= wdata; | writes one whole record | len_hi=101 after a write of len 22 to entry 2 |
shadow <= tab; | copies the array; sizes and types must match | shadow[2]=11010110 after the copy |
tab[raddr].len[4:2] | the entry, then the member, then the bits | reads the top three bits of len |
Read a select from left to right: array index, member name, bit range.
The Lab: Fields on the Wrong Bits
| Port | Direction | Width | Meaning |
|---|---|---|---|
| ins | input | [31:0] | one RV32I instruction word, typed instr_t |
| f | output | [46:0] | fields_t: rd, rs1, rs2 (5 bits each) and imm (32 bits, sign-extended) |
- Latency
- combinational
- Corner cases
- a store with a negative offset. Done when: Run prints
rs1=8 rs2=5 imm=-12for theswline, and Synthesize reports 48 cells
Run as shipped
The
add,addiandlwlines are right. Theswline readsrs1=2 rs2=20 imm=1125. Only the S view is wrong.Compare the type with the ruler
The S row of the ruler starts with
imm_hiat bits 31:25. The shippeds_type_tstarts withopcode. Its author listed the fields from bit 0 up.Fix the order
List the members from the top bit down, as the block below shows. Run: the
swline readsrd=0 rs1=8 rs2=5 imm=-12.Count the gates
Synthesize reports 48 cells and 6 levels. The hand-indexed decoder below builds the same 48 cells. The shipped version was 62 cells and 7 levels, because its S fields came from other bits.
The fix: s_type_t from the top bit down
typedef struct packed { // S-type: a store; the immediate is in two pieces
logic [6:0] imm_hi; // 31:25
logic [4:0] rs2; // 24:20
logic [4:0] rs1; // 19:15
logic [2:0] funct3; // 14:12
logic [4:0] imm_lo; // 11:7
logic [6:0] opcode; // 6:0
} s_type_t;The same decoder with hand-written indexes
module rv_dec (input logic [31:0] ins, output logic [46:0] f);
always_comb begin
f = '0;
case (ins[6:0])
7'b0110011: f = {ins[11:7], ins[19:15], ins[24:20], 32'd0};
7'b0010011,
7'b0000011: f = {ins[11:7], ins[19:15], 5'd0, {20{ins[31]}}, ins[31:20]};
7'b0100011: f = {5'd0, ins[19:15], ins[24:20], {20{ins[31]}}, ins[31:25], ins[11:7]};
default: ;
endcase
end
endmoduleAsked in interviews
What is the difference between a packed and an unpacked struct?
A packed struct is one vector, with the first member in the top bits. You can assign it to a vector or put it in a union. An unpacked struct is a bundle of separate members with no bit order.
Does a struct or a union add hardware?
No. A member select is a part-select of the same wires. In the lab, the struct decoder and the hand-indexed one both built 48 cells on this flow.
Where would you use a packed union in RTL?
Where one word has several formats. Examples are instruction decoding and a packet header read as fields or as bytes. Every member must have the same width.
Try It
The bench drives four instruction words and prints the fields. It connects plain vectors to both ports, which a packed struct or union port accepts.
The first three lines use the R and I views and are right. The sw line uses the S view, whose members are listed from bit 0 up. So rs1, rs2 and both halves of the immediate come from the wrong bits.
Synthesize reports 62 cells, 0 flops, 0 latches and 7 levels for the shipped file. Once the member order is fixed it reports 48 cells and 6 levels.
Synthesize the design to measure its cells and inspect the mapped gates.
add x3, x1, x2 rd=3 rs1=1 rs2=2 imm=0 addi x5, x6, -3 rd=5 rs1=6 rs2=0 imm=-3 lw x7, 8(x10) rd=7 rs1=10 rs2=0 imm=8 sw x5, -12(x8) rd=0 rs1=2 rs2=20 imm=1125Original design · 62 cells · 0 flip-flops · 0 latches · 7 logic levels. Synthesis uses Yosys; counts depend on the toolchain.
Read included file: tb.sv
// The bench knows nothing about the package. A packed struct or union port is a vector to it.
module tb;
logic [31:0] word;
logic [46:0] f; // {rd[4:0], rs1[4:0], rs2[4:0], imm[31:0]}
rv_dec dut (.ins(word), .f(f));
task automatic show(input string name, input logic [31:0] w);
word = w; #1;
$display("%-16s rd=%0d rs1=%0d rs2=%0d imm=%0d", name, f[46:42], f[41:37], f[36:32], $signed(f[31:0]));
endtask
initial begin
show("add x3, x1, x2", 32'h002081b3);
show("addi x5, x6, -3", 32'hffd30293);
show("lw x7, 8(x10)", 32'h00852383);
show("sw x5, -12(x8)", 32'hfe542a23);
$finish(0);
end
endmodule
Check Yourself
Common Mistakes
Wrong Leave out packed and then treat the struct as a vector.
An unpacked struct is a bundle of separate members with no defined bit order.
Fix Write struct packed when the type must match a bus, a register or a memory word.
Wrong Give a packed union members of different widths and expect the short one to be padded.
Every member of a packed union must have the same width, and the tools refuse the type.
Fix Pad the short view with a named filler member so that each view is the full width.
typedef union packed {
logic [31:0] raw;
struct packed {
logic [11:0] imm;
logic [4:0] rs1;
} short_v; // 17 bits
} bad_t;typedef union packed {
logic [31:0] raw;
struct packed {
logic [11:0] imm;
logic [4:0] rs1;
logic [14:0] rest; // filler: 32 bits in all
} short_v;
} good_t;Wrong Fill a struct by position, as '{a, b, c}, in code that will live for years.
A member added or moved later shifts every value after it, and widths that match hide the error.
Fix Fill by name, as '{rd: a, rs1: b, default: '0}, so the order of the type can change safely.
Wrong Declare the typedef once in each module that uses the struct.
Two typedefs with the same text are two types, and an unpacked struct port needs the same type on both sides.
Fix Declare the type once in a package and import it in every module that uses it (lesson R9.3).
Remember
- A packed struct is a vector with named parts. Its first member holds the top bits.
- A packed union gives several views of the same bits. Every member has the same width.
- Fill structs by name with
'{member: value, default: '0}, and keep the typedef in a package. - An unpacked struct is a bundle: it synthesizes, and it cannot stand in for a vector.
- A struct, a union or a member select builds no gates. The lab decoder is 48 cells either way.