Thursday, November 12, 2015

Differance Between this and local

I am explaining here difference between this and local keywords and how they are used.

this - this keyword is handle of object which refers to the object which is calling the subroutine in which this is used.

Complicated ???

class Demo ;
  integer x;
  function new (integer x);
    this.x = x;
  endfunction
endclass

x refers to the argument variable of function new.
this.x refers to the variable x of class for which new is called. (variable x of class Demo)

local:: refers to the variable of current scope. That scope can be subroutine of class itself. It is used with randomize_with constraint to resolve conflict between two same named variable.

randomize_with using this keyword:

class C;
rand  int unsigned  x =101;
endclass

class D;
  int x =5;
  function int F(C c, int x);
    F = c.randomize() with { x < this.x; };
  endfunction
endclass

module test();
  D d;
  C c;
  initial begin
    d=new();
    c = new();
    d.F(c,100);
    $display("@@@@ %0d",c.x);
  end
endmodule

Output : 
=======================================================

Solver failed when solving following set of constraints 


rand bit[31:0] x; // rand_mode = ON 

constraint WITH_CONSTRAINT    // (from this) (constraint_mode = ON) (testbench.sv:8)
{
   (x < x);
}

=======================================================

Reason : 
With "c.randomize() with { x < this.x; };", this refers to c, not d.

randomize_with using local keyword : 

class C;
rand  int unsigned  x =101;
endclass

class D;
  int x =5;
  function int F(C obj, int x);
    F = obj.randomize() with { x < local::x; };
  endfunction
endclass

module test();
  D d;
  C c;
  initial begin
    d=new();
    c = new();
    d.F(c,100);
    $display("@@@@ %0d",c.x);
  end
endmodule


Output : 
@@@@ 38

Reason : 
local::x refers to function argument x (which is 100 here). 

What if I want to refer to class property variable x (here 5), not function argument.

class C;
rand  int unsigned  x =101;
endclass

class D;
  int x =5;
  function int F(C obj, int x);
    F = obj.randomize() with { x < local::this.x; };
  endfunction
endclass

module test();
  D d;
  C c;
  initial begin
    d=new();
    c = new();
    d.F(c,100);
    $display("@@@@ %0d",c.x);
  end
endmodule

Output : 
@@@@ 3

Reason : 
local::this refers to the class D. Hence local::this.x refers to class D's variable x.

Run Here : 


Below will never work,

class Demo ;
integer x;
function new (integer x);
local::x = x;
endfunction
endclass

Error:

Error-[ILCCP] Illegal 'local::' prefix
testbench.sv, 4
'local::' is not allowed in context: 'not in randomize-with constraint'
'local::' is only allowed in inline constraints when an object is randomized

No comments:

Post a Comment