SystemVerilog associative array:稀疏键值存储与参考模型

关联数组(associative array)以键值对存储数据,索引可以是整数、字符串或类句柄。它只占用已写入条目的空间,是稀疏地址空间建模的首选。

1. 声明与访问

1
2
3
4
5
6
7
logic [7:0] mem [int];        // 以 int 地址索引
int score [string]; // 以字符串索引

initial begin
mem[32'h1000] = 8'h5A;
score["cpu0"] = 100;
end

读取未写入的键返回元素类型的默认值,不会自动创建条目。因此写入前不需要初始化整个地址空间。

2. exists 与 delete

1
2
3
4
5
if (mem.exists(addr))
$display("%h", mem[addr]);

mem.delete(addr);
mem.delete(); // 清空全部

exists() 是区分“未写入”和“写入了默认值”的唯一可靠方法,scoreboard 中必须用它判断首次写。

3. 遍历

1
2
3
4
5
6
int idx;

if (mem.first(idx))
do begin
$display("addr=%0h data=%h", idx, mem[idx]);
end while (mem.next(idx));

关联数组的遍历顺序由实现对键排序决定,不保证插入顺序。若需要稳定顺序,应自己维护键队列。

4. 参考模型应用

1
2
3
4
5
6
7
8
9
10
11
class ref_mem;
logic [7:0] store [longint unsigned];

function void write(longint unsigned a, logic [7:0] d);
store[a] = d;
endfunction

function logic [7:0] read(longint unsigned a);
return store.exists(a) ? store[a] : 8'hxx;
endfunction
endclass

64 位地址空间若用 unpacked 数组会耗尽内存,关联数组只记录实际访问过的地址,是参考内存的标准做法。

5. 常见误区

  1. 依赖遍历顺序做比对:顺序不稳定,应按键显式排序。
  2. 忘记 exists():未写入地址返回默认值,可能被误当作合法数据。
  3. 在 RTL 中综合:关联数组不可综合。

小结

关联数组用空间换时间:只存实际使用的键,代价是查找开销高于连续数组。稀疏地址、按名索引和 scoreboard 期望表都适合它。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog Associative Array 章节(https://chipverify.com/systemverilog/systemverilog-associative-array)。本文为原创中文讲解。