SystemVerilog Functions in Constraints

Functions in Constraints

In some cases constraint can’t be expressed in a single line, in such cases function call can be used to constrain a random variable. calling the function inside the constraint is referred to as function in constraints.

  • The function will be written outside the constraint block
  • Constraint logic shall be written inside the function as function definition and function call shall be placed inside the constraint block
  • Functions shall be called before constraints are solved, and their return values shall be treated as state variables.
constraint constraint_name { var = function_call(); };

Functions in constraints example

In the below example,
The function is called inside the constraint.

class packet;
  rand bit [3:0] start_addr;
  rand bit [3:0] end_addr;
  
  constraint start_addr_c { start_addr == s_addr(end_addr); }
  
  function bit [3:0] s_addr(bit [3:0] e_addr);
    if(e_addr < 4) 
      s_addr = 0;
    else 
      s_addr = e_addr - 4;
  endfunction
  
endclass

module func_constr;
  initial begin
    packet pkt;
    pkt = new();
    repeat(3) begin
      pkt.randomize();
      $display("\tstart_addr = %0d end_addr =",pkt.start_addr,pkt.end_addr);
    end
  end
endmodule

Simulator Output

start_addr = 9 end_addr =13
start_addr = 2 end_addr = 6
start_addr = 0 end_addr = 1

Click to execute on   

❮ Previous Next ❯