Vous êtes sur la page 1sur 59

CLASSES

SV for Verification (SystemVerilog LRM)


INTRODUCTION
• SV introduces an object-oriented class data abstraction

• SV provides features such as:


• Dynamic creation, deletion, assignment
• Access via object handles (a safe pointer-like meachanism)
• Inheritance and abstract type modelling
• Polymorphism
SYNTAX
class class_identifier extends class_type;
{class_items}
endclass
OVERVIEW
• A class is a type that includes data and subroutines(functions and
tasks) that operate on that data.

• Class data => Class properties


Class Members
• Subroutines => Methods

Defines the contents and capabilities of


object
OVERVIEW
Each packet is different, but as a class, packets have
Example: certain intrinsic properties that can be captured in a
An object Packet definition

Fields: Things that be done with a


packet:
 Command field
 An address  Initialize the packet
 A sequence number  Set the command
 A timestamp  Read the packet’s status
 A packet payload  Check the sequence number
OVERVIEW Coding convention: Capitalize first letter of class name

class Packet; // methods


// data or class properties task clean();
bit [3:0] command;
command = 0; address = 0; master_id = 5’bx;
bit [40:0] address;
endtask
bit [4:0] master_id;
integer time_requested;
integer time_issued; task issue_request(int delay);
integer status; // send request to bus
endtask
// initiailization
function new();
function integer current_status();
command = IDLE;
address = 41’b0; current_status = status;
master_id = 5’bx; endfunction
endfunction endclass
OBJECTS (CLASS INSTANCE)
Class => Defines a data type
Object = > An instance of that class

Packet p; // declare a variable of class Packet


p = new(); // initialize variable to a new allocated object of the class Packet

- Holds an object handle to an object of class Packet


- Uninitialized object handles set to default value null
OBJECTS (CLASS INSTANCE)
class obj_example;

endclass Uninitialized object

task task1(integer a, obj_example my_example);


if(my_example == null) my_example = new();
endtask
Accessing non-static members / virtual methods via a
null object handle is ILLEGAL !!
OBJECTS (CLASS INSTANCE)
Operation C pointer SV object handle SV chandle
Arithmetic operations (such as incrementing) √ X X
For arbitrary data types √ X X
Dereferencing when null ERROR X X
Casting √ Limited X
Assignment to an address of a data type √ X X
Unreferenced objects are garbage collected No Yes No
Default value Undefined null null
For classes (C++) √ X

Chandle : Data type for use with DPI


OBJECT PROPERTIES
Data fields of an object can be used by qualifying class property names
with an instance name.

Packet p = new;
p.command = INIT;
p.address = $random;
packet_time = p.time_requested;

Net types (supply0, supply1, tri, triand, trior, etc.) -> not compatible with
dynamically allocated data
CANNOT be declared as a class property!!!
OBJECT METHODS
Object methods can be used by qualifying class property names with
an instance name.

Packet p = new;
Status = p.current_status();
CONSTRUCTORS
• SV does not require complex memory allocation and deallocation as
in C++.

• Garbage collection is IMPLICIT and AUTOMATIC.

• SV provides a mechanism for initializing an instance at the time the


object is created.
Packet p = new;
CONSTRUCTORS
Packet p = new; class Packet;
integer command;
Creates an object of class Packet.
While creating the instance, new function is function new();
invoked(by system), in which any specialized
initialization can be done – CLASS command = IDLE;
CONSTRUCTOR. endfunction
endclass
Class properties that include an initializer in - No return type (LHS of assignment
their declaration are initialized before determines return type)
execution of user-defined class constructor. - Non-blocking

Thus, initializer values can be


overridden by class constructor.
CONSTRUCTORS
• Every class has a default (built-in) new method.

• Default constructor first calls its parent class constructor


super.new()and then proceed to initialize each member of the
current object to its default (or uninitialized value).
CONSTRUCTORS
• It is also possible to pass arguments to the constructor.
• Provides run-time customization of an object.

Packet p = new(STARTUP, $random, $time);

function new(int cmd=IDLE, bit[12:0] adrs=0, int cmd_time);


command = cmd;
address = adrs;
time_requested = cmd_time;
endfunction
STATIC CLASS PROPERTIES
• Sometimes only one version of a variable is required to be shared by all instances of a
class.

• These class properties are created using keyword static.

Example:
In case where all instances of a class need access to a common file descriptor:

class Packet;
static integer fileId = $fopen(“data”, “r”);

