Doov
Doov

Reputation: 863

What's the best way to tell if a bus contains a single x in Verilog?

I have a test bench that monitors a bus. Some of the signals (bits) within the bus can be 1'bx. For a variety of reasons, I need to know if any of the signals within the bus are 1'bx. What's the best way to test (not for synthesis -- only for simulation purposes) if a bus contains any x's? I had hoped that I could use a reduction OR and then use ===, but this doesn't seem to work.

Upvotes: 12

Views: 30123

Answers (3)

bcassell
bcassell

Reputation: 46

You can use $countbits(data, 'x) if you want to count only Xs in a vector.

FYI: $isunknown(data) is a synonym for $countbits(data, 'x, 'z)

Upvotes: 1

toolic
toolic

Reputation: 62045

You can use $isunknown (refer to the IEEE Std 1800-2017, section 20.9 Bit vector system functions):

module tb;

reg [3:0] data;

initial begin
    #5 data = 4'b0101;
    #5 data = 4'b000x;
    #5 data = 4'b1111;
    #5 data = 4'b0x0x;
    #5 data = 4'b0x1x;
    #5 data = 4'bzzzz;
    #5 $finish;
end

always @(data) begin
    if ($isunknown(data)) $display($time, " data=%b has x's", data);
end

endmodule

Outputs:

                  10 data=000x has x's
                  20 data=0x0x has x's
                  25 data=0x1x has x's
                  30 data=zzzz has x's

Note that this also treats z as x.

Upvotes: 15

Greg
Greg

Reputation: 19104

(^bus === 1'bX)

Bit-wise xor the bus then check if the result is X. If any bit is X or Z then the result will be X.

To know which bit in the bus has the error:

always @* begin
  for(integer i=0; i<$size(bus); i++) begin
     if(bus[i]===1'bX) $display("bus[%0d] is X",bus[i]);
     if(bus[i]===1'bZ) $display("bus[%0d] is Z",bus[i]);
  end
end

Upvotes: 14

Related Questions