【问题标题】:Verilog/SV conditional variable definitionVerilog/SV条件变量定义
【发布时间】:2016-08-31 16:00:23
【问题描述】:

有没有办法根据参数来操作变量实例化?

例如,如果我在此处仅输入 bit [WIDTH-1:0] a; 并设置 DEPTH == 1,则 WIDTH 将为 0,bit [-1:0] a; 没有意义。

当我在下面的示例中对其进行编码时,我在第二个 $display 上收到错误:“未声明的标识符:a”。有没有办法在 Verilog/SV 中实现这一点,还是我的代码中有错误?

module test #(
  parameter DEPTH = 2,
  parameter WIDTH = $clog2(DEPTH)
)();

  generate
    if (WIDTH == 0) begin
      bit             a;
    end else begin
      bit [WIDTH-1:0] a;
    end
  endgenerate

  initial begin
    $display("WIDTH: %d", WIDTH);
    $display("Bit width of a: %d", $bits(a));
  end
endmodule: test

【问题讨论】:

    标签: verilog system-verilog hdl


    【解决方案1】:

    你需要做的就是

    bit [(WIDTH>0 ? WIDTH-1 : 0):0] a;
    

    【讨论】:

    • 哇:|甚至不知道这是可能的。很好的答案,谢谢戴夫
    【解决方案2】:

    您使用的是哪个版本的 Verilog? $clog2 是在 Verilog-2005 中引入的。以前的实现,可能会产生奇怪的结果。

    见下文,我做了一个循环来显示递增深度与 clog2 的结果。

    CLOG2(0) =           0
    CLOG2(1) =           0
    CLOG2(2) =           1
    CLOG2(3) =           2
    CLOG2(4) =           2
    

    要表示 1 的值,例如,你需要 1 位,而不是 0 要表示 2 的值,您需要 2 位……而不是 1。 要表示 4 的值,您需要 3 位。 CLOG2 在转换点处始终为 1 短路。随着您的成长,先前的解决方案不会考虑到这一点。

    如果你说

    WIDTH = $clog(DEPTH+1);
    

    我想你会自动得到你想要的结果。

    【讨论】:

    • 我正在使用 SystemVerilog。不幸的是,我希望 CLOG2(1) 和 CLOG2(2) 的结果都是 1,所以这不是我需要的。
    【解决方案3】:

    我定期制作并使用它。它确定整数值的位宽度。 0 的特殊情况将返回值 1(您仍然需要 1 位来保存该值)。假设您需要基于具有 256 个地址的内存定义一个索引变量

    参数 NUM_ADDR 256

    localparam A_SZ = bit_size(NUM_ADDR-1); // 示例:255(最高地址)应该返回 8

    逻辑 [A_SZ-1:0] 索引; // 示例:[7:0] 索引

    那么我只需要更改 NUM_ADDR

    function integer bit_size;
    input integer value;
    reg [31:0] shifted;
    integer res;
    begin
      if (value != 0)
      begin
           shifted = value;
           for (res=0; (shifted != 0); res=res+1)
               shifted = shifted >> 1;
           bit_size = res;
      end
      else
         bit_size = 1; // minimum size, even for a value of 0
    end
    endfunction
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多