Monday, March 14, 2016

be careful about passing objects to functions

Generally from uvm_monitor, we form the transactions and write them to one or more scoreboards. For example, if a monitor is writing an object to 2 scoreboards (or any uvm_components),  both the scoreboards will point to the same objects(even though we don't pass it as 'ref' arguments). If you anyone of the scoreboards change the object, other scoreboard will see that change. This is one of the common mistake people do in uvm benches. That's why it is always to recommend to clone the object before consuming that object in that component.

Here is an simple example to illustrate how it works:-

class C;
  int a;
endclass

program test;
  function F(C c2);
    //c2 = new();
    c2.a = 20;
  endfunction

  initial begin
   C c1;
   c1 = new();
   F(c1);
   $display("c1.a = %0d", c1.a);
  end

endprogram

Result:-
c1.a = 20

Please note here we didn't pass the object as ref but still it acts as if it is ref argument.
Then, what is the meaning of ref argument for the class objects?
Let me slightly change the code and see what happens.

program test;
  function F(C c2);
    c2 = new();
    c2.a = 20;
  endfunction

  initial begin
   C c1;
   //c1 = new();
   F(c1);
   $display("c1.a = %0d", c1.a);
  end

endprogram

Result:-
Null object error

In earlier case, c1 & c2 are 2 different object handles pointing to same object memory and hence any change in function is visible outside. Whereas in latter case, c1 points to null and c2 points to valid object memory. Hence we get null object error for c1.a.

if we use ref, it will behave differently.
program test;
  function F(ref C c2);
    c2 = new();
    c2.a = 20;
  endfunction

  initial begin
   C c1;
   //c1 = new();
   F(c1);
   $display("c1.a = %0d", c1.a);
  end

endprogram

Result:-
c1.a = 20

Now c1, c2 are same and hence any object allocation to c2 is same as to c1 itself. Most of the times, we play around with transaction objects and we might face potential issues if we miss this understanding.


No comments:

Post a Comment