Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Width independent functions

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.

like image 899
Ari Avatar asked Mar 27 '14 19:03

Ari


2 Answers

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.

like image 116
nguthrie Avatar answered Sep 22 '22 16:09

nguthrie


You can use macros. The function can be declared like:

`define PARITY(FUNC_name, WIDTH)             \
function FUNC_name (input [WIDTH-1:0] data); \
begin                                        \
  FUNC_name = ^ data;                        \
end                                          \
endfunction                       

and you can call it with:

`PARITY(parity, 32);
assign parity_bit = parity(data);

This code is synthesizable in xilinx, altera and synopsys tools

like image 34
Chrysa Avatar answered Sep 18 '22 16:09

Chrysa