Now fileId will be created and initialized once. Thereafter, every Packet object access file
descriptor in the usual way.
Static class properties can be used without creating an object of that type
STATIC METHODS
• A static method can be called outside the class, even with no class
instantiation.

• A static method has no access to non-static member(class


properties/methods).

• A static method can directly access static class properties.

• A static method can call static methods of the same class.

• Static methods cannot be virtual.


STATIC METHODS
class id;
static int current = 0;
static function int next_id(); A static method can directly access static class properties.
next_id = ++current;
endfunction
endclass
STATIC METHODS
• A static method is different from a method with static lifetime.

class TwoTasks;
static task foo(); ……… endtask Static class method with automatic variable lifetime

task static bar(); ……… endtask Non-static class method with static variable lifetime
endclass

• By default, class methods have automatic lifetime for their arguments


and variables.
THIS
• this keyword is used to unambiguously refer to class properties / methods of the current
instance.

• A pre-defined object handle.

• this keyword shall ONLY be used with-in non-static class methods.

class Demo;
integer x;
x is a property of the class and an argument to function
function new(integer x); new
this.x = x;
endfunction
endclass
ASSIGNMENT, RENAMING & COPYING
Packet p1;
creates a variable p1, that can hold the handle of an object of class
Packet, but initial value of p1 is null.

The object does not exist, and p1 does not contain actual handle, until
an instance of type Packet is created using
p1 = new
ASSIGNMENT, RENAMING & COPYING
Packet p1;
Packet p2;
p1 = new; new executed only once. So, only one object has been created.
p2 = p1; Still there is only 1 object, which can be referred to with either the name p1 or p2

Packet p1;
Packet p2;
p1 = new;
p2 = new p1; Object p2 copies ALL class properties of object p1 -> SHALLOW COPY

Objects are not copied, only


their handles.
ASSIGNMENT, RENAMING & COPYING
class A;
integer j = 5;
endclass

class B;
integer i = 1;
A a = new;
endclass

function integer test;


B b1 = new; // Create an object of class B
B b2 = new b1; // Create an object that is a copy of b1
b2.i = 10; // i is changed in b2, but not in b1
b2.a.j = 50; // change a.j share by both b1 and b2
test = b1.i; // test is set to 1 (b1.i has not changed)
test = b1.a.j; // test is set to 50 (a.j has changed)
endfunction
ASSIGNMENT, RENAMING & COPYING
Packet p1 = new;
Packet p2 = new;
p2.copy(p1);

Custom method written to copy the object specified as its argument into its instance

DEEP COPY of p1
INHERITANCE & SUBCLASSES
Packet class can be extended so that the packets can be chained
together into a list.

class LinkedPacket;
Packet packet_c;
LinkedPacket next;

function LinkedPacket get_next();


get_next = next;
endfunction
endclass
INHERITANCE & SUBCLASSES
class LinkedPacket extends Packet;
LinkedPacket next;

function LinkedPacket get_next(); New subclass, inherits members of parent class


get_next = next; LinkedPacket.
endfunction
Now, all methods and class properties of
endclass Packet are part of LinkedPacket – as if they
were defined in LinkedPacket – and
LinkedPacket has additional class properties
and methods.

Parent’s methods can also be overridden.

SV support SINGLE-INHERITANCE, that is each class is derived from a single parent


class.
OVERRIDDEN MEMBERS
• Subclass objects are also legal representative objects of their parent
classes.

LinkedPacket lp = new;
Packet p = lp;

References to p access the methods and class properties of the Packet


class.
OVERRIDDEN MEMBERS
class Packet; LinkedPacket lp = new;
integer i = 1; Packet p = lp;
function integer get();
j = p.i; // j=1, not 2
get = i;
endfunction j = p.get(); // j=1, not -1 or -2
endclass

class LinkedPacket extends Packet;


i and get() are overridden in LinkedPacket.
integer i = 2;
But new and all overridden members are hidden
function integer get(); from p.
get = -i;
endfunction
endclass
SUPER
• super keyword is used from within a derived class to refer to
members of the parent class.

• It is necessary to use super to access members of a parent class when


those members are overridden by derived class.
SUPER
The member that can be accessed using
class Packet; super, can be a member declared a level
integer value; up/be inherited by the class one level up.
function integer delay();
delay = value * value;
endfunction
endclass

class LinkedPacket extends Packet;


integer value;
function integer delay();
delay = super.delay() + value + super.value;
endfunction
endclass
super.super.count is NOT ALLOWED
SUPER
• When using super within new, super.new shall be the first
statement executed in the constructor.

• This is because, superclass must be initialized before the current class.

