Tuesday, November 19, 2013

Second level constraints

Ok let me start with this open-secret i usually forget while doing randomization:

Writing the constraints won't apply them on the random variable, at some point in time ".randomize" must be called for the class instance

There was some confusion about randomization for a class instance declared inside another class, the scenarios was given as below.

class lower;
   rand int y;
endclass : lower

The random variable y will get random value if lower is randomized at some point in time (i.e., .randomize is called for its instance at some time) and it will get some random value as there are no constraints present in lower class.Now consider another class upper  where i have created a handle for lower class and added constraints for it, what should happen when i do "lower_inst.randomize()" in upper class will the constraints be applied? the answer is NO as the constraint is in upper class and it is never randomized, for this to happen you can add a line where u have "this.randomize()" which calls randomization for upper class and the constraint gets applied.

The upper class code looks like below:

class upper;

   rand lower x;
   constraint x_y { x.y == 5; }

   function new();
      x = new();
   endfunction : new

   function void randomize_x();
      this.randomize(x);                   // Randomize called for upper class (with the key word "this")
   endfunction : randomize_x

    function void randomize_xx();
      x.randomize();                       // Randomization called for lower class 
   endfunction : randomize_xx

endclass : upper

program automatic test();
   initial begin

      upper u = new();

      $display("u.x.y=%0d", u.x.y);
      u.randomize_x();
      $display("u.x.y=%0d", u.x.y);
      u.randomize_xx();
      $display("u.x.y=%0d", u.x.y);
      u.x.y = 10;
      $display("u.x.y=%0d", u.x.y);
      u.randomize();
      $display("u.x.y=%0d", u.x.y);

   end
endprogram

Output for the above test is:

u.x.y=0
u.x.y=5                      // output with u.randomize_x()  randomizing the upper class with constraints
u.x.y=-2118898666  // output with u.randomize_xx() randomizing the lower class no constraints
u.x.y=10                    
u.x.y=5                     // output with u.randomize()  randomizing the upper class with constraints





No comments:

Post a Comment