SystemVerilog Soft Constraints

 Soft Constraints 

A soft constraint is the constraint on random variable, and it will be true unless contradicted by another constraint.

For any random variable, there should not be any conflict between the constraint declared in parent class and child class or inline constraint,

for example, constraining a < 10 in parent class and
                     constraining a > 10 in child class or inline constraint.
conflicts in constraints leads to an randomization failure.

In some situations like,suppose in error test-case need to have inline constraint that conflicts the constraint defined inside the class, In this situation we have only option to change the constraint defined inside the class, but changing the constraint will reflect in all other test cases.
so this kind of problems can be avoided using soft constraints.

     constraint c_name { soft variable { condition }; }

 Example-1: 


In the example below,
In the class packet,addr variable is constrained to greater than 6 and the same addr variable is constrained to less than 6 in the inline constraint.
that means expecting value of addr to be less than and greater than 6, this is never possible, this leads to an randomization failure.
this problem is resolved in next example using soft constraint.

class packet;
  rand bit [3:0] addr;
  constraint addr_range { addr > 6; } 
endclass

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

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

 Simulator Output  

Constraints inconsistency failure
Constraints are inconsistent and cannot be solved.
Please check the inconsistent constraints being printed above and rewrite
them.

addr = 0
Execute the above code on 



 Example-2: 


In the example below,
previous example problem is solved using soft constraints,
Constraint declared inside the class will get suppressed by inline constraint.

class packet;
  rand bit [3:0] addr;
  constraint addr_range { soft addr > 6; } 
endclass

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

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

 Simulator Output  

addr = 1
addr = 3
Execute the above code on