• If user code doesn’t provide an initialization, the compiler shall insert


a call to super.new automatically.
CASTING
• Assign a subclass variable to a variable of a class higher in inheritance
tree is LEGAL.

• Directly assign a superclass variable to a variable of one of its subclass


is ILLEGAL.

• Assign superclass handle to a subclass variable is LEGAL, if superclass


handle refers to an object of the given subclass.
CASTING
• To check if the assignment is legal, dynamic cast function $cast() is
used.

• Syntax for $cast() is:

task $cast(singular dest_handle, singular source_handle);


OR
function int $cast(singular dest_handle, singular source_handle);

$cast() checks the hierarchy tree (super and subclasses) of source_expr to


see it it contains the class of dest_handle.
If it does, $cast() does the assignment. Otherwise, ERROR.
CHAINING CONSTRUCTORS
• When a subclass is instantiated, class method new() is invoked.

• The first action new() takes, before any code defined in the
function is evaluated is to invoke the new() method of its superclass,
and so on up the inheritance hierarchy.

• If the initialization method of the superclass requires arguments,


there are 2 choices:
 To always supply same arguments
 To use super keyword
CHAINING CONSTRUCTORS
class EtherPacket extends Packet(5);

This passes 5 to the new routine associated with Packet.

function new();
super.new(5);
endfunction

This uses super keyword to call superclass constructor.


DATA HIDING & ENCAPSULATION
• In SV, unqualified class properties and methods are PUBLIC, available
to anyone who has access to the object’s name.

• A member identified as local is available only to methods inside the


class.

• local members are visible within subclasses(or derived classes).

• Non-local methods that access local class properties/methods can be


inherited, and work properly as methods of that subclass.
DATA HIDING & ENCAPSULATION
• A protected class property/methods has all characteristics of a local
member, except that it can be inherited i.e. it is visible to subclasses.

• Within a class, a local member/class property of the class can be referenced,


even if it in a different instance.

class Packet;
local integer i;
function integer compare(Packet other);
compare = (this.i == other.i);
endfunction
endclass
other.i should not be visible inside this packet since it is local class property
being referenced from outside this instance. However, this is ALLOWED within the
same class.
CONSTANT CLASS PROPERTIES
• Class properties can be made read-only by a const declaration.

• Since class objects are dynamic objects, class properties allow 2 forms
of read-only variables:

Global constants
Instance constants
CONSTANT CLASS PROPERTIES
Global constant class properties Instance constant class properties
- Include an initial value as part of their - Do not include an initial value in their declaration,
declaration. only the const qualifier.
- Cannot be assigned a value anywhere other - Can be assigned a value at run-time, but the
than in the declaration. assignment can only be done once in the
corresponding class constructor.

class Jumbo_Packet; class Big_Packet;


const int size;
const int max_size=9*1024;
byte payload[];
byte payload[];
function new();
function new(int size);
size = $random%4096;
payload=new[size>max-size?max_size:size];
payload = new[size];
endfunction endfunction
endclass endclass

- Typically, global constants are also declared static, - Cannot be declared static since that would
since they are constant for all instances of the class. disallow all assignments in the constructor.
ABSTRACT CLASSES & VIRTUAL METHODS
• A set of classes can be created that can be viewed as all being derived from
a common base class.

• Example:
A common base class of type BasePacket sets out structure of
packets but is incomplete and would never be instantiated.

From this base class, though number of useful subclasses could be derived,
such as Ethernet packets, token-ring packets, GPSS packets, etc.

Each of these packets might look very similar, all needing the same set of
methods, but they could vary significantly in terms of their internal details.
ABSTRACT CLASSES & VIRTUAL METHODS
• A base class sets out the prototype for the subclasses.

• Since base class is not intended to be instantiated, it can be made


abstract by specifying the class to be virtual:

virtual class BasePacket;


ABSTRACT CLASSES & VIRTUAL METHODS
• Abstract classes can also have virtual methods.

• Virtual methods are polymorphic constructs.

• Virtual method overrides a method in all the base classes, whereas normal method only
overrides a method in that class and its descendants.

• There is only implementation of a virtual method per class hierarchy, and it is always the
one in the latest derived class.

• Virtual methods provide prototypes for sub-routines.

