Functions and Tasks in RTL

Write functions that synthesize to the logic you expect, and find the two ways a function makes simulation differ from the gates.

You Will Be Able To

  • Predict how many copies of its logic a function builds.
  • Choose between automatic and static storage, and between a task and a void function.
  • Find a stale output caused by a function that reads a signal it does not take as an argument.
  • Write a constant function that sizes a port at elaboration.
Lesson
R11.3
Time
25 min
Runs on
Your browser
Check
5 questions

A gain block limits its output to a ceiling that software can lower. Software lowered it, and the simulation kept showing the old, larger output. The synthesized block had no such fault. The limiter was a function, and the function read the ceiling without anyone passing it in.

The Ceiling Moves and the Simulated Output Does NotThe lab bench, 1 ns after edges 2 to 7. y (Icarus) is the shipped design in simulation. y (gates) is what the synthesized block computes: twice the sample, limited to the ceiling.
012345clksample607090ceiling200100250150y (Icarus)120100150y (gates)120100140150stalestalestale
Scroll horizontally ↔
  1. Cycle 0

    Edge 2: the sample is 60 and the ceiling 200. Both rows show 120.

  2. Cycle 1

    Edge 3: only the ceiling changed, to 100. The gates give 100. Simulation still shows 120.

  3. Cycle 3

    Edge 5: the sample changed, so the block ran again and caught up.

  4. Cycle 4

    Edge 6: the ceiling rose alone to 250. The gates give 140. Simulation still shows 100.

Measured on Icarus 12. Verilator 5.052 printed the gates row for the same file.

A Function Is Logic, Copied at Every Call

A function takes inputs, runs in zero time and returns a value. In RTL it is a named piece of combinational logic. The synthesizer pastes that logic in at every place you call it.

Two Calls, Two CopiesArrows show data. Each call site becomes its own copy of the function body.
  • Neutral
  • Step
  • Datapath
  • Structure
Two calls, two copiesArrows show data. Each call site becomes its own copy of the function body. neutral sat_add one definition in apackage step sat_add(a, b) call site 1 step sat_add(c, d) call site 2 datapath adder + limiter its own gates, drivesy datapath adder + limiter its own gates, drivesz used byused bybuildsbuilds
  1. neutral sat_addone definition in a package
    • used by → sat_add(a, b)
    • used by → sat_add(c, d)
  2. step sat_add(a, b)call site 1
    • builds → adder + limiter
  3. step sat_add(c, d)call site 2
    • builds → adder + limiter
  4. datapath adder + limiterits own gates, drives y
  5. datapath adder + limiterits own gates, drives z
  1. One definition

    The package holds the text of sat_add once.

  2. Two calls

    The module calls it for y and again for z.

  3. Two copies

    Synthesize reports 89 cells for the module. One call alone is 44.

Read the diagram as text
  • sat_add: one definition in a package
  • sat_add(a, b): call site 1
  • sat_add(c, d): call site 2
  • adder + limiter: its own gates, drives y
  • adder + limiter: its own gates, drives z
  • sat_add → sat_add(a, b): used by
  • sat_add → sat_add(c, d): used by
  • sat_add(a, b) → adder + limiter: builds
  • sat_add(c, d) → adder + limiter: builds

A function saves typing and review time. It does not save gates.

The function lives in a package, so any module can import it (lesson R9.3).
package sat_pkg;
  // The sum of two bytes, held at 255.
  function automatic logic [7:0] sat_add(input logic [7:0] a, b);
    logic [8:0] s;
    s = a + b;
    return s[8] ? 8'hff : s[7:0];
  endfunction
endpackage

module two_calls
  import sat_pkg::*;
(
  input  logic [7:0] a, b, c, d,
  output logic [7:0] y, z
);
  assign y = sat_add(a, b);      // one copy of the adder and the limiter
  assign z = sat_add(c, d);      // a second copy
endmodule
How the module calls sat_addCellsLevels
once: y = sat_add(a, b)4416
twice, two results: y and z8916
twice, nested: sat_add(sat_add(a, b), c)8832
once, arguments chosen by sel6217

Measured on this flow. Nesting puts the copies in series, so the levels double.

automatic, and What Static Storage Does

A function declared in a module or a package is static unless you write automatic. Static means its arguments and local variables exist once, and every call shares them. They keep their values after the call returns.

Hardware has no such memory inside a block of gates. So a static function can simulate one way and synthesize another.

Static, and the variable is never cleared

function logic [2:0] ones(input logic [3:0] d);
  logic [2:0] n;
  for (int i = 0; i < 4; i++)
    n = n + 3'(d[i]);
  return n;
endfunction

Icarus 12 prints x: n starts unknown. With n cleared once, the count keeps growing: 3, then 4 for inputs 0111 and 0001. Synthesize refuses the module: found logic loop. Lint warns UNOPTFLAT.

