Width independent functions

Ari picture Ari · Mar 27, 2014 · Viewed 9.2k times · Source

Is it possible to write a function that can detect the input data width automatically? For example, consider the parity function below:

function parity;
  input [31:0] data;
  parity = ^ data;
endfunction

When parity(data) is called, the input data should be limited to 32 bits.

Alternatively, one could write a macro, such as `PARITY(data) in which the system function $bits can detect the width of data and make the macro width-independent. Is it possible to have the same flexibility for functions?

Edit: I need my code to be synthesizable.

Answer

nguthrie picture nguthrie · Mar 28, 2014

You can create a parameterized function. See section 13.8 in the LRM. It looks like the function must be declared inside a class like this:

virtual class C #(parameter WIDTH=32);
   static function parity (input [WIDTH-1:0] data);
      parity=^data;
   endfunction
endclass

Then when you call the function parameterized it with the bits task:

assign parity_bit = C#($bits(data))::parity(data);

Working example on EDA Playground.