⚙️ Verilog System Functions & Tasks#
Verilog provides many built-in system functions (prefixed with $
) to help with simulation, data manipulation, and runtime control. These are not synthesizable and should only be used in testbenches or simulation-only environments.
🎲 Randomization Functions#
Function | Description | Example |
---|---|---|
$random | Returns a 32-bit signed pseudo-random int | r = $random; |
$urandom | Returns 32-bit unsigned random number | r = $urandom; |
$urandom_range(min, max) | Bounded unsigned random | r = $urandom_range(0, 15); |
Use for test stimulus generation in testbenches.
🛑 Simulation Control Tasks#
Task | Description | Example |
---|---|---|
$stop | Pauses simulation and enters debugger (if supported) | $stop; |
$finish | Ends simulation cleanly | $finish; |
$fatal | Ends simulation with error (like assert ) | $fatal(1, "Error!"); |
➗ Math and Conversion Functions#
Function | Description | Example |
---|---|---|
$clog2(x) | Returns ceiling of log base 2 | localparam W = $clog2(10); |
$bits(x) | Returns number of bits in variable | $bits(my_reg) |
$signed(x) | Converts to signed | out = $signed(data); |
$unsigned(x) | Converts to unsigned | out = $unsigned(signed_data); |
$clog2
is useful for parameterizing memory widths, counters, etc.
module tb_system_tasks;
reg [7:0] r1, r2;
reg [3:0] index;
reg signed [15:0] s_val = -10;
reg [15:0] u_val;
initial begin
// Randomization
r1 = $urandom;
r2 = $urandom_range(0, 15);
$display("Random r1 = %0d, r2 (0-15) = %0d", r1, r2);
// Math & conversion
index = $clog2(10); // = 4
$display("clog2(10) = %0d", index);
u_val = $unsigned(s_val);
$display("s_val = %0d, u_val = %0d", s_val, u_val);
// Simulation control
#20 $finish;
end
endmodule