Automatic, and the variable starts at 0

function automatic logic [2:0] ones(input logic [3:0] d);
  logic [2:0] n = 0;
  for (int i = 0; i < 4; i++)
    n = n + 3'(d[i]);
  return n;
endfunction

Icarus 12: 3 and then 1. Synthesize builds 9 cells and 4 levels of logic.

Rule for an RTL functionReason
Declare it automaticeach call gets fresh variables, as each copy of the logic does
Assign every local variable before reading itan automatic variable starts unknown at each call
Use input arguments, and output ones in a void functionevery synthesis tool accepts these two directions
Return with return value; on every patha path that returns nothing gives an unknown or an old value

Tasks and void Functions

A task is a subroutine with no return value. It passes results out through output arguments. Unlike a function, a task may wait for time or for a clock edge.

That freedom is the problem in RTL. A void function does the same job and cannot wait, so the compiler enforces the rule for you.

SubroutineThis flowTool message
task with no wait: reverses 8 bitsbuilds, 0 cells (wiring)none
void function with two outputs: reversed byte and paritybuilds, 7 cellsnone
task that waits: @(posedge clk); insiderefusedunsynthesizable timing control
function with a delay: #1 insiderefusedYosys: statements that pass time are not allowed in this context. Lint: Delays are not legal in functions

Measured on the pinned Yosys and the Lint button.

Constant Functions: Run by the Tool

A function called with only parameters and literals is a constant function. The tool runs it during elaboration, before any hardware exists. Its result can size a port or a counter.

