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.

One Word, Three ViewsArrows show the same 32 bits read through three packed structs. The opcode picks the view the decoder uses.
  • Neutral
  • Data
One word, three viewsArrows show the same 32 bits read through three packed structs. The opcode picks the view the decoder uses. neutral ins.raw 32 bits from thefetch stage neutral ins.r funct7 rs2 rs1funct3 rd opcode neutral ins.i imm rs1 funct3 rdopcode neutral ins.s imm_hi rs2 rs1funct3 imm_lo opcode neutral opcode bits 6:0 in every view neutral fields rd, rs1, rs2, imm same bitssame bitssame bitsr.opcodea storeaddi, lw
  1. neutral ins.raw32 bits from the fetch stage
    • same bits → ins.r
    • same bits → ins.i
    • same bits → ins.s
  2. neutral ins.rfunct7 rs2 rs1 funct3 rd opcode
    • r.opcode → opcode
  3. neutral ins.iimm rs1 funct3 rd opcode
    • addi, lw → fields
  4. neutral ins.simm_hi rs2 rs1 funct3 imm_lo opcode
    • a store → fields
  5. neutral opcodebits 6:0 in every view
  6. neutral fieldsrd, rs1, rs2, imm
  1. One word

    The union holds 32 bits. ins.raw, ins.r, ins.i and ins.s are four names for those same bits.

  2. The opcode picks a view

    Bits 6:0 mean the same in every format, so the decoder reads them as ins.r.opcode.

  3. A store uses the S view

    For opcode 0100011 the decoder joins ins.s.imm_hi and ins.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:2524:2019:1514:1211:76:0
funct7rs2rs1funct3rdopcode

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 writeIt means
ins.r.rdbits 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_tconnects 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.

View31:2524:2019:1514:1211:76:0
ins.rfunct7rs2rs1funct3rdopcode
ins.iimm[11:5]imm[4:0]rs1funct3rdopcode
ins.simm_hirs2rs1funct3imm_loopcode

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.

TypeThis flowTool message
packed union, members of equal widthbuildsnone
packed union, one member 17 bits and one 32refusedall members of a packed union must have the same width; 'short_v' has width of 17, previously seen width was 32
tagged unionrefusedYosys: 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 goesRule
A module portput the typedef in a package and import it in the module header
A function argument or resultthe same: function automatic fields_t decode(input instr_t ins);
A copyf2 = f1; copies every member, packed or not
A flopalways_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 packedstruct (unpacked)
Storageone vector, first member on topseparate members
Membersbits, vectors, packed structs and unionsany type, including arrays and int
Assign to or from a vectoryesno
Use in a unionyesno
Connect to a portany vector of the same widthonly the very same typedef
Synthesis on this flowbuildsbuilds
Verilator printed 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
endmodule

Assign 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.

Synthesize reports 106 cells: 64 flops for two tables of four 8-bit records, 33 $_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
LineWhat it doesMeasured on Verilator
tab <= '{default: '0};clears every member of every entrylen_hi=000 after reset
shadow <= '{'0, '0, '0, '{en: 1'b1, default: '0}};a list, one item per entry, 0 to 3shadow[3]=10000000 after reset
tab[waddr] <= wdata;writes one whole recordlen_hi=101 after a write of len 22 to entry 2
shadow <= tab;copies the array; sizes and types must matchshadow[2]=11010110 after the copy
tab[raddr].len[4:2]the entry, then the member, then the bitsreads 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

Design brief
PortDirectionWidthMeaning
insinput[31:0]one RV32I instruction word, typed instr_t
foutput[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=-12 for the sw line, and Synthesize reports 48 cells
  1. Run as shipped

    The add, addi and lw lines are right. The sw line reads rs1=2 rs2=20 imm=1125. Only the S view is wrong.

  2. Compare the type with the ruler

    The S row of the ruler starts with imm_hi at bits 31:25. The shipped s_type_t starts with opcode. Its author listed the fields from bit 0 up.

  3. Fix the order

    List the members from the top bit down, as the block below shows. Run: the sw line reads rd=0 rs1=8 rs2=5 imm=-12.

  4. 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
The decoder itself does not change. Lint is silent before and after.
  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
48 cells, 6 levels, the same four printed lines. Every index here is a place to make the mistake the struct made once.
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
endmodule
Asked in interviews
  1. 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.

  2. 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.

  3. 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.

RTLVerilator · simulator service · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: 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=1125

Original 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

Predict the outputThe header struct has a 1-bit, a 3-bit and an 8-bit member. The bench fills it with a pattern, then adds 1 to len. What does it print?
module tb;
  typedef struct packed { logic valid; logic [2:0] kind; logic [7:0] len; } hdr_t;
  hdr_t h;
  initial begin
    h = '{kind: 3'd5, default: '0};
    h.len = h.len + 8'd1;
    $display("%0d %h", $bits(h), h);
    $finish(0);
  end
endmodule
Spot the bugEach option fills the struct so that hi gets a and lo gets b. The bench checks both members. Which option fails?
ConceptIn the lab, the struct decoder (after the fix) and the hand-indexed decoder were both synthesized on this flow. What did the counts show?
ConceptA block needs one type for a 24-bit header that is stored in a memory word and compared with a 24-bit bus. Which declaration fits?
Conceptchan_t tab [4]; is an array of packed structs with members en, prio[1:0] and len[4:0]. Which select reads the top two bits of len in entry 3?

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.

Before
typedef union packed {
  logic [31:0] raw;
  struct packed {
    logic [11:0] imm;
    logic [4:0]  rs1;
  } short_v;                 // 17 bits
} bad_t;
After
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.

Practice

Report a problem with this page