• When subclasses override the virtual methods, they MUST follow the prototype exactly.
ABSTRACT CLASSES & VIRTUAL METHODS
virtual class BasePacket;
virtual function integer send(bit[31:0] data);
endfunction - If an abstract class has any virtual
endclass methods, all of the methods MUST
be overridden ( and provided with a
method body) for the subclass to
class EtherPacket extends BasePacket;
be instantiated.
function integer send(bit[31:0] data);
// body of the function - If any virtual methods have no
endfunction implementation, the subclass needs
to be abstract.
endclass
Can be instantiated
ABSTRACT CLASSES & VIRTUAL METHODS
• An abstract class can contain methods for which there is only a
prototype and no implementation.

• An abstract class cannot be instantiated, it can only be derived.

• Methods of normal class can also be declared virtual.


• In this case, methods must have a body.
• If the method does have a body, then the class can be instantiated, as can its
subclasses.
POLYMORPHISM: DYNAMIC METHOD LOOKUP
• Allows the use of a variable in the superclass to hold subclass objects,
and to reference the methods of those subclasses directly from the
superclass variable

• Example:
Packet -> base class
BasePacket -> object of Packet. Defines all public methods
that are used by its subclasses(send, receive, print, etc.) as virtual.
POLYMORPHISM: DYNAMIC METHOD LOOKUP
Even though BasePacket is abstract, it can be used to declare a variable:
BasePacket packets[100];

Now instances of various packet objects can be created, and put into the array:

EtherPacket ep = new;
TokenPacket tp = new;
GPSSPacket gp= new;
packets[0] = ep;
packets[1] = tp;
packets[2] = gp;
POLYMORPHISM: DYNAMIC METHOD LOOKUP
Since methods are declared as virtual, appropriate subclass methods
can be accessed from superclass variable, even though compiler didn’t
know – at compile time – what was going to be loaded into it.

e.g. packets[1].send();
shall invoke send method associated with TokenPacket class.

At run-time, the system correctly binds the methods from the


appropriate class.
CLASS SCOPE RESOLUTION OPERATOR ::
• Used to specify an identifier defined within the scope of a class.

• Syntax:
class_identifier :: {class_identifier::} identifier

class names or package names

• :: allows access to static members from outside class, as well as


public/protected elements of a superclass from within the derived
class.
CLASS SCOPE RESOLUTION OPERATOR ::
class Base;
typedef enum {bin, oct, dec, hex} radix;
static task print (radix r, integer n); … endtask
endclass

Base b = new;
int bin = 123;
b.print(Base::bin, bin);
Base::print(Base::hex, 66);
CLASS SCOPE RESOLUTION OPERATOR ::
• In SV, class scope resolution operator applies to all static elements of
a class:
- static methods
- typedef
- enumerations
- structures
- unions
- nested class declarations
CLASS SCOPE RESOLUTION OPERATOR ::
class StringList; class StringTree;
class Node; class Node;
string name; string name;
Node link; Node left, right;
endclass endclass
endclass endclass

Nested class for a node in a


linked list

Nested class for a node in a


binary tree

StringList::Node is different from StringTree::Node


CLASS SCOPE RESOLUTION OPERATOR ::
• :: enables:
- Access to static public members from outside class hierarchy
- Access to public or protected class members of a superclass
from within the derived class
- Access to type declarations and enumerations named constants
declared inside the class from outside the class hierarchy or from
within derived class
OUT OF BLOCK DECLARATIONS
Out-of-block declaration must match the prototype
class Packet; declaration exactly, with addition of method name and
Packet next; scope operator ::
function Packet get_next();
get_next = next;
endfunction

extern protected virtual function int send(int value);


endclass
Keyword extern removed Out-of-body declaration

function int Packet::send(int value);


………
endfunction
PARAMETERIZED CLASSES
• Often useful to define a generic class whose objects can be
instantiated to have a different array size/data types.

• Avoids writing similar code for each size/type.

• Allows a single specification to be used for objects that are


fundamentally different, and not interchangeable.
PARAMETERIZED CLASSES
class vector #(int size=1);
bit [size-1:0] a;
endclass

vector #(10) vten; // object with vector of size 10


vector #(.size(2)) vtwo; // object with vector of size 2
typedef vector #(4) Vfour; // Class with vector of size 4
PARAMETERIZED CLASSES
class stack #(type T=int);
local T items[];
task push(T a); … endtask
task pop(ref T a); … endtask
endclass

stack is; //default: a stack of int’s


stack #(bit[1:10]) bs; //a stack of 10-bit vector
stack #(real) rs; //a stack of real numbers

Any type can supplied as parameter, including a user-defined type such as class or struct.
TYPEDEF CLASS
CLASS & STRUCTURES
MEMORY MANAGEMENT

Vous aimerez peut-être aussi