Inline Constraints Functions in Constraints

 Inline Constraints 

Inline constraints allows to add constraints along with randomize call statement. Constraints defined inside the class also considered along with the inline constraints.

 Example-1 : 


In the example below,
random variable addr is constrained using inline constraint.

class packet;
  rand bit [3:0] addr;
endclass

module inline_constr;
  initial begin
    packet pkt;
    pkt = new();

    repeat(2) begin
      pkt.randomize() with { addr == 8;};
      $display("\taddr = %0d",pkt.addr);
    end
  end
endmodule

 Simulator Output  

addr = 8
addr = 8
Execute the above code on 

 Example-2 : 


In the example below,
constraint declared inside the class also considered along with the inline constraint.

class packet;
  rand bit [3:0] addr;
  rand bit [3:0] data;

  constraint data_range { data > 0;
                          data < 10; }
endclass

module inline_constr;
  initial begin
    packet pkt;
    pkt = new();
    repeat(2) begin
      pkt.randomize() with { addr == 8;};
      $display("\taddr = %0d data = %0d",pkt.addr,pkt.data);
    end
  end
endmodule

 Simulator Output  
addr = 8 data = 2
addr = 8 data = 5
Execute the above code on 



 Functions in Constraints 


In some cases constraint can't be expressed in single line, function call can be used to constraint an random variable.

 Example-1 : 

Constraint in the below example can be written with if..else constraint also, this example is just to show the usage of functions in constraints.

class packet;
  rand bit [3:0] start_addr;
  rand bit [3:0] end_addr;

  constraint end_addr_c { end_addr == e_addr(start_addr); }

  function bit [3:0] e_addr(bit [3:0] s_addr);
    if(s_addr<0)
      e_addr = 0;
    else
        e_addr = s_addr * 2;
  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 = 2
start_addr = 14 end_addr =12
start_addr = 12 end_addr = 8
Execute the above code on