Search code examples
verilogmodelsim

why output of 2nd function call to 4 bit adder is X(don't care)?


I am new to verilog, I was building a 32-bit adder using structural modelling. So I made a 1-bit full adder, then used that to construct a 4-bit adder, and that was used to create an 8- bit adder. Everything works fine until the 4-bit adder but when I use the 4-bit adder as a function this error pops up.

module adder_1bit(Sum,CarryOut,A,B,CarryIn);

output Sum,CarryOut;
input A,B,CarryIn;

assign Sum = A^B^CarryIn;
assign CarryOut = (A&B) | (B&CarryIn) | (A&CarryIn);


endmodule

module adder_4bit(Sum,CarryOut,A,B,CarryIn);

output [3:0] Sum;
output CarryOut; 
input [3:0] A,B;
input CarryIn;
wire w[2:0];

assign CarryIn = 1'b0;
adder_1bit add0(Sum[0],w[0],A[0],B[0],CarryIn);
adder_1bit add1(Sum[1],w[1],A[1],B[1],w[0]);
adder_1bit add2(Sum[2],w[2],A[2],B[2],w[1]);
adder_1bit add3(Sum[3],CarryOut,A[3],B[3],w[2]);

endmodule 


module adder_8bit(Sum,CarryOut,A,B,CarryIn);

output [7:0] Sum;
output CarryOut; 
input [7:0] A,B;
input CarryIn;
wire w;

assign CarryIn = 1'b0;
adder_4bit add4(Sum[3:0],w,A[3:0],B[3:0],CarryIn);
adder_4bit add5(Sum[7:4],CarryOut,A[7:4],B[7:4],w);

endmodule 

When I run with the following testbench code I get MSB 4-bit get as don't care

module adder_test;

reg [7:0] A,B;
reg CarryIn;
wire [7:0] Sum;
wire CarryOut;

adder_8bit UUT (Sum,CarryOut,A,B,CarryIn);

initial
    begin
    A = 8'b00101011;
    B = 8'b01010110;
    CarryIn = 1'b0;
#10;
    
    end
endmodule

Simulation Result enter image description here


Solution

  • Your problem is in this statement: assign CarryIn = 1'b0;

    The following happens:

       module adder_4bit(Sum,CarryOut,A,B,CarryIn);
          ... 
          assign CarryIn = 1'b0;
    

    In this case you have carryIn driven by two drivers:

    1. the input port
    2. the assign statement

    Unless the value of the port is the same as your driver (1'b0) the resulting value of carryIn will always be 'x'. This interferes with all your results.

    To fix the issue just move this statement to your test bench:

    module adder_test;
      ...
      wire CarryOut = 0;