oop - SystemVerilog 中的打包联合

标签 oop enums system-verilog unions

代码不太长,所以我发布完整的代码。

// Code your design here
module temp;
typedef enum logic[15:0]
{
  ADD = 16'h0000,
  SUB = 16'h0001
} my_opcode_t;

typedef enum logic[15:0]
{
  REG = 16'h0000,
  MEM = 16'h0001
} my_dest_t;
  
  typedef struct packed
{
  my_opcode_t  opcode; // 16-bit opcode, enumerated type
  my_dest_t    dest; // 16-bit destination, enumerated type
  logic [15:0] opA;
  logic [15:0] opB;
} my_opcode_struct_t;

my_opcode_struct_t cmd1;
  
  
typedef union packed
{
  my_opcode_struct_t opcode_s; //"fields view" to the struct
  logic[1:0][31:0] dword; // "dword view" to the struct
} my_opcode_union_t;

my_opcode_union_t cmd2;

initial begin
  $display("cmd1 = %p",cmd1);
  $display("cmd2 = %p", cmd2);
  // Access opcode_s struct fields within the union
  cmd2.opcode_s.opcode = ADD;
  cmd2.opcode_s.dest = REG;
  cmd2.opcode_s.opA = 16'h0001;
  cmd2.opcode_s.opB = 16'h0002;
  $display("cmd1 = %p",cmd1);
  $display("cmd2 = %p", cmd2);

  // Access dwords struct fields within the union
  cmd2.dword[1] = 32'h0001_0001; // opcode=SUB, dest=MEM
  cmd2.dword[0] = 32'h0007_0008; // opA=7, opB=8
  $display("cmd2 = %p", cmd2);
  end
endmodule

来源:https://www.verilogpro.com/systemverilog-structures-unions-design/

输出:

enter image description here

我在 EDA Playground 中运行了这段代码。我不明白为什么会显示“

cmd2='{opcode_s:'{opcode:SUB, dest:MEM, opA:'h7,opB:'h8}}

我期待它会打印双字值。 我对工会的理解缺少什么? 是否因为我们没有使用 cmd2.dword[0]cmd2.dword[1] 它正在打印一些垃圾值?

最佳答案

不打印 dword 值的原因是 %p 格式说明符的行为。请参阅 IEEE Std 1800-2017,第 21.2.1.7 节分配模式格式:

The %p format specifier may be used to print aggregate expressions such as unpacked structures, arrays, and unions. ... For unions, only the first declared elements shall be printed.

如果您按如下方式更改 union 声明(首先使用 dword):

typedef union packed
{
  logic[1:0][31:0] dword; // "dword view" to the struct
  my_opcode_struct_t opcode_s; //"fields view" to the struct
} my_opcode_union_t;

您将看到以下输出:

cmd1 = '{opcode:'hxxxx, dest:'hxxxx, opA:'hxxxx, opB:'hxxxx}
cmd2 = '{dword:'hxxxxxxxxxxxxxxxx}
cmd1 = '{opcode:'hxxxx, dest:'hxxxx, opA:'hxxxx, opB:'hxxxx}
cmd2 = '{dword:'h10002}
cmd2 = '{dword:'h1000100070008}

关于oop - SystemVerilog 中的打包联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70101066/

相关文章:

c++ - 来自 int C++ 类的无效转换

java - 关于 Java 中枚举的问题

verilog - 如何在 Verilog 上显示字符串

verilog - 如何在 RTL 中使用时钟门控?

python 3 : Class inheritance and private fields

javascript - 如何在 ES6 中创建与调用类实例相同类型的新对象?

c# - 我在这里需要抽象类或接口(interface)吗(或者两者都不需要)?

c++ - 枚举成员的值可以自动递减而不是递增吗?

system-verilog - 在包内定义接口(interface)

php - CakePHP 管理索引