SystemVerilog unique/priority case:case 语句的完整性声明

case 语句同样可以加 unique / priority 修饰,用来声明分支互斥性或优先级。与 if-else 相比,case 更常用于译码器和状态机。

1. unique case

1
2
3
4
5
6
7
8
9
10
typedef enum logic [1:0] {IDLE, READ, WRITE, DONE} state_t;

always_comb begin
unique case (state)
IDLE: next = READ;
READ: next = WRITE;
WRITE: next = DONE;
DONE: next = IDLE;
endcase
end

枚举已覆盖全部取值,因此 unique case 可以省略 default。若后续新增枚举成员却忘记增加分支,检查工具会报错。

2. priority case

1
2
3
4
5
6
7
8
9
always_comb begin
priority casez (req)
4'b1??? : grant = 4'b1000;
4'b01?? : grant = 4'b0100;
4'b001? : grant = 4'b0010;
4'b0001 : grant = 4'b0001;
default : grant = 4'b0000;
endcase
end

priority casez 表达“高位优先仲裁”:多个 req 同时有效时,靠前的分支胜出。

3. 默认值策略

即使写了 unique,也建议保留 default 分支处理非法编码:

1
2
3
4
5
unique case (state)
IDLE: ...;
...
default: next = IDLE; // 非法状态恢复
endcase

这样既保留唯一性检查,又避免状态机跑飞。

4. 常见误区

  1. 用 unique case 替代穷举:关键字不生成分支,只检查分支。
  2. casez 中 ? 与 x 混用导致匹配歧义。
  3. 把 priority case 当成无优先级的并行译码。

小结

unique 用于“恰好一个分支”,priority 用于“按顺序取第一个”。casez/casex 处理无关位,default 处理非法态,三者组合才能写出健壮的译码逻辑。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog ‘unique’ and ‘priority’ case 章节(https://chipverify.com/systemverilog/systemverilog-unique-priority-case)。本文为原创中文讲解。