With DEPTH at 12 the function returns 4. Synthesize reports 13 cells and 4 flops: a 4-bit pointer and its wrap logic. The loop inside the function built nothing.
module fifo_ptr #(parameter int DEPTH = 12) (
  input  logic                         clk, rst_n, inc,
  output logic [width_for(DEPTH)-1:0]  ptr
);
  // How many bits a pointer into n entries needs.
  function automatic int width_for(input int n);
    int w = 1;
    while ((1 << w) < n) w++;
    return w;
  endfunction
  localparam int W = width_for(DEPTH);   // called with a parameter: it runs in the tool

  always_ff @(posedge clk or negedge rst_n)
    if (!rst_n)   ptr <= '0;
    else if (inc) ptr <= (ptr == W'(DEPTH - 1)) ? '0 : ptr + 1'b1;
endmodule

Pass it a signal and the same call is refused: reference to non-constant variable 'd' is not allowed in a constant expression.

What always @* Cannot See

always @* builds its wake-up list from the signals that its own statements read. It does not look inside a function. always_comb does.

How y is drivenChanges with gain alone on Icarus 12?
always_comb y = mul(d);yes
always @* y = mul(d);no: stale
assign y = mul(d);no: stale
always @* y = mul2(d, gain);yes: gain is an argument
always @(d or gain) y = mul(d);yes, as long as the list is kept complete by hand

mul reads gain from the module. mul2 takes it as an argument. A continuous assign missed the change too.

Two habits remove the problem. Use always_comb for combinational logic. And pass a function everything it reads, so the call shows its inputs.

The Lab: The Limiter That Missed Its Ceiling

Design brief
PortDirectionWidthMeaning
clkinput1clock
rst_ninput1reset, asynchronous, active-low
sampleinput[7:0]the input sample
ceilinginput[7:0]the largest value y may take
youtput[7:0]twice the sample, limited to the ceiling
y_qoutput[7:0]y registered
Clock
rising edge
Reset
rst_n asynchronous, active-low
Corner cases
ceiling changing while sample stays still. Done when: Run shows y=100 at edge 3 and y=140 at edge 6, and Synthesize still reports 43 cells
  1. Run as shipped

    At edges 3, 4 and 6 y ignores the new ceiling, and y_q stores the stale value. Lint prints nothing.

  2. Find what the block reads

    The statement reads sample. The function also reads ceiling, which the statement never names.

  3. Fix it

    Change always @* to always_comb and Run. y follows the ceiling at once.

  4. Make the input visible

    Give clip a second argument for the ceiling and pass it in the call. Now even always @* would work, and a reader sees the dependency.

  5. Check the gates

    Synthesize each version: 43 cells, 8 flops, 11 levels every time. Only the simulation changed.

Asked in interviews
  1. Why should RTL functions be automatic?

    A static function shares its variables between calls and keeps their values. Hardware built from the function has no such memory, so simulation and gates can differ. An automatic function gets fresh variables at each call.

  2. Does calling a function twice share its logic?

    No. Each call builds a copy. On this flow one saturating add was 44 cells and two calls were 89. To share, mux the arguments into a single call.

  3. What is the difference between always @* and always_comb with functions?

    always @* is sensitive only to signals its own statements read. always_comb also includes signals read inside the functions it calls, and it runs once at time 0.

Try It

The bench changes its inputs 1 ns after an edge and prints 1 ns after the next one. At edges 3 and 4 the ceiling is 100, yet y shows 120. At edge 6 the ceiling is 250, yet y shows 100.

The block reran only when sample changed, at edges 2, 5 and 7. With always_comb the six lines read 120, 100, 100, 100, 140 and 150.

Synthesize reports 43 cells: 8 $_DFF_PN0_ flops and 35 gates, 0 latches and 11 levels of logic. The count is the same for the fixed design.

RTLIcarus Verilog · in your browser · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: e2 sample=60 ceiling=200 y=120 y_q=120 e3 sample=60 ceiling=100 y=120 y_q=120 e4 sample=60 ceiling=100 y=120 y_q=120 e5 sample=70 ceiling=100 y=100 y_q=100 e6 sample=70 ceiling=250 y=100 y_q=100 e7 sample=90 ceiling=150 y=150 y_q=150

Original design · 43 cells · 8 flip-flops · 0 latches · 11 logic levels. Synthesis uses Yosys; counts depend on the toolchain.

Read included file: tb.sv
`timescale 1ns/1ps
module tb;
  logic clk = 0;
  always #5 clk = ~clk;                   // rising edges at 5, 15, 25, ...
  logic rst_n = 1;                        // falls at 1 ns, rises 1 ns after edge 1
  int edge_n = -1;
  always @(posedge clk) edge_n = edge_n + 1;
  logic [7:0] sample = 0, ceiling = 8'd200;
  logic [7:0] y, y_q;
  clip_gain dut (.*);
  task automatic tick();
    @(posedge clk); #1;
    if (rst_n) $display("e%0d sample=%0d ceiling=%0d y=%0d y_q=%0d", edge_n, sample, ceiling, y, y_q);
  endtask
  initial begin
    #1 rst_n = 0; tick(); tick(); rst_n = 1;
    sample = 8'd60;                   tick();
    ceiling = 8'd100;                 tick();   // the ceiling changes alone
                                      tick();
    sample = 8'd70;                   tick();
    ceiling = 8'd250;                 tick();   // the ceiling changes alone
    sample = 8'd90; ceiling = 8'd150; tick();
    $finish(0);
  end
endmodule

Check Yourself

Predict the outputouter calls inner. Each one reads a module signal that is not an argument. The bench changes x, then step, then base, each alone. What does Icarus 12 print?
module tb;
  logic [3:0] base = 4'd2, step = 4'd1, x = 4'd0, y;
  function automatic logic [3:0] inner(input logic [3:0] v);
    return v + step;
  endfunction
  function automatic logic [3:0] outer(input logic [3:0] v);
    return inner(v) + base;
  endfunction
  always @* y = outer(x);
  initial begin
    #1 x = 4'd4;
    #1 step = 4'd3;
    #1 base = 4'd5;
    #1 $display("y=%0d", y);
    $finish(0);
  end
endmodule
Spot the bugEach option drives y from a function. mul reads gain from the module, and mul2 takes it as an argument. The bench changes d and gain one at a time and checks y. Which option fails on Icarus 12?
ConceptA module calls an 8-bit saturating-add function twice, for two separate outputs. One call alone built 44 cells on this flow. What did two calls build?
ConceptWhich subroutine does this flow refuse to synthesize?
ConceptA static function counts the 1 bits of its input in a local variable that it never clears. What did the tools do with it?

Common Mistakes

Wrong Call one function in ten places and expect one shared block of logic.

Each call builds its own copy of the function body.

Fix Share on purpose: mux the arguments into one call, and check the cell count.

Before
assign y = sat_add(a, b);
assign z = sat_add(c, d);   // two adders: 89 cells
After
// one adder, when only one result is needed at a time
assign y = sat_add(sel ? c : a,
                   sel ? d : b);   // 62 cells

Wrong Leave out automatic on a function in a module or a package.

The function is then static, so its variables are shared by every call and keep their last values.

Fix Write function automatic for every RTL function, and give each local variable a value before you read it.

Wrong Put a wait such as @(posedge clk) inside a task that RTL calls.

This flow refuses it: unsynthesizable timing control.

Fix Keep time in the always_ff block. Use a void function for the zero-time work, so the compiler rejects any wait.

Wrong Size a port with a function call whose argument is a signal.

A size must be known at elaboration, and a signal has no value then.

Fix Call the function with parameters and literals only, as localparam int W = width_for(DEPTH); does.

Remember

  • A function is combinational logic. Every call builds its own copy: 44 cells for one saturating add, 89 for two.
  • Declare RTL functions automatic and assign each local variable before reading it.
  • A subroutine in RTL runs in zero time. Use a void function where you would write a task.
  • A function called with parameters only runs in the tool and can size a port.
  • always @* does not look inside functions and always_comb does. Pass a function everything it reads.

Practice

Report a problem with this page