You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Verilog for循环中k数组位拼接失效问题求助

问题

尝试将k、count与输入数据in拼接至temp_reg中时,k数组的位未被成功拼接,但count与in的拼接工作正常,请问实现方式存在问题吗?

代码实现

module Concatenation #(
    parameter NUM_VALS = 8,
    parameter SIZE     = 8
)(  input  wire rst,
    input  wire clk,
    input  wire [NUM_VALS-1:0] k,
    input  wire [NUM_VALS*SIZE-1:0] in,
    output reg  [NUM_VALS*SIZE-1:0] out
);
    reg [2:0] count;
    reg [SIZE + 3:0] temp_reg [1:NUM_VALS];

    always @* begin
    if(~rst) begin
        count = 7;
    end
    else begin
        for (int i = 0; i < NUM_VALS; i = i + 1) begin
            temp_reg[i+1] = {k[i], count-i, in[i*SIZE +: SIZE]};
        end
    end
    end

endmodule

测试示例

k = [101]
count = 7;
in = [00100010_00100010_00100010]

预期结果

temp_reg = [111100100010
            011000100010
            110100100010]

实际结果

temp_reg = [011100100010
            011000100010
            010100100010]

可见k中的所有位均未被正确拼接。


分析与解决

问题核心出在组合逻辑的latch隐患以及代码规范问题上,具体如下:

  1. count变量的latch问题
    原代码中count仅在~rst条件下赋值,当rst为高电平时,count无赋值路径,综合器会生成latch锁存其值。虽然你的测试中count-i结果正常,但latch会引入信号不稳定风险,可能间接影响k[i]的拼接采样。

  2. 循环变量类型兼容性
    使用int作为循环变量是SystemVerilog语法,部分传统Verilog综合器可能存在兼容性问题,建议改用integer保证兼容性。

  3. out信号未赋值
    原代码中out始终未被赋值,属于无效输出,需补充对应逻辑。

修改后的代码

module Concatenation #(
    parameter NUM_VALS = 3, // 匹配示例的参数默认值
    parameter SIZE     = 8
)(  input  wire rst,
    input  wire clk,
    input  wire [NUM_VALS-1:0] k,
    input  wire [NUM_VALS*SIZE-1:0] in,
    output reg  [NUM_VALS*SIZE-1:0] out
);
    reg [2:0] count;
    reg [SIZE + 3:0] temp_reg [0:NUM_VALS-1]; // 改为0起始数组,符合常规编码习惯

    // 时序逻辑处理count,避免latch
    always @(posedge clk or negedge rst) begin
        if(~rst) begin
            count <= 7;
        end else begin
            count <= count; // 若需计数逻辑,可在此修改,示例中保持固定值7
        end
    end

    // 组合逻辑完成拼接
    always @* begin
        for (integer i = 0; i < NUM_VALS; i = i + 1) begin
            temp_reg[i] = {k[i], count - i, in[i*SIZE +: SIZE]};
        end
        // 补充out的赋值逻辑(示例为提取temp_reg的低8位,可按需调整)
        for (integer i = 0; i < NUM_VALS; i = i + 1) begin
            out[i*SIZE +: SIZE] = temp_reg[i][SIZE-1:0];
        end
    end

endmodule

额外注意事项

  • 确保NUM_VALS参数与k、in的位宽匹配,比如示例中NUM_VALS=3时,k需为3位,in需为24位;
  • 确认k的位序是否符合预期:k[i]对应k的第i位(最低位为k[0]),若你的输入k是高位在前,需调整索引顺序(如用k[NUM_VALS-1-i])。

内容的提问来源于stack exchange,提问作者Musadiq Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:59:55