Tasks & Functions
Reusable code in Verilog: functions for combinational calculations (synthesizable) and tasks for timed testbench procedures.
Functions and tasks package reusable code. A function computes and returns one value in zero simulation time, so it can be used in expressions and in synthesizable logic. A task can take time (wait for clocks, contain delays), have several outputs, and is mainly used in testbenches.
A function in a design, a task in the testbench
function [3:0] popcount(input [7:0] v); declares a 4-bit return value and one input.
The function name is used as the return variable.
{3'd0, v[k]} widens each bit to 4 bits so the additions do not lose width.
Rules
function check(input [7:0] v); @(posedge clk); // error task check(input [7:0] v); @(posedge clk);
Functions execute in zero time and cannot contain timing controls. Anything that waits must be a task.
Can a function be synthesized? Can a task?
Functions are synthesizable (they become combinational logic). Tasks without timing controls are accepted by many synthesis tools, but tasks are mainly used in testbenches.
Why declare a task automatic?
Static tasks share one copy of their variables across all calls; if two calls overlap in time (fork, or calls from two initial blocks) they corrupt each other's variables. automatic gives each call its own storage.