32位ALU仿真输出含X与0混合值问题排查求助
32位ALU仿真输出R出现X与0混合的问题解决
问题背景
设计32位ALU时,Modelsim仿真发现输出R存在X与0混合的异常值:20ns执行加法运算、40ns执行减法运算时均出现该问题。ALU由Adder、Subtractor和32位2x1多路选择器组成,且Adder、Subtractor单独测试结果正确。
相关代码
ALU顶层模块
module alu32(input [31:0] A, input [31:0] B, input [2:0] ALUOP, output [31:0] R); wire [31:0] w0, w1, w2, w3, w4, w5, w6, w7; wire carry_out_add, carry_out_sub, carry_in; adder add(.sum(w0), .carry_out(carry_out_add), .A(A), .B(B), .carry_in(1'b0)); // ADD 000 sub sub(.A(A), .B(B), .out(w1)); // SUB 001 _32bit_mux2x1 mux(w0, w1, ALUOP, R); endmodule
测试平台代码
`timescale 1ns / 1ps `define DELAY 20 module testbench_alu32(); reg [31:0] A = 32'b0; reg [31:0] B = 32'b0; wire [31:0] R = 32'b0; reg [2:0] ALUOP; reg clk, start; alu32 alu(A, B, ALUOP, R); initial begin clk = 1'b0; #10 start = 1'b1; #2100 $finish; end always #100 clk = ~clk; initial begin #`DELAY; // add A = 32'b00000001111000000001111011110101; B = 32'b00000000000000000000000000000010; ALUOP = 3'b000; #`DELAY; // sub A = 32'b00000000000000000000000000001111; B = 32'b00000000000000000000000000000011; ALUOP = 3'b001; #`DELAY; end initial begin $monitor("\ntime=%2d, \nA=%32b, \nB=%32b, \nR=%32b, \nALUOP=%3b \n\n", $time, A, B, R, ALUOP); end endmodule
32位2x1多路选择器
module _32bit_mux2x1(input [31:0] I0, input [31:0] I1, input s, output [31:0] out); genvar i; generate for(i=0; i<32; i=i+1) begin: no_time_left _1bit_mux2x1 mux2x1(I0[i], I1[i], s, out[i]); end endgenerate endmodule
1位2x1多路选择器
module _1bit_mux2x1(input I0, input I1, input s, output out); wire input0; wire input1; wire s_not; not not_s(s_not, s); and and0(input0, s_not, I0); and and1(input1, s, I1); or or0(out, input0, input1); endmodule
问题根源
- 多路选择器选择信号不匹配:
alu32模块中,将3位的ALUOP直接传入仅支持1位选择信号的_32bit_mux2x1模块。这会导致选择信号的高两位处于未知状态(X),进而使多路选择器内部逻辑输出X值。 - 测试平台非法赋值:测试平台中对
wire类型的R进行初始化赋值(wire [31:0] R = 32'b0;),这在Verilog中是不允许的,线网类型只能由驱动赋值,不能直接初始化。
解决方案
- 修正多路选择器的选择信号连接:在
alu32模块中,仅传入ALUOP的最低位作为多路选择器的选择信号,因为当前仅用最低位区分加法(000)和减法(001):
_32bit_mux2x1 mux(w0, w1, ALUOP[0], R);
- 修正测试平台的线网定义:将测试平台中的
wire [31:0] R = 32'b0;改为:
wire [31:0] R;
验证效果
修改完成后重新仿真,多路选择器将正确根据ALUOP[0]选通加法或减法的输出结果,R的输出将不再出现X与0混合的异常情况。
内容的提问来源于stack exchange,提问作者questionhead
相关产品推荐
相关产品推荐

