Sunteți pe pagina 1din 544

System Verilog

INTRODUCTION, DATA
TYPES
What is SV?

 System Verilog is a hardware description and


Verification language (HDVL).

 The bulk of the verification functionality is based on the


OpenVera language.

 System Verilog (IEEE Standard 1800-2005) is an


extensive set of enhancements to IEEE 1364 Verilog-
2001 standards.

 It inherits features from Verilog, VHDL, C and C++.


Futurewiz
www.futurewiz.co.in
Features of SV

Constrained
Randomization

OOPS Improved
Data Types

System Verilog

Functional
Synchronization
Coverage
Assertions

Futurewiz
www.futurewiz.co.in
Regions in SV

Preponed Continuous, Blocking and RHS of


Active
Non Blocking Assignment. $display,
Sample Data $write.
before entering Inactive Execute statements with #0 delay
current time
slot (#1step) NBA Non Blocking Assignments

From Current Time Observed Assertions are evaluated


Slot
Pass/ Fail code of concurrent
To Next Time Re-Active assertions
Slot
Blocking Statement in Program
$strobe,
Re-Inactive #0 StatementsBlock
in Program Block
$monitor, PLI
Calls
Postponed Re-NBA NBA inside Program Block

Futurewiz
www.futurewiz.co.in
Data Type

 System Verilog offers following Data Types:

o 4-State Type o Structures


o 2-State Type o Unions
o Real o Strings
o Arrays o Enumerated Type
o User Define o Class

Futurewiz
www.futurewiz.co.in
4-State Type

 Allowed values are 0, 1, X and Z.

 Following 4-State types are included from Verilog:


o wire //Size: 1-bit Value: Z
o reg //Size: 1-bit Value: X
o integer // Size: 32-bit Value: X
o time // Size: 64-bit Value: X

 User can define size for wire and reg.

 integer is signed, all others are unsigned.

Futurewiz
www.futurewiz.co.in
4-State Type

 Addition to System Verilog


o logic //Size: 1-bit Value: X

 User can define size for logic.

 Logic is improved reg data type.

 Logic can be driven by continuous as well as


procedural assignments.

 Logic has a limitation that it cannot be driven by


multiple drivers in such case use wire.
Futurewiz
www.futurewiz.co.in
Logic

Example1:
module and_gate ( input logic a, b,
output logic c);
assign c= a & b; //driving logic using continuous
assignment
endmodule
Example2:
module flip_flop ( input logic din, clk,
output logic dout);
always @ (posedge clk)
dout<=din; //driving logic using procedural
assignment
endmodule Futurewiz
www.futurewiz.co.in
Logic

Example3:
module example3 ( input logic a, b,
output logic c);

assign c= a & b; //driving logic using continuous


assignment

always @ *
c= a | b; //driving logic using procedural
assignment
This code will give compilation error because of multiple
endmodule
driver.
Futurewiz
www.futurewiz.co.in
Logic

Example4:

module example4 ( input logic a, b, ctrl,


output logic c);
assign c= ctrl?a:1’bZ; //driving logic using continuous
assignment

assign c= !ctrl?b:1’bZ; //driving logic using continuous


assignment
endmodule

Compilation error, use wire to achieve this functionality.


Futurewiz
www.futurewiz.co.in
2-State Type

 Allowed values are 0 and 1.

 System Verilog offers following 2-State Data Types :


o shortint //Size: 16-bit Value: 0
o int //Size: 32-bit Value: 0
o longint //Size: 64-bit Value: 0
o byte //Size: 8-bit Value: 0
o bit //Size: 1-bit Value: 0

 User can define size for bit.

 All are signed except bit which is unsigned.


Futurewiz
www.futurewiz.co.in
Example1

module example1;
int a;
int unsigned b; //unsigned integer
bit signed [7:0] c; //same as byte
initial
begin
a=-32’d127;
b=‘1; //SV offers un-sized literal to fill all
c=‘0; // locations with given number
end
endmodule
Futurewiz
www.futurewiz.co.in
Example2

module example2;
int a;
logic [31:0] b=‘Z; //b=32’hzzzz_zzzz
initial
begin
a=b; //a=32’h0000_0000
b=32’h123x_5678;
if($unknown(b)) $display(“b is unknown”);
else $display(“b is known”);
end
endmodule
Futurewiz
www.futurewiz.co.in
Real Type

 Included from Verilog


o real //Default Value : 0

 real is same as double in C.

 Addition to System Verilog


o shortreal //Default Value : 0
o realtime //Default Value : 0

 shortreal is same as float in C.

 realtime and real can be used interchangeably.


Futurewiz
www.futurewiz.co.in
Void

 void data type represents non existing data.

 It can be used as return type of functions to indicate


nothing is returned.

Example: Usage:

function void display; display();


$display(“Hello”);
endfunction

Futurewiz
www.futurewiz.co.in
Arrays

 Arrays are used to group elements of same type.

 Arrays can be categorized as following:


o Fixed Array
o Dynamic Array
o Packed Array
o Unpacked Array
o Queues
o Associative Array

Futurewiz
www.futurewiz.co.in
Fixed Array

 Array whose size is fixed during compilation time is


called as Fixed Array.

 Size of fixed array cannot be modified during run time.

Examples

int array1 [15]; //array of int containing 15


elements
//Equivalent to int array1 [0:14]
int array2 [0:14];
logic array3 [7:0]; //array of logic containing 8
elements Futurewiz
www.futurewiz.co.in
Unpacked Array

 Unpacked Arrays can be declared by adding size after


array name.

 Unpacked Arrays can be made of any data type.

Example:
int array1 [16] [8]; //16 rows , 8 columns
bit array2 [3:0] [7:0]; //4 rows , 8 columns
bit [7:0] array3 [4]; //4 rows each containing 8 bits

 System Verilog stores each element of an unpacked


array in a longword (32-bit).

Futurewiz
www.futurewiz.co.in
Unpacked Array

bit [7:0] array1 [4];

array1 [0] Unused 7 6 5 4 3 2 1 0


Memory
array1 [1] Unused 7 6 5 4 3 2 1 0
Memory
array1 [2] Unused 7 6 5 4 3 2 1 0
Memory
array1 [3] Unused 7 6 5 4 3 2 1 0
Memory

Futurewiz
www.futurewiz.co.in
Unpacked Array

Initializing Array:
int array1 [2] [4] = ‘{ ‘{ 1, 2, 3, 4 } , ‘{ 5, 6, 7, 8 } };
int array2 [2] [3] = ‘{ ‘{ 1, 3, 6 } , ‘{ 3 {2} };
// same as ‘{ 1, 3, 6 } , ‘{ 2, 2, 2 }

int array3 [0:5] = ‘{1:5, 3:1, default: 0};


// same as ‘{0, 5, 0, 1, 0, 0}

int array4 [0:2] [1:4] = ‘{3 { ‘{ 2 {1, 2} } } };


// same as ‘{ ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} }

int array5 [2] [2] [2] = ‘{ ‘{ ‘{4, 5}, ‘{3, 1} }, ‘{ ‘{1, 7}, ‘{2, 5} }
}; Futurewiz
www.futurewiz.co.in
Unpacked Array

Accessing Array
int array1 [2] [4];
int array2 [0:5];
byte array3 [0:2] [1:4];
int a, b;
byte c;

a= array1[1] [3];
b= array2[4];
c= array3[1] [2];

Futurewiz
www.futurewiz.co.in
Basic Array Operation

 Arrays can be manipulated using for and foreach loop

bit [7:0] array1[10], array2[10] ;

initial
begin
for ( int i=0; i <$size(array1); i++) //$size returns size of
array
array1[ i ]= 0;
foreach(array2[ k ]) //k is defined implicitly
array2[ k ]=$random;
end
Futurewiz
www.futurewiz.co.in
Basic Array Operation

Example:
bit [7:0] array1[10] [20];

initial
begin
array1=‘{10 { ‘{0:2, 1 : 0 , default:$random} } };

foreach(array1[i ,k])
$display(“array1[%0d] [%0d]=%0d”, i, k, array1[i] [k]);
end

Futurewiz
www.futurewiz.co.in
Packed Array

 Packed Arrays can be declared by adding size before


array name.

 One dimensional packed arrays are also referred as


vectors.

 Packed array is a mechanism of subdividing a vector


into subfields which can be accessed as array elements.

 Packed array represents contiguous set of bits.

 Packed array can be made of single bit data (logic, bit,


reg), enumerated type or other packed arrays.
Futurewiz
www.futurewiz.co.in
Packed Array

bit [3:0] [7:0] array1;

7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0

array1[3 array1[3:2] array1[1 array1[0][4]


] ]
array1 a=array1[3];
bit [7:0] a, b;
b=array1[1];
bit [15:0] c;
c=array1[3:2];
bit d;
d=array1[0][4];
bit [31:0] e;
e=array1;
Futurewiz
www.futurewiz.co.in
Packed Array

Mixture of Packed and Unpacked Array


bit [3:0] [7:0] b [4];

b[0] 76543210765432107654321076543210
b[0] [2] b[0] [1] [4:0]
b[1] 76543210765432107654321076543210
b[1]
b[2] 76543210765432107654321076543210
b[2] [2]
b[3] 7 6 5 4 3 2 1 0 7 6 5[2]
432107654321076543210

b[3] [0]
Futurewiz
www.futurewiz.co.in
Packed vs. Unpacked Array

 Packed arrays are handy if user wants to access array


with different combination.

 If user want to wait for change in array(i.e. @), in that


case packed array will be preferred over unpacked
array.

 Only fixed size arrays can be packed. Therefore it is not


possible to pack following arrays:
o Dynamic Arrays
o Queues
o Associative Arrays

Futurewiz
www.futurewiz.co.in
Operation on Arrays

int A [0:7] [15:0] , B [0:7] [15:0];


 Following operation are possible for both packed and
unpacked arrays.

 Both array A and B should be of same type and size.

A=B; //Copy Operation


A[0:3]= B[0:3]; //Slice and Copy
A[1+:4]= B[3+:4];
A[5]=B[5];
A==B //Comparison Operations
A[2:4]!=B[2:4];
Futurewiz
www.futurewiz.co.in
Operation on Arrays

bit [3:0] [7:0] A;

 Following operation are only allowed in packed arrays:

A=0;
A=A + 3;
A=A * 2;
A=‘1;
A=A & 32’d255;
A[3:1]=16’b1101_1110_0000_1010;

Futurewiz
www.futurewiz.co.in
Dynamic Array

 Dynamic arrays are unpacked arrays whose size can be set


and changed during simulation time.

 new constructor is used to set or change size of Dynamic


Array.

 size() method returns current size of array.

 delete() method is used to delete all elements of the array.

Futurewiz
www.futurewiz.co.in
Dynamic Array

int dyn1 [ ]; //Defining Dynamic Array (empty subscript)


int dyn2 [4] [ ];

initial
begin
dyn1=new[10]; //Allocate 10 elements
foreach (dyn1[ i ]) dyn1[ i ]=$random; // Initializing Array
dyn1=new[20] (dyn1); // Resizing array and
// Copying older values
dyn1=new[50]; // Resizing to 50 elements Old Values are lost
dyn1.delete; // Delete all elements
end

Futurewiz
www.futurewiz.co.in
Dynamic Array

int dyn1 [ ]= ‘{5, 6, 7, 8} ; //Alternative way to define size

initial
begin
repeat (2)
if (dyn1.size != 0)
begin
foreach(dyn1 [ i ] ) $display(“dyn1[%0d]=%0d”, i, dyn[ i ] );
dyn1.delete;
end
else
$display(“Array is empty”);
end

Futurewiz
www.futurewiz.co.in
Queue

 A Queue is a variable size, ordered collection of


homogenous elements.

 Queues support constant time access to all its


elements.

 User can Add and Remove elements from anywhere in


a queue.

 Queue is analogous to 1-D array that grows and shrinks


automatically.

 0 represents 1st element and $ represents last element.


Futurewiz
www.futurewiz.co.in
Queue

Declaration:
int q1 [ $ ]; // Unbounded Queue
int q2 [ $ : 100 ]; // Bounded Queue max size is
101
Operators:
q [ a : b ];
0 < a < b returns queue with b - a + 1 elements.
a = b = n returns q[n]
a > b returns empty queue
a or b is either x or z returns empty queue
a < 0 returns q [0: b]
b > $ returns q [a:$]
Futurewiz
www.futurewiz.co.in
Queue Methods

int A [$] = ‘{ 0, 1, 2, 3, 4, 5, 6 }; A 0 1 2 3 4 5 6
int x, y, z;

 size() method returns number of elements in a queue.


x=A.size(); x 7
 insert(index, item) method is used to insert item at a
given index.
A.insert(3, 7); A 0 1 2 7 3 4 5 6
 delete(index) method is used to delete a queue if index
is not specified else it is used to delete item at given
index.
A 0 1 2 7 3 5 6
A.delete(5); Futurewiz
www.futurewiz.co.in
Queue Methods

 pop_front() method removes and returns 1st element of the


queue.
y=A.pop_front();
y 0 A 1 2 7 3 5 6
 pop_back() method removes and returns last element of the
queue.
z=A.pop_back(); z 6 A 1 2 7 3 5

 push_front(item) method inserts item at the front of the


queue.
A 9 1 2 7 3 5
A.push_front(9);
 push_back(item) method inserts item at the back of the
queue.
A 9 1 2 7 3 5 8
A.push_back(8);
Futurewiz
www.futurewiz.co.in
Queue

int q [$] = ‘{ 5, 7, 9, 11, 2};

q = { q, 6 }; // q.push_back(6)
q = { 3, q }; // q.push_front(3)
q = q [1:$]; // void'(q.pop_front())
// or q.delete(0)
q = q[0:$-1]; // void'(q.pop_back())
// or q.delete(q.size-1)
q = { q[0:3], 9, q[4:$] }; // q.insert(4, 9)
q = {}; // q.delete()
q = q[2:$]; // a new queue lacking the first two items
q = q[1:$-1]; // a new queue lacking the first and last items

Futurewiz
www.futurewiz.co.in
Array Query Functions

 $left returns the left bound of the dimension.

 $right returns the right bound of the dimension.

 $increment returns 1 if $left is greater than or equal to


$right and –1 if $left is less than $right.

 $low returns the same value as $left if $increment returns


–1, and the same value as $right if $increment returns 1.

Futurewiz
www.futurewiz.co.in
Array Query Functions

 $high returns the same value as $right if $increment returns –


1, and the same value as $left if $increment returns 1.

 $size returns the number of elements in the dimension.

 $dimensions returns total number of dimensions in the array.

 $unpacked_dimensions returns total number of unpacked


dimensions for an array.

Futurewiz
www.futurewiz.co.in
Array Locator Methods

 Array locator methods works on unpacked arrays and returns queue.

 with clause is mandatory for the following locator methods:

 find() returns all the elements satisfying the given expression.

 find_index() returns the indices of all the elements satisfying the given
expression.

 find_first() returns the first element satisfying the given expression.

Futurewiz
www.futurewiz.co.in
Array Locator Methods

 find_first_index() returns the index of the first element


satisfying the given expression.

 find_last() returns the last element satisfying the given


expression.

 find_last_index() returns the index of the last element


satisfying the given expression.

Futurewiz
www.futurewiz.co.in
Array Locator Methods

 with clause is not mandatory for the following locator methods:

 min() returns the element with the minimum value or whose


expression evaluates to a minimum.

 max() returns the element with the maximum value or whose


expression evaluates to a maximum.

 unique() returns all elements with unique values or whose expression


evaluates to a unique value.

 unique_index() returns the indices of all elements with unique values


or whose expression evaluates.

Futurewiz
www.futurewiz.co.in
Array Locator Methods

int a [6] = ‘{9, 1, 8, 3, 4, 4};


int b [$], c [$] = ‘{1, 3, 5, 7};

b = c.min; // {1}
b = c.max; // {7}
b = a.unique; // {1, 3, 4, 8, 9}
b = a.find with (item > 3); // {9, 8, 4, 4}
b = a.find_index with (item > 3); // {0, 2, 4, 5}
b = a.find_first with (item > 3); // {9}
b = a.find_first_index with (item==8); // {2}
b = a.find_last with (item==4); // {4}
b = a.find_last_index with (item==4); // {5}
Futurewiz
www.futurewiz.co.in
Array Ordering Methods

 reverse() reverses the order of elements in an array.


 sort() sort array in ascending order with optional with clause.
 rsort() sort array in descending order with optional with
clause.
 shuffle() randomizes the order of elements in an array.

int A [7] = ‘{ 5, 3, 1, 9, 8, 2, 7}; A 5 3 1 9 8 2 7

A.reverse(); A 7 2 8 9 1 3 5

A.sort(); A 1 2 3 5 7 8 9

A.rsort(); A 9 8 7 5 3 2 1

Futurewiz
www.futurewiz.co.in
Array Reduction Methods

 sum() returns sum of all elements in an array or specific elements if


with clause is present.

 product() returns product of all elements in an array or specific


elements if with clause is present.

 and() returns bitwise and of all array elements or specific elements


if with clause is present.

 or() returns bitwise or of all array elements or specific elements if


with clause is present.

 xor() returns bitwise xor of all array elements or specific elements if


with clause is present.

Futurewiz
www.futurewiz.co.in
Associative Array

 In case size of data is not known or data space is sparse,


Associative array is a better option.

 System Verilog allocates memory for an associative element when


they are assigned.

 Index of associative can be of any type.

 If index is specified as * , then the array can be indexed by any


integral expression of arbitrary size.

 real and shortreal are illegal index type.

Futurewiz
www.futurewiz.co.in
Associative Array

int array1 [ * ];
int array2 [ int ];
//Array can be indexed by any integral expression.

int array3 [ string ];


//Indices can be strings or string literals of any length.

class xyz; …
int array4 [ xyz ];
//Indices can be objects of xyz.
Futurewiz
www.futurewiz.co.in
Associative Array

int xyz [ * ];

5 7 2 1 3 9
0 1 2 3 7 10
xyz[0]=5; //Memory allocated during assignment
xyz[1]=7;
xyz[2]=2;
xyz[3]=1;
xyz[7]=3;
xyz[10]=9;

Futurewiz
www.futurewiz.co.in
Associative Array Methods

 num() and size() method returns number of elements in associative


array.

 delete(index) deletes element at given index if index is specified


else deletes entire array.

 exists(index) checks whether an element exists at the specified


index.

 first(index) method assigns to the given index variable the value of


the first (smallest) index. first (smallest) index. It returns 0 if the
array is empty; otherwise, it returns 1.

Futurewiz
www.futurewiz.co.in
Associative Array Methods

 last(index) method assigns to the given index variable the value of


the last (largest) index in the associative array. It returns 0 if the
array is empty; otherwise, it returns 1.

 next(index) method finds the smallest index whose value is greater


than the given index argument. Returns 1 if new index is different
as old index else 0.

 prev(index) function finds the largest index whose value is smaller


than the given index argument. Returns 1 if new index is different
as old index else 0.

Futurewiz
www.futurewiz.co.in
Associative Array Methods

int a [string]= ‘{“Jan”: 1, “Feb”: 2, “Mar”: 3, “April”: 4, “May”:


5};
string index;

initial
begin
a.first(index); //index=Jan
$display(a[index]);
while(a.next(index)) //Go through all index
$display(a[index]);
end
Futurewiz
www.futurewiz.co.in
User Defined

 System Verilog allows user to define new data types


using typedef keyword.

typedef byte unsigned uint8; //Defining uint8


typedef bit [15:0] word; //Defining word

uint8 a, b;
word c, d;

a=8’d10;
c=16’d25;
Futurewiz
www.futurewiz.co.in
Structures

 Structure and Unions are used to group non-


homogenous data types.
 By default structure are unpacked.
 Unpacked structure can contain any data type.

Declaration :

struct { bit [7:0] opcode; struct {bit [7:0] r, g, b;} pixel;


bit [15:0] addr; } IR;

struct {int a, b; real b;} mix;

Futurewiz
www.futurewiz.co.in
Structures

Initializing : Accessing :

IR=‘{opcode : 7’d8, addr : 15’d1}; int x;


pixel=‘{ 128, 255, 100}; bit [7:0] y;
pixel=‘{ r :128, g : 255, b :100}; pixel.r=200;
pixel=‘{ int :0}; mix.a=3;
mix=‘{ 3, 5, 5.6}; mix.c=4.5;
mix=‘{ int : 1, real : 1.0}; x=mix.b;
mix=‘{ default : 0}; y=pixel.g;

Futurewiz
www.futurewiz.co.in
Packed Structures

 Packed Structure is made up of bit fields which are


packed together in memory without gaps.

 A packed structure can be used as a whole to perform


arithmetic and logical operations.

 First member of packed array occupies MSB and


subsequent members follow decreasing significance.

 Structures can be packed by writing packed keyword


which can be followed by signed or unsigned keyword.

Futurewiz
www.futurewiz.co.in
Packed Structures

Example :
typedef struct packed signed { shortint a; //16-bits [31:16]
byte b; //8-bits [15:8]
bit [7:0] c; //8-bits [7:0]
} exam_st;
exam_st pack1;
bit [7:0] a, b, c;
pack1=‘{a: ’1, b: -10, c: 8’b1001_0101};
a=pack1.b;
b=pack1.c;
c=pack1[9:2];
Futurewiz
www.futurewiz.co.in
Packed Structures

 Only packed data type and integer data types are allowed
inside packed structures

struct packed // default unsigned


{ bit [3:0] a;
bit [7:0] b;
bit [15:0] c [7:0] ; } pack2;

Compilation Error packed structure cannot have unpacked


element
Futurewiz
www.futurewiz.co.in
Packed vs Unpacked Structures

struct { bit [7:0] a; struct packed { bit [7:0] a;


bit [15:0] b; bit [15:0] b;
int c; int c;
} str1; } str2;

31:24 23:16 15:8 7:0


Unused a 55:48 47:32 31:0
Unused b a b c
c

Futurewiz
www.futurewiz.co.in
Unions

 Union represents a single piece of storage element that


can be accessed by any of its member.

 Only one data types in union can be used at a time.

Example :
union union packed
{ real a; { real a;
int b; int b;
bit [7:0] c; } exam1; bit [7:0] c; }
exam2;
Futurewiz
www.futurewiz.co.in
Unions

Example :
typedef union
{ shortint a;
00 00 00 00
int b;
bit [7:0] c; } my_un;
my_un un1; 00 00 F0 F0
un1.a=16’hf0f0;
$displayh(un1.b);
00 00 F0 AA
un1.c=8’b1010_1010;
$displayh(un1.b);
Futurewiz
www.futurewiz.co.in
Structures vs Unions

Structure Union

Memory is allocated to each Common memory is allocated


and every element. for all the members.

Size of structure is sum of size Size of union is equal to size of


of each member or more. largest member

First member is at offset 0. All member have 0 offset.

Modifying value of one member Modifying value of one member


has no effect on other members modifies value of all members

Futurewiz
www.futurewiz.co.in
String

 System Verilog string type is used to store variable


length strings.

 Each character of string is of type byte.

 There is no null character at the end of string.

 String uses dynamic memory allocation, so size of string


is no longer a concern.
Example :
string s=“hello”;

Futurewiz
www.futurewiz.co.in
String Operators

 str1 == str2 checks whether strings are equal or not.

 str1 != str2 checks for inequality of strings.

 Comparison using lexicographical ordering of strings.


o str1 < str2
o str1 <= str2
o str1 > str2
o str1 >= str2

 {str1, str2, str3, .. , strn} concatenation of strings.

Futurewiz
www.futurewiz.co.in
String Operators

Example :
string s1=“hello”, s2=“Hello”, s3=“xyz”;
initial
begin
if(s1 != s2)
$display(“strings are different”);
if(s1 > s3)
$display(“s1 is more than s3”);
else
$display(“s3 is more than s1”);
$display({s1, s2, s3});
end
Futurewiz
www.futurewiz.co.in
String Methods

 len() method returns length of a string.

 putc(position, character) method replaces character at


given position by character passed as an argument.

 getc(position) method returns ASCII value of character


at given position.

 toupper() method returns a string with all characters in


uppercase.

Futurewiz
www.futurewiz.co.in
String Methods

 tolower() method returns a string with all characters in


lowercase.

 compare(string) compares given string with string


passed as an argument.

 icompare(string) same as above but comparison is case


insensitive.

 substr(i, j) returns a string formed between characters at


position i and j.

Futurewiz
www.futurewiz.co.in
String Methods

 atoi() method returns integer corresponding to ASCII


decimal representation.

 The conversion scans all leading digits and underscore


characters ( _ ) and stops as soon as it encounters any
other character or the end of the string.

 itoa(i) stores the ASCII decimal representation of i in


string.
Example :
string s1=“12_3xyz”, s2; a=s1.atoi(); //a=123
int a, b=127; s2.itoa(b); //s2=“127”

Futurewiz
www.futurewiz.co.in
String Methods

Example :
string s1, s2;
initial begin
s1 = "SystemVerilog";
$display(s1.getc(0)); //Display: 83 (‘S’)
$display(s1.toupper()); // Display: SYSTEMVERILOG
s1 = {s1, "3.1b"}; // "SystemVerilog3.1b"
s1.putc(s1.len()-1, "a"); // change b-> a
$display(s1.substr(2, 5)); // Display: stem
s2=$psprintf("%s %0d", s1, 5);
$display(s2); // Display: SystemVerilog3.1a 5
end

Futurewiz
www.futurewiz.co.in
Enumerated Type

 An enumeration creates a strong variable type that is


limited to a set of specified names.
Example :
enum { RED, GREEN, BLUE } color;
typedef enum { FETCH, DECODE, EXECUTE } operation_e;
 enum are stored as int unless specified.
typedef enum bit [2:0] { RED, GREEN, BLUE } color_e;
 First member in enum gets value 0, second value 1 and
so on.
 User can give different values to member if required.

Futurewiz
www.futurewiz.co.in
Enumerated Type

Example :
enum { RED, GREEN, BLUE } color;
//RED=0, GREEN=1, BLUE=2

enum { GOLD, SILVER=3, BRONZE} medals;


//GOLD=0, SILVER=3, BRONZE=4

enum {A=1, B=3, C, D=4} alphabet;


//Compilation error C and D have same value

enum logic [1:0] {A=0; B=‘Z, C=1, D} exam;


//A=00, B=ZZ, C=01, D=10 Default value of exam is X

Futurewiz
www.futurewiz.co.in
Enumerated Type Methods

 first() method returns first member of enumeration.

 last() method returns last member of enumeration.

 next(N) method returns the Nth next member (default is


1) starting from current position.

 previous(N) method returns Nth previous member


(default is 1) starting from current position.

Futurewiz
www.futurewiz.co.in
Enumerated Type Methods

 Both next() and prev() wraps around to start and end of


enumeration respectively.

 num() method returns number of elements in given


enumeration.

 name() method returns the string representation of


given enumeration value.

Futurewiz
www.futurewiz.co.in
Enumerated Type Methods

Example

typedef enum { RED, BLUE, GREEN} color_e;


color_e mycolor;
mycolor = mycolor.first;
do
begin
$display("Color = %0d %0s", mycolor, mycolor.name);
mycolor = mycolor.next;
end
while (mycolor != mycolor.first); // Done at wrap-
around
Futurewiz
www.futurewiz.co.in
const

 const keyword is used to define constants in System


Verilog.

 localparam constants are set during elaboration time.

 const constants are set during simulation time.


Example:
const byte colon= “:”;
const real pi=3.14;

Futurewiz
www.futurewiz.co.in
Casting

 Casting is used convert data from one type to other.

 There are two ways to perform casting :


o Static Casting: destination = return_type’ (source). This
type of casting always succeeds at run time and does not
give any error.
o Dynamic Casting: using $cast system task or function.

Example :
int a;
initial a=int’(3.0 * 2.0);

Futurewiz
www.futurewiz.co.in
Casting

 System Verilog provides the $cast system task to assign


values to variables that might not ordinarily be valid
because of differing data type.

 $cast can be called as either a task or a function.


$cast used as a function
if ($cast(destination, source)) //destination and
source
// should be singular
$cast used as a task
$cast(destination, source);
Futurewiz
www.futurewiz.co.in
Casting

int a;
real b=3.0;

if($cast(a, b)) //Returns 1 if casting succeeds else 0


$display(“casting success”);

$cast(a, b); //If casting fails run time error occurs

In both cases if casting fails then destination value


remains unchanged.

Futurewiz
www.futurewiz.co.in
Casting

Example :
int a=-10;

initial
begin
$display(a>>>1); // -5
$display(unsigned’(a)>>>1); // positive value
const’(a); // changing to constant
a=3; //Runtime error
end

Futurewiz
www.futurewiz.co.in
Casting

typedef enum { red, green, blue, yellow, white, black }


Colors;
Colors col;
int a, b;

initial begin
col=green;
//col=3; Runtime error
a= blue * 2;
b= col + green;
end
Futurewiz
www.futurewiz.co.in
Casting

typedef enum { red, green, blue, yellow, white, black }


Colors;
Colors col;

initial begin
$cast( col, 2 + 3 ); //col=black

if ( ! $cast( col, 2 + 8 ) ) //10: invalid cast


$display( "Error in cast" );

col = Colors’(2 + 1); //col=yellow


col = Colors’(4 + 3); //value is empty
end Futurewiz
www.futurewiz.co.in
System Verilog
OPERATORS,
SUBPROGRAMS
Operators

 Included from Verilog


 Arithmetic + - * / % **
 Logical ! && ||
 Relational > < >= <=
 Equality == != === !==
 Bitwise ~ & | ^ ~^ ^~
 Reduction & ~& | ~| ^ ~^ ^~
 Shift >> << >>> <<<
 Concatenation { op1, op2, op3, .. , opn }
 Replication { no_of_times { a } }
 Conditional cond ? True_Stm : False_Stm
Futurewiz
www.futurewiz.co.in
Operators

 Additions to System Verilog


 Arithmetic += -= *= /= %=
 Increment/Decrement ++ --
 Logical -> <->
 Bitwise &= |= ^=
 Shift >>= <<= >>>= <<<=
 Wildcard Equality =?= !?=
 Set Membership inside
 Distribution dist
 Stream {<<{}} {>>{}}

Futurewiz
www.futurewiz.co.in
Example1

int a, b, c=2, d=6, e=10;


initial begin Result:
a=d++; a=6
b=++d; b= 8
c*=d; c= 8
c>>=1; d= 8
e%=3; e= 3
e+=2;
end

Futurewiz
www.futurewiz.co.in
Example2

Result:
int a, b, c, d; a=3 b=3 //Display
initial begin c=4
b=3; b= 4
if((a=b)) //brackets compulsory a=4
$display(“a=%d b=%d”, a, b);
(a=(b=(c=4))); if ((a=b)) is same as
end a=b;
if (a)

Futurewiz
www.futurewiz.co.in
Example3

a->b is same as !a || b
a<-> b is same as (!a || b) && (!b || a)
int a=1, b=2;
initial begin
Result:
if(a->b)
a implies b
$display(“a implies b”);
a is logically equivalent to b
if (a<-> b)
$display(“a is logically equivalent to
b”);
end

Futurewiz
www.futurewiz.co.in
Example4

int i=11, range=0; Result:


bit a=5’b10101; range=2
initial begin
if(i inside { [1:5], [10:15], 17,18}) // i is 1-5 or 10-15 or 17or 18
range+=1;
if(a=?=5’b1XZ01) //X and Z acts like don’t care
range+=1;
end

Futurewiz
www.futurewiz.co.in
Loops

 Included from Verilog


o for
o repeat
o while

 Additions to System Verilog


o foreach
o do while

Futurewiz
www.futurewiz.co.in
Loops

inital begin
int i=10;
inital begin
do begin
int a [8] [5];
i -=1; //statements
foreach ( a [i, j] )
end
a[i] [j]=$random;
while (i >5)
end
end
Used to access all Statements executed first an
elements in an then execution depends upon
array condition
Futurewiz
www.futurewiz.co.in
Break and Continue

inital begin inital begin


int i; int i;
repeat(10) repeat(10)
begin begin
if(i==7) break; if(i==7) continue;
i+=1; i+=1;
end end
end end
Result: i=7 Result: i=7

Futurewiz
www.futurewiz.co.in
package

 Packages provide ways to have common code to be


shared across multiple modules.
 A package can contain any of the following:
o Data Types
o Subprograms (Tasks/Functions)
o Sequence
o property

 Elements of a package can be accessed by:


o :: (Scope Resolution Operator)
o import keyword
Futurewiz
www.futurewiz.co.in
`include vs import

 `include is used to include the content of specified file to


the given location.

 It is equivalent to copying the content and pasting at the


given location.
`include “xyz.v”

 Import is used to access elements defined inside the


package without copying them to current location.
import :: element_name;
import :: *;

Futurewiz
www.futurewiz.co.in
Example

“file1.sv” `include “file1.sv”


function int add (input int a, b ); `include “file2.sv”
add= a + b; module test;
endfunction initial begin
int x=add(1, 2, 3);
“file2.sv” int y=add(3, 4);
function int add (input int a, b, c end
); endmodule
add= a + b + c;
Compilation error add already
endfunction exists
Futurewiz
www.futurewiz.co.in
Example

“pack1.sv” “pack2.sv”
package mypack1; package mypack2;
int x; int y;
function int add (input int a, b ); function int add (input int a, b, c
add= a + b; );
endfunction add= a + b + c;
endfunction
endpackage
endpackage

Futurewiz
www.futurewiz.co.in
Example

`include “pack1.sv”
`include “pack2.sv”
module test;
import mypack1::*;
import mypack2::*;
initial begin
x=mypack1 :: add(3, 6); //x=9
y=mypack2 :: add(4, 5, 3); //y=12
end
endmodule
Futurewiz
www.futurewiz.co.in
unique and priority

 Improperly coded case statements can frequently cause


unintended synthesis optimizations or unintended
latches.

 System Verilog unique and priority keywords are


designed to address improperly coded case and if
statements.

 unique and priority keywords can be placed before an if,


case, casez, casex statement.

Futurewiz
www.futurewiz.co.in
unique

 A unique keyword performs following checks:


o Each choice of statement is unique or mutually exclusive.
o All the possible choices are covered.

 A unique keyword causes simulator to perform run time


checks and report warning if any of the following conditions
are true:
o More than one case item matches the case expression.
o No case item matches the case expression, and there is
no default case

Futurewiz
www.futurewiz.co.in
unique

always @ * Result:
unique case (sel) Inputs Outputs
2’b00: y=a; 00 : y=a;
2’b01: y=b; 01 : y=b; warning
2’b01: y=c; issued
2’b10: y=d; x1 : Latch; warning
2’b11: y=e; issued
endcase 11 : y=e;

Futurewiz
www.futurewiz.co.in
unique

always @*
casez (ip)
4’b1??? : y=2’b11; Synthesis Result:
4’b?1?? : y=2’b10; Priority Encoder
4’b??1? : y=2’b01;
4’b???1 : y=2’b00;
default: y=2’b00;
endcase

Futurewiz
www.futurewiz.co.in
unique

always @*
unique casez (ip)
4’b1??? : y=2’b11; Synthesis Result:
4’b?1?? : y=2’b10; Encoder
4’b??1? : y=2’b01;
4’b???1 : y=2’b00;
default: y=2’b00;
endcase

Futurewiz
www.futurewiz.co.in
priority

 A priority instruct tools that choices should be evaluated


in order they occur.

 A priority case will cause simulation to report a warning if


all possible choices are not covered and there is no
default statement.

 A priority if will cause simulators to report a warning if all


of the if…if else conditions are false, and there is no
final else branch.

Futurewiz
www.futurewiz.co.in
priority

always @ *
priority case (sel) Result:
2’b00: y=a; Inputs Outputs
2’b01: y=b; 00 : y=a;
2’b01: y=c; 01 : y=b;
2’b10: y=d; x1 : Latch; warning
issued
2’b11: y=e;
11 : y=e;
endcase

Futurewiz
www.futurewiz.co.in
priority

Result:
always @ * Inputs Outputs
priority if (sel==2’b00) y=a; 00 : y=a;
else if (sel==2’b01) y=b; 01 : y=b;
else if (sel==2’b10) y=c; 10 : y=c;
else if (sel==2’b10) y=d; 11 : y=e;
else if (sel==2’b11) y=e; 1x : Latch; warning
issued
z1 : Latch; warning
issued
Futurewiz
www.futurewiz.co.in
Procedural Statements

 If there is label on begin/fork then you can put same label


on the matching end/join.
 User can also put label on other System Verilog end
statements such as endmodule, endfunction, endtask,
endpackage etc.
module test;
initial
for (int i=0; i<15; i++)
begin : loop
…………….
end : loop
endmodule : test
Futurewiz
www.futurewiz.co.in
Scope and Lifetime

 System Verilog adds the concept of global scope. Any


declaration and definitions which are declared outside
module, interface, subprograms etc has a global scope.

 These declaration and definitions can be accessed by


any scope that lies below the current scope including the
current scope.

 All global variables have static lifetime i.e. they exist till
end of simulation. Global members can be explicitly
referred by $root.

Futurewiz
www.futurewiz.co.in
Example

int i;
//task increment task
module test; increment;
//task decrement i+= 1;
initial begin : label endtask
i=5;
task decrement;
#6 $root.i=3;
$root.i-=1;
#3 increment;
endtask
#4 decrement;
end : label
endmodule : test
Futurewiz
www.futurewiz.co.in
Scope and Lifetime

 Local declarations and definitions are accessible at


scope where they are defined or scopes below it.

 By default all the variables are static in a local scope.

 These variables can be made automatic.

 Static variables can be accessed by hierarchal names.

Futurewiz
www.futurewiz.co.in
Scope and Lifetime

 automatic variables cannot be accessed by hierarchical name.

 automatic variables declared in an task, function, or block are


local in scope, default to the lifetime of the call or block, and
are initialized on each entry to the call or block.

 Static variables are initialized only once during the simulation


period at the time they are declared.

 Advantage of defining variables local to scope is that there is


no side effect i.e the variable is getting modified by operations
local to it.

Futurewiz
www.futurewiz.co.in
Example1

int i; //Global Declaration


module test;
int i; //Local to module
initial begin
int i; //Local to initial block
for (int i=0; i<5; i++) //Local to for loop
test.i=i; //Modifies i inside test
i=6; //Modifies i inside initial
end
endmodule : test
Futurewiz
www.futurewiz.co.in
Example2

int svar1 = 1; // static keyword


optional
initial begin
for (int i=0; i<3; i++) begin : l1
automatic int loop3 = 0; // executes every loop
for (int k=0; k<3; k++) begin : l2
loop3++;
$display(loop3);
end : l2 //loop3 destroyed here
end : l1
end Result: 1 2 3 1 2 3 1 2 3

Futurewiz
www.futurewiz.co.in
Example3

initial begin
for (int i=0; i<3; i++) begin : l1
static int loop3 = 0; // executes once
for (int k=0; k<3; k++) begin : l2
loop3++;
$display(loop3); //loop3 stays till end of
end : l2 //simulation
end : l1
end
Result: 1 2 3 4 5 6 7 8 9

Futurewiz
www.futurewiz.co.in
Type Parameter

 A parameter constant can also specify a data type.

 This allows modules, interfaces, or programs to have


ports and data objects whose type can be set for each
instance.
module test #( parameter p1=1, parameter type p2= logic)
( input p2 [p1:0] in, output p2 [p1:0] op);
p2 [p1:0] x;
endmodule

test u0 (15, bit); //Module instance example

Futurewiz
www.futurewiz.co.in
Subprograms

 Following advancement has been done to System


Verilog Subprograms (Functions and Task) :

o Default Port Direction : default port is input, unless


specified. Following types of ports are allowed:
o input : value captured during subprogram call.
o output: value assigned at end of subprogram.
o inout : value captured at start assigned at the end.
o ref : a reference of actual object is passed, the object
can be modified by subprogram and can also respond
to changes.
Futurewiz
www.futurewiz.co.in
Subprograms

 Following advancement has been done to System Verilog


Subprograms (Functions and Task) :

o Default Data Type : Unless declared, data types of ports is


logic type.
o Default Value : Input ports can have default values. If few
arguments are not passed, there default values are taken.
o begin..end : begin end is no longer required.
o Return : return keyword can be used to return value in case of
functions and to exit subprogram in case of tasks.
o Life Time : Variables can be defined as static or automatic.

Futurewiz
www.futurewiz.co.in
Function and Tasks

 Both Functions and Tasks can have zero or more


arguments of type input, output, inout or ref.

 Only Functions can return a value, tasks cannot return a


value.

 A void return type can be specified for a function that is


not suppose to return any value.

 Functions executes in zero simulation time, where as


tasks may execute in non zero simulation time.

Futurewiz
www.futurewiz.co.in
Example1

function int add (int a=0, b=0, c=0);


return a + b+ c;
endfunction

initial begin
int y;
y=add(3, 5); //3+5+0
#3 y=add(); //0+0+0
#3 y=add(1, 2, 3); //1+2+3
#3 y=add(, 2, 1); //0+2+1
end

Futurewiz
www.futurewiz.co.in
Example2

function void display (int a=0, b=0); //void function


$display(“a is %0d b=%0d”, a, b);
endfunction

initial begin
display(3, 5); //a=3 b=5
#3 display(); // a=0 b=0
#3 display(1); // a=1 b=0
#3 display( , 3); // a=0 b=3
end

Futurewiz
www.futurewiz.co.in
Example3

function int initialize(ref int a [7:0]);


foreach( a[ i ] )
a[ i ]=$random;
return 1;
endfunction

int b[7:0], status;


initial begin
status=initialize(b); //same as pointer concept in c
#3 void’(initialize(b)); // ignore return value
end

Futurewiz
www.futurewiz.co.in
Example4

//If argument is const then subprogram cannot modify it


function void copy(const ref int a [7:0], ref b [7:0]);
foreach( a[ i ] )
b[ i ]=a[ i ];
endfunction

int a[7:0], b [7:0];


initial begin
foreach (a [i] ) a [ i ]=$random;
copy(a, b);
end

Futurewiz
www.futurewiz.co.in
Example5

task check (int a, output b);


if (!a) begin
b=1;
$display(“error”);
return; end
b=0;
endtask

initial begin
#3 check(5, error); // error=0
#3 check(0, error); // error=1
end
Futurewiz
www.futurewiz.co.in
Example6

task add (int a=0, b=0, output int z); //Variables are static by
//default
#2 z=a + b;
endtask

int x, y; Result
:
initial fork x=6
add(3, 5, x); y=6
#1 add(2, 4, y);
join

Futurewiz
www.futurewiz.co.in
Example6

task add (int a=0, b=0, output int z); //Variables are static by
//default
#2 z=a + b;
endtask

int x, y; Result
:
initial begin x=8
add(3, 5, x); y=6
#1 add(2, 4, y);
end

Futurewiz
www.futurewiz.co.in
Example7

task automatic add (int a=0, b=0, output int z);


#2 z=a + b;
endtask

int x, y;
Result
initial fork :
add(3, 5 , x); x=8
#1 y=add(2, 4 , y); y=6
join

Futurewiz
www.futurewiz.co.in
System Verilog
CLASSES
Introduction

 System Verilog introduces an object-oriented class data


type.

 Classes allow objects to be dynamically created, deleted,


assigned, and accessed via object handles.

 A class is a type that includes data and subroutines


(functions and tasks) that operate on that data.

 class’s data is referred to as class properties, and its


subroutines are called methods.

Futurewiz
www.futurewiz.co.in
Example1

class rectangle;
int lenght, width; //class properties

function int area(); //class method


return lenght * width;
endfunction

function int perimeter(); //class method


return 2*(lenght + width);
endfunction
endclass

Futurewiz
www.futurewiz.co.in
Example2

class person;
string name, address; //class
properties
int number;

function void set_name(string user); //class


method
name=user;
endfunction
endclass
Futurewiz
www.futurewiz.co.in
Example3

class packet;
bit [7:0] data; //class property

tast randomize(); //class method


data=$random;
endtask

task display();
$display(“data is %d”, data);
endtask
endclass
Futurewiz
www.futurewiz.co.in
Objects

 A class defines a data type. An object is an instance of that


class.

 An object is created by defining a handler of class type and


then calling new function which allocates memory to the
object.

packet p; //p is handler to class packet


p=new(); //Object is constructed

 If objects are not created then handler points to null.

Futurewiz
www.futurewiz.co.in
Default Constructor

 new() is a default constructor which allocates memory and


initializes class variables for an object.

rectangle rec;

initial begin
rec=new; //memory allocated to length and width
int a, p;
rec.set_size(3, 5);
a=rec.area;
p=rec.perimeter; end
Futurewiz
www.futurewiz.co.in
Constructor

 User can define customized constructers by writing there


own new function inside a class.

 The new method is defined as a function with no return


type.

 It is also possible to pass arguments to the constructor,


which allows run-time customization of an object.

function new (int x=0, y=0);


length=x;
width=y;
endfunction Futurewiz
www.futurewiz.co.in
Example

rectangle r1, r2, r3;


class rectangle;
int a1, a3, p1;
int lenght, width;

function new(int initial begin


x=1,y=1);..... r1=new(3, 5);
function int area(); r2=new(4);
.............
a1=r1.area;
function int perimeter();
p1=r2.perimeter;
..........
Result: a1=15 p1=10 a3=r3.area; //error r3 is null
endclass end
Futurewiz
www.futurewiz.co.in
Parameterized Class

class packet #(number=10, type dtype= bit);


dtype data [number];

function void randomize();


foreach(data[i]) data[i]=$random;
endfunction

function void display();


foreach(data[i]) $display(“data[%0d”]=%0d”, i, data[i]);
endfunction
endclass
Futurewiz
www.futurewiz.co.in
Parameterized Class

packet p1; //number=10, dtype=bit


packet p2#(20); //number=20, dtype=bit
packet p3#( , int); //number=10, dtype=int
packet p4#(30, bit [3:0]); //number=30, dtype=bit [3:0]

initial begin
p1=new(); p2=new(); p3=new(); p4=new();
p4.display;
p4.randomize;
p4.display;
end
Futurewiz
www.futurewiz.co.in
This

 The this keyword is used to unambiguously refer to class


properties or methods of the current instance.

 The this keyword shall only be used within non-static


class methods, otherwise an error shall be issued.
class example;
Now a is property of class as well as
int a;
argument of function new.
function new(int a);
a=a; SV will look in local scope to resolve
endfunction reference to a, which in this case is
endclass subroutine argument.
Futurewiz
www.futurewiz.co.in
This

 To solve this issue this keyword is used which now refers


to property a in current class instance.

class example; example x, y;


int a; initial begin
function new(int a); x=new(5);
this.a=a; y=new(3);
endfunction $display(x.a);
endclass $display(y.a);
end

Futurewiz
www.futurewiz.co.in
Fundamental Principles of OOP

 Encapsulation
o It’s a concept that binds together the data and functions
that manipulate the data.
o Encapsulation keeps both data and function safe from
outside world i.e. data hiding.

 Abstraction
o Abstraction is the concept of moving the focus from the
details and concrete implementation of things, to the
types of things, the operations available thus making
the programming simpler, more general.

Futurewiz
www.futurewiz.co.in
Fundamental Principles of OOP

 Inheritance
o New classes are created by inheriting properties and
method defined in an existing class.
o Existing class is called the base class(parent class),
and the new class is referred to as
the derived class(child class).

 Polymorphism
o polymorphism means having many forms.
o A member function will cause a different function to be
executed depending on the type of object that invokes
the function. Futurewiz
www.futurewiz.co.in
Inheritance

 Inheritance allows user to create classes which are


derived from other classes.

 The derived class (child class) inherits all the properties


and methods defined in base class (parent class).

 Additional properties and methods can be defined in child


class.

 properties and methods defined in base class can be


overridden by redefining them in child class. This
phenomenon is called as overriding.
Futurewiz
www.futurewiz.co.in
Example1

class parent; class child extends


int a, b; parent;
task display(); int c;
$display(“Parent task print();
Class”); $display(“Child Class”);
endtask endtask
endclass endclass

Futurewiz
www.futurewiz.co.in
Example1

parent p; parent p child c


child c; a=4 ; a=3 ;
initial begin b=0; b=0;
p=new; c=0;
c=new;
c.print;
Child Class
c.display;
Parent
c.a=3; Class
p.a=4;
end
Futurewiz
www.futurewiz.co.in
Example2

class parent; class child extends


int a, b; parent;
task display(); int a;
$display(“Parent task display();
Class”); $display(“Child Class”);
endtask endtask
endclass endclass

Display method and property a is overridden in child


class
Futurewiz
www.futurewiz.co.in
Example2

parent p;
parent p child c
child c;
a=2 ; a=7 ;
initial begin b=0; b=0;
p=new; c=0;
c=new;
c.display;
p.display; Child Class
Parent
c.a=7;
Class
p.a=2;
end

Futurewiz
www.futurewiz.co.in
Example3

 A super keyword can be used to access properties and


methods defined in parent class from a child class.

class parent; class child extends


int a; parent;
task display(); int a, b;
$display(“Parent task display();
Class”); $display(“Child Class”);
endtask super.display;
endclass $display(super.a);
endtask
endclass Futurewiz
www.futurewiz.co.in
Example3

parent p;
parent p child c
child c;
a=5 ; a=6 ;
initial begin b=0;
p=new;
c=new;
p.a=5; Parent
Class
c.a=6;
Child Class
p.display; Parent
c.display; Class
end 0

Futurewiz
www.futurewiz.co.in
Inheritance

 Every time when child object is created, constructer of


parent (super.new) is called first implicitly.

 If a new function has been defined in parent which


accepts a set of arguments and arguments don’t have
default values. In such a case super.new has to be
explicitly specified with required arguments.

 It is because of this reason that child class is able to


access properties and methods defined in parent class.

Futurewiz
www.futurewiz.co.in
Example4

class parent; class child extends


function new(); parent;
$display(“Parent function new();
Class”); $display(“Child Class”);
endfunction endfunction
endclass endclass
initial begin
Parent
child c;
Class
c=new; Child Class
end

Futurewiz
www.futurewiz.co.in
Example5

class parent; class child extends


function new(string parent;
str); function new();
$display(str); $display(“Child Class”);
endfunction endfunction
endclass endclass
initial begin
child c;
Error super.new is not
c=new;
called
end

Futurewiz
www.futurewiz.co.in
Example6

class parent; class child extends


function new(string str=“ parent;
”); function new();
$display(str); $display(“Child Class”);
endfunction endfunction
endclass endclass
initial begin
child c; Child Class
c=new;
end No error, parent constructor has default
value
Futurewiz
www.futurewiz.co.in
Example7

class parent; class child extends


function new(string parent;
str); function new();
$display(str); super.new(“Parent
endfunction Class”);
endclass $display(“Child Class”);
initial begin endfunction
child c; endclass
Parent
c=new; Class
end Child Class

Futurewiz
www.futurewiz.co.in
Example8

class rectangle; class square extends


int length, width; rectangle;
int size;
function new(int x, y); function new(int size);
this.length=x; this.size=size;
this.width=y; super.new(size, size);
endfunction endfunction
function int area(int x, y);.... endclass
function int perimeter(int x, square sq=
y);... new(5);
sq.area;
endclass sq.perimeter;
Futurewiz
www.futurewiz.co.in
Encapsulation

 Till now classes have members which were accessible to


rest of the program. However in many situation such
functionality are not desired.

 Example: In cars we are not concerned by how engine


works but we our focus is how to control it.

 System Verilog provides various ways of hiding class


members:
o local keyword will ensure that the members are
available only to the method of the same class.
o protected keyword is similar to local keyword but
members can also be accessed by child class.Futurewiz
www.futurewiz.co.in
Example1

class rectangle; rectangle rec;


int length, width;
initial begin
function new(int x, y); rec=new(2, 3);
this.length=x; rec.area;
this.width=y; rec.length=5; //length is
endfunction modified
rec.area;
function int area; ….

endclass end

Futurewiz
www.futurewiz.co.in
Example2

class rectangle; rectangle rec;


local int length, width;
initial begin
function new(int x, y); rec=new(2, 3);
this.length=x; rec.area;
this.width=y; rec.length=5; //error
endfunction rec.area;

function int area; ….


end
endclass

Futurewiz
www.futurewiz.co.in
Example3

class rectangle; class square extends rectangle;


local int length, width; function new (int x);
function new(int x, y); super.new(x, x);
this.length=x; endfunction
this.width=y; endclass
endfunction
square sq;
function int area; …. initial sq=new(3);
endclass Error length and width are local to class
rectangle
Futurewiz
www.futurewiz.co.in
Example4

class rectangle; class square extends rectangle;


protected int length, width; function new (int x);
super.new(x, x);
function new(int x, y);
endfunction
this.length=x;
endclass
this.width=y;
endfunction square sq;
initial sq=new(3);
function int area; ….

endclass
Now length and width are accessible to both rectangle and
square Futurewiz
www.futurewiz.co.in
Lifetime in Class

 By default properties and methods defined inside a class


have automatic lifetime.

 Memory to properties are allocated dynamically when a


new instance of the class is created.

 User can define properties and methods as static. A static


property is a class variable that is associated with the
class, rather than an instance of the class.

Futurewiz
www.futurewiz.co.in
Lifetime in Class

 Memory to static properties and methods are allocated


during elaboration time.

 Scope resolution operator ( :: ) can be used to access


static property and methods defined inside a class.

 Static properties and methods can be accessed without


creating any instance of a class.

Futurewiz
www.futurewiz.co.in
Example1

packet p1, p2, p3;


class packet;
static int id; initial begin
int val; //default: automatic p1=new; $display(p1.id, p1.val);
p2=new; $display(p2.id, p2.val);
function new();
p3=new; $display(p3.id, p3.val);
id++;
p2.id=7; p2.val=3;
val++;
$display(p1.id, p1.val);
endfunction
$display(p2.id, p2.val);
endclass $display(packet :: id);
end
Futurewiz
www.futurewiz.co.in
Example1

Result :
p1.id= 1 p1.val=1
p2.id= 2 p2.val=1
p3.id= 3 p3.val=1
p1.id= 7 p1.val=1
p2.id= 7 p2.val=3
packet :: 7

Futurewiz
www.futurewiz.co.in
Example2

initial begin
class packet;
static int id; packet:: id=3;
$display(packet::id);
int val; //default: automatic
packet p1;
function new(); p1=new;
id=id+1; $display(packet::id);
val=val+1; end
endfunction
Result
endclass id=3; id=4;

Futurewiz
www.futurewiz.co.in
Functions and Tasks

 Task and Functions defined inside class have automatic


lifetime for their arguments and variables.

 A static keyword can be added after Task/Function to


make arguments and variables static in nature.

 A function prototype can be declared inside a class and


body can be defined outside class with help of extern
keyword.

Futurewiz
www.futurewiz.co.in
Example1

class test;
initial begin
task increment; test t1;
Result
int i; t1=new; :
i++; t1.increment; i=1
$display(“i=%d”, i); t1.increment; i=1
endtask t1.increment; i=1
end
endclass

Futurewiz
www.futurewiz.co.in
Example2

class test;
initial begin
task increment;
test t1;
static int x; Result:
t1=new;
int y; x=1 y=1
t1.increment;
x++; y++; x=2 y=1
t1.increment;
$display(“x=%d y=%d”, x, x=3 y=1
y); t1.increment;
endtask end

endclass
Futurewiz
www.futurewiz.co.in
Example3

class test;

task static increment; initial begin


int x; test t1; Result:
int y; t1=new; x=1 y=1
x++; y++; t1.increment; x=2 y=2
$display(“x=%d y=%d”, x, t1.increment; x=3 y=3
y); t1.increment;
endtask end

endclass
Futurewiz
www.futurewiz.co.in
Example4

class test;
initial begin
task static increment;
test t1; Result:
int x;
t1=new; x=1 y=1
automatic int y;
t1.increment; x=2 y=1
x++; y++;
t1.increment; x=3 y=1
$display(“x=%d y=%d”, x,
y); t1.increment;
endtask end

endclass
Futurewiz
www.futurewiz.co.in
Example5

function rectangle :: new(int


class rectangle; x, y);
local int length, width; this.length=x;
this.widht=y;
extern function new(int x, y);
endfunction
extern function int area();

endclass function int rectangle::area();


return length*width;
endfunction

Futurewiz
www.futurewiz.co.in
Functions and Tasks

 Functions and Tasks can be local as well as protected.

 Functions and Tasks can also be declared as static. The lifetime of


variables inside static methods are automatic by default.

 Memory to static methods are allocated during elaboration time.

 A static methods can only access static members of a class.

 A static method can be called without creating instance of a class.


They can be accessed by scope resolution operator(::).

Futurewiz
www.futurewiz.co.in
Example1

class test;
int i;
initial begin
local function void increment; test t1;
i++; $display(“i=%0d”, i); t1=new; Result
endtask t1.inc; :
t1.inc; i=1
function void inc;
//t1.increment; will give
increment; i=2
//compilation error
endfunction
end
endclass

Futurewiz
www.futurewiz.co.in
Example2

class test;
initial begin
static function int add(int x, $display(test::add(3,2));
y); $display(test::add(1,1));
int i; end
i++;
$display(“i=%0d”, i); Result:
return x + y; 5 i=1
endfunction 2 i=1
endclass
Futurewiz
www.futurewiz.co.in
Example3

class test;
initial begin
int i;
$display(test::add(3,2));
static function int add(int x, $display(test::add(1,1));
y); end
i++;
$display(“i=%0d”, i);
return x + y; Result :
endfunction Error, Static function cannot access
non-static class properties
endclass
Futurewiz
www.futurewiz.co.in
Example4

class test;
initial begin
static int i;
$display(test::add(3,2));
static function int add(int x, $display(test::add(1,1));
y); end
i++;
$display(“i=%0d”, i); Result:
return x + y; 5 i=1
endfunction 2 i=2
endclass
Futurewiz
www.futurewiz.co.in
Polymorphism

 Polymorphism is an ability to appear in many forms.

 In OOPS multiple routines sharing a common name is


termed as Polymorphism.

 In SV, Polymorphism allows a parent class handler to


hold sub class object and access the methods of those
child classes from the parent class handler.

 To achieve this, functions/tasks in SV are declared as


virtual functions/tasks which allow child
classes to override the behaviour of the function/task.
Futurewiz
www.futurewiz.co.in
Example1

class shape; //Main Class


protected x, y, z;
virtual function void display(); //Function call can be
$display(“I am shape”); // overridden, will call
endfunction //child function instead

virtual function void perimeter();


$display(“I don’t know perimeter”);
endfunction

endclass
Futurewiz
www.futurewiz.co.in
Example1

class rectangle extends shape;


virtual function void display();
$display(“I am rectangle”);
endfunction

virtual function void perimeter();


$display(“perimeter=%0d”, 2*(x + y));
endfunction
function new (int x, y); .....
endclass

Futurewiz
www.futurewiz.co.in
Example1

class square extends rectangle;


function void display(); //This function call
$display(“I am square”); //cannot be overridden
endfunction

function void perimeter();


$display(“perimeter=%0d”, 4*x);
endfunction
function new (int x); .....
endclass

Futurewiz
www.futurewiz.co.in
Example1

class triangle extends shape;


function void display();
$display(“I am a triangle”);
endfunction

function void perimeter();


$display(“perimeter=%0d”, (x + y + z));
endfunction
function new (int x, y, z); .....
endclass

Futurewiz
www.futurewiz.co.in
Example1

shape s1, s2;


s1.display; s1.perimeter;
rectangle r1,r2;
r1.display; r1.perimeter;
square sq1;
t1.display; t1.perimeter;
triangle t1;
s2=t1;
s2.display; s2. perimeter;
initial begin
r2=sq1;
s1=new;
r2.display; r2. perimeter;
r1=new(2, 3);
s2=r1;
sq1=new(4);
s2.display; s2. perimeter;
t1=new(1, 2, 3); end
Futurewiz
www.futurewiz.co.in
Example1

Result :
I am shape I don’t know
perimeter
I am rectangle Perimeter= 10
I am triangle Perimeter= 6
I am triangle Perimeter= 6
I am square Perimeter= 16
I am rectangle Perimeter= 10

Futurewiz
www.futurewiz.co.in
Example2

class parent; class child extends


int a=3; parent;
int b=8;
function void d1();
$display(“Parent d1”); function void d1();
endfunction $display(“Child d1”);
endfunction
virtual function void d2();
$display(“Parent d2”); function void d2();
endfunction $display(“Child d2”);
endclass endfunction
endclass Futurewiz
www.futurewiz.co.in
Example2

initial begin
parent p1; child c1;
c1=new;
$cast(p1, c1); // checks run-time casting errors
//p1=c1; //checks compile time casting errors
//properties and virtual methods in parent class
//points to one defined in child class
p1.d1; p1.d2;
$display(“p1.a=%0d”, p1.a); c1.a=9;
$display(“p1.a=%0d”, p1.a);
end
Futurewiz
www.futurewiz.co.in
Example2

parent p child c after p1=c1; child c


null a : inherited a : inherited
b : local; b : local;
d1 : inherited; parent p d1 : inherited;
d2 : inherited; d2 : inherited;
d1 : d1 :
Result : overridden; overridden;
Parent d1 d2 : d2 :
Child d2 overridden; overridden;
p1.a=5 parent points to child memory for
p1.a=9 inherited properties and virtual
methods
Futurewiz
www.futurewiz.co.in
Example3

class parent; class child extends


int a=3; parent;
int a=5; b=8;
function void d1();
$display(“Parent d1”); function void d1();
endfunction $display(“Child d1”);
endfunction
virtual function void d2();
$display(“Parent d2”); function void d2();
endfunction $display(“Child d2”);
endclass endfunction
endclass Futurewiz
www.futurewiz.co.in
Example3

initial begin
parent p1; child c1;
c1=new;
p1=c1; //Polymorphism occurs
//c1=p2; will give compilation error
p1.d1; p1.d2;
$display(“p1.a=%0d”, p1.a); c1.a=9;
$display(“p1.a=%0d”, p1.a);
end

Futurewiz
www.futurewiz.co.in
Example3

parent p child c after p1=c1; child c


null a : inherited a : inherited
a : overridden a : overridden
b : local; b : local;
d1 : inherited; parent p d1 : inherited;
d2 : inherited; d2 : inherited;
Result : d1 : d1 :
Parent overridden; overridden;
d1 d2 : d2 :
Child d2 overridden; overridden;
p1.a=3 Modifying parent’s a will not modify
p1.a=3 child’s a since it is overridden in
child. Futurewiz
www.futurewiz.co.in
Abstraction

 Sometimes, it is useful to create a class without intending


to create any objects of the class.

 The class exists simply as a base class from which other


classes can be derived.

 In System Verilog this is called an abstract class and is


declared by using the word virtual.

 A virtual class object can not be constructed but handle to


the virtual class can be defined.
Futurewiz
www.futurewiz.co.in
Abstraction

 Virtual methods can be declared without any body.

 These methods can be overridden in a derived class.

 The method overriding virtual method should have same


signature i.e. (return type, number and type of arguments)
must be the same as that of the virtual method.

 If a virtual method is defined as pure then these methods


must be defined in child classes. A pure virtual method
forces child classes to implement standard set of
methods.
Futurewiz
www.futurewiz.co.in
Example1

virtual class abstract; //Abstract Class

virtual task display(); //Virtual Method


//Body not defined

function int increment(int x);


return x + 1;
endfunction
endclass

Futurewiz
www.futurewiz.co.in
Example1

class abc extends abstract;

task display(); // display may or may not be


defined
$display(“abc”);
endtask

function int increment(int x); //Overriding


return x + 2;
endfunction

endclass Futurewiz
www.futurewiz.co.in
Example1

class xyz extends abstract;

task display(); // display may or may not be


defined
$display(“xyz”);
endtask

//Increment function may not be defined


endclass

Futurewiz
www.futurewiz.co.in
Example1

abstract ab; initial begin


abc a; //ab=new; not allowed
xyz x; //will give compilation error
a=new; x=new;
int p1, p2; a.display; x.display;
Results: p1=a.increment(2);
abc xyz p2=x.increment(5);
4 6 ab=x; ab.display;
xyz abc ab=a; ab.display;
end

Futurewiz
www.futurewiz.co.in
Example2

virtual class abstract; //Abstract Class

pure virtual task display();


//Pure Virtual Method

virtual function int increment(int x); //Virtual


Function
//Body may not be
defined

endclass
Futurewiz
www.futurewiz.co.in
Example2

class abc extends abstract;

task display(); //display method needs to be defined


$display(“abc”); //will give compilation error if not defined
endtask

function int increment(int x); //Increment function may


return x + 2; // or may not be defined
endfunction

endclass

Futurewiz
www.futurewiz.co.in
Nested Class

 A class can contain instance of another class using


handle to an object. Such classes are called as Nested
Classes.

 Common reasons for using containment are reuse and


controlling complexity.
class Node;
Node left, right;
//properties and methods for
Node
endclass
Futurewiz
www.futurewiz.co.in
Example

class timestat;
time start_time,
end_time;

function void start;


start_time=$time;
endfunction

function void end;


end_time=$time;
endfunction
endclass Futurewiz
www.futurewiz.co.in
Example

class packet;
int data[7:0];
task packet :: transmit();
timestat t;
t.start;
function new; //do some operation
t=new; t.end;
endfunction endtask

extern task transmit;

endclass

Futurewiz
www.futurewiz.co.in
Typedef Class

 A forward declaration is a declaration of a object which


the programmer has not yet given a complete definition.

 System Verilog language supports the typedef class


construct for forward referencing of a class declaration.

 This allows for the compiler to read a file from beginning


to end without concern for the positioning of the class
declaration.

Futurewiz
www.futurewiz.co.in
Example

module test;
class packet;
timestat t; Compilation error class
//definitions timestat is not defined.
endclass

class timestat; Timestat is referred


//definitions before it is defined
enclass
endmodule

Futurewiz
www.futurewiz.co.in
Example

module test;
typedef class timestat;
class packet;
timestat t; typedef allows compiler
//definitions to process packet class
endclass before timestat class.

class timestat;
//definitions
enclass
endmodule
Futurewiz
www.futurewiz.co.in
Copy

 User can make a copy of an object to keep a routine from


modifying the original.

 There are two ways of copying an object:


o Using built-in copy with new function (Shallow Copy)
o Writing your own complex copy function (Deep Copy)

 Using new to copy an object is easy and reliable. A new


object is constructed and all variables from the existing
object are copied.

Futurewiz
www.futurewiz.co.in
Shallow Copy

class pkt; pkt src, dst;


bit addr [15:0]; initial begin
bit [7:0] data; src=new; //create object
int status; dst=new src; //copy to dst
end
function new();
addr=$randomize;
data=$randomize; src dst
status=0; addr=5 ; addr=5 ;
endfunction data=10; data=10;
endclass status=0; status=0;

Futurewiz
www.futurewiz.co.in
Shallow Copy

 Shallow copy is similar to photocopy, blindly copying


values from source to destination.

 If a class contains handle to another class then only top


level objects are copied by new, not the lower one.

 When using new to copy objects, the user define new


constructer is not called. New function just copies the
value of variables and object handle.

Futurewiz
www.futurewiz.co.in
Example

class pkt;
bit addr [15:0];
class timestat;
bit [7:0] data;
time start_time, int id; static int count;
end_time;
timestat t;
endclass
function new();
id=count++;
t=new;
endfunction
endclass

Futurewiz
www.futurewiz.co.in
Example

packet src, dst;


initial begin
src=new;
src.t.start_time=10; src dst
id=1 ; id=1 ;
dst=new src;
//handle of t is copied
//id is not incremented

dst.t.start_time=14; t
//modifies t since start_time=14 ;
// handler is common
end

Futurewiz
www.futurewiz.co.in
Deep Copy

 User can write his own deep copy function.

 This user defined copy function should copy the content


of class handle, not handle itself.

Futurewiz
www.futurewiz.co.in
Example

class pkt;
bit addr [15:0];
bit [7:0] data;
int id; static int count; function pkt pkt :: copy;
copy=new;
timestat t; copy.addr=this.addr;
copy.data=this.data;
function new(); copy.t.start_time=this.t.start_ti
id=count++; me;
t=new; copy.t.end_time=this.t.end_tim
endfunction e;
extern function pkt copy; endfunction
endclass
Futurewiz
www.futurewiz.co.in
Example

initial begin src dst


pkt src, dst; id=1 ; id=2 ;
src=new;
src.t.start_time=3;
dst=src.copy;
dst.t.start_time=7; t t
end start_time=3 ; start_time=7 ;

Futurewiz
www.futurewiz.co.in
Interface Class

 A set of classes can be created that have a common set of


behaviors. This set is called Interface class.

 An interface class can only contain pure virtual functions, type


declaration and Parameter declarations.

 Pure functions are function that don’t have any implementation.

 implements keyword is used to define a class that implements


function defined in interface class.

 When interface class is implemented then nothing is extended,


implementation of pure virtual function is defined in class that
implements interface class.

Futurewiz
www.futurewiz.co.in
Interface Class

interface class shape #(type id=int);


int a;
pure virtual function id area(id x=0, y=0);
pure virtual function id perimeter(id x=0, y=0);
endclass

Futurewiz
www.futurewiz.co.in
Interface Class

class int_rectangle implements shape #(int);

virtual function int area(int x=0, y=0); //virtual keyword


return x*y; //compulsory
endfunction

virtual function int perimeter(int x=0, y=0);


return 2*(x+y);
endfunction
//a defined in interface class cannot be accessed
endclass
Futurewiz
www.futurewiz.co.in
Interface Class

class real_rectangle implements shape


#(real);

virtual function real area(real x=0, y=0);


return x*y;
endfunction

virtual function real perimeter(real x=0, y=0);


return 2*(x+y);
endfunction

endclass
Futurewiz
www.futurewiz.co.in
Singleton Class

 These are classes that restricts instantiation of class to


just one object.

class singleton; static function singleton create(int


int a; a);
static singleton obj; if (obj==null)
obj=new(a);
local function new (int a);
return obj;
this.a=a;
endfunction
endfunction
initial begin
//static function singleton s1;
s1=singleton::create();
endclass end
Futurewiz
www.futurewiz.co.in
Semaphore

 Semaphore is a built-in class which conceptually is a bucket.

 When semaphore is allocated, then a bucket containing fixed number


of keys is created.

 Process using semaphore must first procure a key from bucket before
they can continue to execute.

 Once process is over, key should be returned back to the bucket.

 Semaphore is basically used to control access to shared resources.

Futurewiz
www.futurewiz.co.in
Semaphore - Methods

 new() method is used to create semaphore with specified


number of keys. Default key count is 0.

 put() method is used to return specified number of keys to


semaphore. Default value is 1.

 get() method is used to procure specified number of keys


from semaphore. Default value is 1.

Futurewiz
www.futurewiz.co.in
Semaphore - Methods

 In get() method if the specified number of keys is not


available, the process blocks until the keys become
available.

 try_get() method is used to procure a specified number of


keys from a semaphore, but without blocking.

 In try_get() method if the specified number of keys are not


available, the method returns 0 else a positive value and
continues.
Futurewiz
www.futurewiz.co.in
Example

semaphore smp;
int got=0;
initial
initial begin begin
smp=new(5); #8 smp.get(2);
#5 smp.get(3); #7 smp.put(2);
#6 smp.get(1); got=got +1; end
#2 if(smp.try_get(3)) got=got +1; got=1 at 15
end

Futurewiz
www.futurewiz.co.in
Example

module test; begin : statement1


semaphore smp; smp.get;
int a=0; a=7;
smp=new(1); #3 smp.put;
end statement1
initial
fork begin : statement2
//statement1 smp.get;
//statement2 a=3;
join #2 smp.put;
end statement2
Futurewiz
www.futurewiz.co.in
Mailbox

 Mailbox is a built-in class that allows messages to be


exchanged between processes.

 Data can be sent to mailbox by one process and retrieved


by another.

 Mailbox can be bounded or unbounded queues.

 Mailbox can be parameterized or Non-parameterized.

 Non-Parameterized mailboxes are typeless , that is single


mailbox can send and receive different type of data.

Futurewiz
www.futurewiz.co.in
Mailbox - Methods

 new() method is used to create mailbox with size specified


as an argument.

 If size is defined as 0 (default) then mailbox is unbound.

 num() method is returns the number of message currently


present inside mailbox.

 put() method places a message in a mailbox in a FIFO


order.

 If the mailbox is bounded, the process shall be suspended


until there is enough room in the queue.
Futurewiz
www.futurewiz.co.in
Mailbox - Methods

 try_put() method attempts to place a message in mailbox.


This method is meaningful only for bounded mailboxes.

 If mailbox is full this method returns 0 and message is not


placed else it returns 1 and message is placed.

 get() method retrieves a message from a mailbox.

 This method removes message from a mailbox and calling


process is blocked if mailbox is empty.

 try_get() method attempts to retrieves a message from a


mailbox without blocking.
Futurewiz
www.futurewiz.co.in
Mailbox - Methods

 peek() method copies message from a mailbox without removing


message from the queue.

 If mailbox is empty then current process is blocked till a message is


placed in the mailbox.

 If the type of the message variable is not equivalent to the type of the
message in the mailbox, a run-time error is generated.

 try_peek() method attempts to copy a message from a mailbox without


blocking. If the mailbox is empty, then the method returns 0 else if
variable type is different it returns negative number else positive
number is returned.

Futurewiz
www.futurewiz.co.in
Parameterized Mailboxes

 By default mailboxes are typeless. They can send and


receive different data types. This may lead to runtime
errors.

 Mailbox type can be parameterized by passing type as a


argument.
mailbox #(string) mbox;

 In parameterized mailboxes, tools catches type mismatch


errors at compilation time.

Futurewiz
www.futurewiz.co.in
Example

module test;
mailbox mb; //typeless Mailbox

string s; int i;
initial begin
mb=new(); //Unbound Mailbox
$monitor(“s=%s and i=%0d at time=%0d”, s, i, $time);
fork gen_data;
rec_data;
join end
endmodule

Futurewiz
www.futurewiz.co.in
Example

task rec_data;
task gen_data;
#1 mb.peek(s);
mb.put(“Hello”);
#2 mb.get(s);
#3 mb.put(7);
#2 mb.get(i);
#4 mb.put(“Test”);
#1 mb.peek(s);
#3 mb.put(3);
#2 void’(mb.try_get(s));
#3 mb.put(“Hi”);
#1 void’(mb.try_get(i));
#2 mb.put(9);
#4 mb.get(s);
endtask
#2 mb.get(i);
endtask

Futurewiz
www.futurewiz.co.in
Example

Result:
# s= and i=0 at time=0
# s=Hello and i=0 at time=1
# s=Hello and i=7 at time=5
# s=Test and i=7 at time=7
# s=Test and i=3 at time=16

Futurewiz
www.futurewiz.co.in
Example

module test;
mailbox #(int) mb; //Parameterized Mailbox

int i;
initial begin
mb=new(3); //bound mailbox
$monitor(“i=%0d at %0d”, i ,$time);
fork gen_data;
rec_data;
join end
endmodule
Futurewiz
www.futurewiz.co.in
Example

task gen_data; task rec_data;


mb.put(1); #1 mb.peek(i);
#1 mb.put(7); #5 mb.get(i);
#1 mb.put(4); #2 mb.get(i);
#2 mb.put(3); #2 void’(mb.try_get(i));
#2 #1 mb.get(i);
void’(mb.try_put(2)); #2 void’(mb.try_get(i));
#10 mb.put(5); #2 void’(mb.try_peek(i));
#2 mb.put(6); #2 mb.get(i);
endtask endtask
Futurewiz
www.futurewiz.co.in
Example

Result:
# i=0 at time=0
# i=1 at time=1
# i=7 at time=8
# i=4 at time=10
# i=3 at time=11
# i=2 at time=13
# i=5 at time=18

Futurewiz
www.futurewiz.co.in
System Verilog
RANDOMIZATION
Why Randomize?

 As designs grow it becomes more difficult to verify their


functionally through directed test cases.

 Directed test cases checks specific features of a design


and can only detect anticipated bugs.

 Verifying your design using this approach is a time


consuming process.

 Randomization helps us detecting bugs that we do not


expect in our design.

Futurewiz
www.futurewiz.co.in
Comparison

Directed Random Constrained Random


o Verifies specific o Broader Coverage. o Broad and Deep
scenarios. o TB’s are easy to write. o Tests are more
o Time Consuming. o Tests are redundant. productive
o Linear progress. o Takes longer time to o Finds corner cases
achieve functionality. o Constrained to
achieve functionality

Futurewiz
www.futurewiz.co.in
What to Randomize?

 Device configuration
 Environment configuration
 Primary input data
 Encapsulated input data
 Protocol exceptions
 Errors and violations
 Delays
 Test order
 Seed for the random test

Futurewiz
www.futurewiz.co.in
Verilog Constrained Randomization

Futurewiz
www.futurewiz.co.in
Random in range

module test;
integer a, b, c;

initial
repeat(20) begin
a=$random % 10; //-9 to 9 (Random range)
b={$random} % 20; //0 to 19 (Random range)
c=$unsigned($random)%15; //0 to 14 (Random
range)
#2; end
endmodule
Futurewiz
www.futurewiz.co.in
Random in range

module test;
integer a, b, c;

initial
repeat(20) begin
a=10 + {$random} % 6; //10 to 15 (positive range)
b=-5 - {$random} % 6; //-5 to -10 (negative range)
c =-5 + {$random} % 16; //-5 to 10 (mix range)
#2; end
endmodule

Futurewiz
www.futurewiz.co.in
Algorithms

Positive Range:
result= min + {$random} % (max – min + 1);

Negative Range:
result= -min - {$random} % (max – min + 1);

Mix Range:
result= -min + {$random} % (max + min + 1);
//min is the magnitude of minimum number
//max is the magnitude of maximum number

Futurewiz
www.futurewiz.co.in
Random between ranges

module test;
integer a;

initial
repeat(20)
if ({$random} % 2)
#2 a=10 + {$random} % 6; //10 to 15
else
#2 a= 3 + {$random} % 5; // 3 to 7
endmodule

Futurewiz
www.futurewiz.co.in
Weighted Random numbers

module test;
integer a, count=0;

always if(count< 10) #2 count=count+1; else #2 count=0;

initial repeat(20)
if (count<3)
#2 a=1 + {$random} % 9; //1 to 9
else
#2 a=11 + {$random} % 8; // 11 to 18 Higher weight
endmodule
Futurewiz
www.futurewiz.co.in
Real random numbers

module test;
reg sign; reg [7:0] exp;
reg [22:0] mantisa; real a;

initial repeat(20) begin


sign=$random;
exp=$random;
mantisa=$random;
a=$bitstoshortreal({sign, exp, mantisa});
#2; end
endmodule
Futurewiz
www.futurewiz.co.in
Unique random numbers

while(index!=10) begin
Generate 10 unique
random numbers temp=$random;
begin: loop
integer rec [0:9]; for(i=0; i<index; i=i+1)
integer i, temp, num, index=0; if(rec[i]==temp)
disable loop;
initial begin rec[index]=temp;
$monitor(“num=%0d”, num); index=index + 1; num=temp;
#2; end
end end
Futurewiz
www.futurewiz.co.in
Result

# num=303379748
# num=-1064739199
# num=-2071669239
# num=-1309649309
# num=112818957
# num=1189058957
# num=-1295874971
# num=-1992863214
# num=15983361
# num=114806029

Futurewiz
www.futurewiz.co.in
Unique random numbers

while(index!=10) begin
Generate 10 unique
random numbers between temp={$random} % 100;
0 to 99 begin: loop
integer rec [0:9]; for(i=0; i<index; i=i+1)
integer i, temp, rand, index=0; if(rec[i]==temp)
disable loop;
rec[index]=temp;
index=index + 1; rand=temp;
#2; end
end
Futurewiz
www.futurewiz.co.in
Result

# num=48
# num=97
# num=57
# num=87
# num=57
# num=25
# num=82
# num=61
# num=29

Futurewiz
www.futurewiz.co.in
Other types

 Verilog also offers few more randomization system


functions apart from $random. They can be categorized as
following:

o$dist_uniform (seed, start, end)


o$dist_normal (seed, mean, standard_deviation)
o$dist_exponential (seed, mean)
o$dist_poisson (seed, mean)
o$dist_chi_square (seed, degree_of_freedom)
o$dist_t (seed, degree_of_freedom)
o$dist_erlang (seed, k_stage, mean)

Futurewiz
www.futurewiz.co.in
$dist_uniform

module test;
integer num1, num2, seed;

initial
repeat(20) begin
num1=$dist_uniform (seed, 5, 15); //5 to 15
num2=$dist_uniform (seed, -5, 10); //-5 to
10
#2; end
endmodule

Futurewiz
www.futurewiz.co.in
SV Constrained Randomization

Futurewiz
www.futurewiz.co.in
$urandom

module test;
integer num1, num2, seed;

initial
repeat(20) begin
#2 num1=$urandom (seed); //Unsigned 32-bit
//Random Number
num2=$urandom;
end
endmodule

Futurewiz
www.futurewiz.co.in
$urandom_range

module test;
integer num1, num2 , num3;

initial
repeat(20) begin
#2 num1=$urandom_range(35, 20); //35:max to 20:min
num2=$urandom_range(9); //9:max to 0:min
num3=$urandom_range(10,15); //10:min to 15:max
end
endmodule

Futurewiz
www.futurewiz.co.in
Result

# num1=27 num2=8 num3=10


# num1=32 num2=0 num3=11
# num1=26 num2=0 num3=14
# num1=29 num2=0 num3=13
# num1=21 num2=6 num3=12
# num1=25 num2=4 num3=10
# num1=20 num2=7 num3=12
# num1=23 num2=2 num3=12
# num1=33 num2=2 num3=13
# num1=22 num2=1 num3=11
# num1=34 num2=8 num3=14
# num1=24 num2=2 num3=15

Futurewiz
www.futurewiz.co.in
Randomize function

 SV provides scope randomize function which is used to


randomize variables present in current scope.

 randomize() function can accept any number of variables


which have to be randomized as an arguments.

 This function returns true if randomization was successful


else false.

 User can also provide inline constraints to control range of


random values.
Futurewiz
www.futurewiz.co.in
Randomize function

module test;
integer num1, num2;

initial
repeat(20) begin
if(randomize(num1, num2)) //Randomize num1 and
num2
$display(“Randomization Successful”);
else $display(“Randomization Failed”);
#2 ; end
endmodule
Futurewiz
www.futurewiz.co.in
Randomize function with constraint

module test;
integer num;

initial
repeat(20) begin
if(randomize(num) with {num>10; num<20;} )
$display(“Randomization Successful”);
//num should be between 10 and 20 Inline
Constraint
#2 ; end
endmodule
Futurewiz
www.futurewiz.co.in
Result

# num=19
# num=15
# num=11
# num=13
# num=15
# num=14
# num=16
# num=15
# num=17
# num=15
# num=11
# num=15
Futurewiz
www.futurewiz.co.in
Randomize Object Properties

 In SV properties (variables) inside a class can also be


randomized.

 Variables declared with rand and randc are only considered


for randomization.

 A class built-in randomize function is used to randomized


rand and randc variables.

 User can also specify constraint blocks to constrain random


value generation.
Futurewiz
www.futurewiz.co.in
rand vs randc

 Variables defined with rand keyword, distribute values uniformly.

rand bit [1:0] num1;


num1: 3, 2 , 0, 3, 0, 1, 2, 1, 3

 Variables defined with randc keyword, distribute values in a cyclic


fashion without any repetition within an iteration.

randc bit [1:0] num2;


num2: 3, 2, 0, 1
0, 2, 1, 3
1, 3, 0, 2

Futurewiz
www.futurewiz.co.in
Example1

program test; class sample;


sample sm; rand int num1;
initial begin
int num2;
sm=new;
repeat(20) endclass
assert(sm.randomize()) //assert checks randomization status
$display(“num1=%0d num2=%0d”, sm.num1, sm.num2);
end
endprogram

num1 is randomized num2 remains untouched

Futurewiz
www.futurewiz.co.in
Result

# num1=-1884196597 num2=0
# num1=-326718039 num2=0
# num1=1452745934 num2=0
# num1=-2130312236 num2=0
# num1=1572468983 num2=0
# num1=131041957 num2=0
# num1=1115460554 num2=0
# num1=-818992270 num2=0
# num1=2000525113 num2=0
# num1=1547354947 num2=0
# num1=1196942489 num2=0
# num1=736230661 num2=0
Futurewiz
www.futurewiz.co.in
Example2

class sample; program test;


rand bit[1:0] main m;
num; initial begin
endclass m=new;
class main;
repeat(20)
rand sample sm; //rand is must to
assert(m.randomize())
//randomize num
$display(m.sm.num);
function new;
end
sm=new;
endprogram
endfunction
endclass
Futurewiz
www.futurewiz.co.in
Example3

program test;
class sample; sample sm;
typedef struct { randc int a; initial begin
bit [3:0] b; sm=new;
} st_t; repeat(20)
rand st_t st; assert(sm.randomize()
//rand is must to randomize )
//int present inside structure $display(sm.st.a);
endclass end
endprogram

Futurewiz
www.futurewiz.co.in
Example4

class sample; program test;


rand bit[3:0] num; main m;
endclass initial begin
m=new;
repeat(20) begin
class main; assert(m.randomize()) ;
rand sample sm1; $display(m.sm1.num);
sample sm2; $display(m.sm2.num);
function new; end
sm1=new; sm2=new; end
endfunction endprogram
endclass

Futurewiz
www.futurewiz.co.in
Result

# 14 # 0
# 4 # 0
# 9 # 0
# 6 # 0
# 5 # 0
# 15 # 0
# 4 # 0
# 13 # 0
# 1 # 0
# 8 # 0
# 9 # 0
# 14 # 0
Futurewiz
www.futurewiz.co.in
Specifying Constraints

class sample1;
rand int num;
class sample3;
constraint c { num>10;
randc int num;
num<100; }
int Max, Min;
endclass
constraint c1 { num>Min; }
class sample2; constraint c2 { num<Max; }
randc bit [7:0] num; endclass
constraint c1 { num>10; }
constraint c2 { num<100; }
endclass

Futurewiz
www.futurewiz.co.in
Example1

class packet; repeat(10)


rand bit [7:0] data; assert(pkt.randomize())
$display(pkt.data);
int Max=50, Min=10;
pkt.Min=30;
constraint c1 { data>Min; pkt.Max=100;
data<Max; } repeat(10)
endclass assert(pkt.randomize())
$display(pkt.data);
program test; end
packet pkt; endprogram
initial begin
pkt=new;
Futurewiz
www.futurewiz.co.in
Result

# 22 # 72
# 22 # 53
# 29 # 66
# 27 # 79
# 46 # 68
# 43 # 69
# 33 # 78
# 43 # 95
# 46 # 65
# 36 # 34

Futurewiz
www.futurewiz.co.in
Example2

class packet; program test;


rand bit [7:0] data; packet pkt;
constraint c2 { data>50; initial begin
data<10; } pkt=new;
endclass repeat(10)
if(pkt.randomize())
$display(“Randomization
Success”);
else
$display(“Randomization Fails”);
end
endprogram Futurewiz
www.futurewiz.co.in
Result

# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails
# Randomization Fails

Futurewiz
www.futurewiz.co.in
pre_randomize and post_randomize

 Every class contains pre_randomize and post_randomize functions


which are evoked every time randomize function is called.

 When randomize function is called, it first evokes pre_randomize and


then randomization is done.

 post_randomize function is only called if randomization was successful.

 pre_randomize and post_randomize functions can be written in a class


to offer user defined functionality before and after randomization.

Futurewiz
www.futurewiz.co.in
Example1

class packet; program test;


rand bit [7:0] data; packet pkt;

function void pre_randomize; initial begin


$display(“Pre-Randomize”); pkt=new;
endfunction repeat(5) begin
void'(pkt.randomize);
function void post_randomize;
$display(pkt.data);
$display(“Post-Randomize”);
end
endfunction
end
endclass endprogram
Futurewiz
www.futurewiz.co.in
Result

# Pre-Randomize
# Post-Randomize # 33
# Pre-Randomize
# Post-Randomize # 25
# Pre-Randomize
# Post-Randomize # 202
# Pre-Randomize
# Post-Randomize # 138
# Pre-Randomize
# Post-Randomize # 15

Futurewiz
www.futurewiz.co.in
Example2

class A; class B extends A;

function void pre_randomize; function void pre_randomize;


$display(“B: Pre-Randomize”);
$display(“A: Pre-Randomize”);
endfunction
endfunction
function void post_randomize;
function void post_randomize; $display(“B: Post-Randomize”);
$display(“A: Post-Randomize”); endfunction
endfunction endclass

endclass

Futurewiz
www.futurewiz.co.in
Example2

program test;
Result
B b1; # B: Pre-
Randomize
initial begin # B: Post-
b1=new; Randomize
# B: Pre-
repeat(2)
Randomize
void'(b1.randomize); # B: Post-
end Randomize
endprogram
Pre-Randomize and Post-
Randomize of parent class are
overridden Futurewiz
www.futurewiz.co.in
Controlling Randomization

 Randomization nature of rand and randc variables can be turned on/off


dynamically.

 rand_mode method is used to change randomization status of rand and


randc variable.

 When used as a task, the argument determines the state of rand and
randc variables.

 When argument is 0 then randomization is disabled(turned-off), when


argument is 1 then randomization is enabled(turned-on).

Futurewiz
www.futurewiz.co.in
Controlling Randomization

 When used as a function, rand_mode returns the current


status of rand and randc variables.

 It returns 1 if randomization is on else it returns 0.

 Hierarchal reference of variables in an object can also be


given to disable/enable specific rand and randc variables.

 Randomization is enabled by default.

Futurewiz
www.futurewiz.co.in
Example1

class packet; repeat(4) begin


rand bit [7:0] data; void'(pkt.randomize);
$display(pkt.data); end
endclass
pkt.rand_mode(0);
//Disabling Randomization
program test; repeat(3) begin
packet pkt; void'(pkt.randomize)
$display(pkt.data);
initial begin
end end
pkt=new;
endprogram
Futurewiz
www.futurewiz.co.in
Result

# 33
# 25
# 202
# 138
# 138
# 138
# 138

Futurewiz
www.futurewiz.co.in
Example2

class packet;
if(pkt.rand_mode()) //Check current Status
rand bit [7:0] data1;
$display(“Randomization on”);
rand int data2;
else $display(“Randomization off”);
endclass
end
pkt.rand_mode(0);
program test; void'(pkt.randomize);
packet pkt; if(pkt.rand_mode())
initial begin $display(“Randomization on”);
pkt=new; else $display(“Randomization off”); end
repeat(10) begin endprogram
void'(pkt.randomize);

Futurewiz
www.futurewiz.co.in
Example3

class packet; repeat(10) if(pkt.randomize)


rand bit [7:0] data1; $display(pkt.data1, pkt.data2);
rand byte data2; pkt.data2.rand_mode(0);
//turn off for data2
endclass
repeat(10) if(pkt.randomize)
$display(pkt.data1, pkt.data2);
program test; pkt.data2.rand_mode(1);
packet pkt; repeat(10) if(pkt.randomize)
initial begin $display(pkt.data1, pkt.data2); end
pkt=new; endprogram

Futurewiz
www.futurewiz.co.in
Result

# 238 94
# 85 48
# 202 -92
# 29 38
# 155 48
# 225 -91
# 81 -66
# 232 -82
# 85 -112
# 141 -34
# 244 -34
# 32 -34
# 9 -34 Futurewiz
www.futurewiz.co.in
Example4

class packet; repeat(10)


rand bit [7:0] data1; if(pkt.randomize)
byte data2; $display(pkt.data1, pkt.data2);
repeat(10)
endclass
if(pkt.randomize(data2))
program test; //will only randomize data2
packet pkt; $display(pkt.data1, pkt.data2);
initial begin end
pkt=new; endprogram

Futurewiz
www.futurewiz.co.in
Result

# 238 0
# 85 0
# 202 0
# 29 0
# 155 0
# 225 0
# 141 75
# 141 115
# 141 -24
# 141 111
# 141 -119

Futurewiz
www.futurewiz.co.in
Example5

class packet;
rand int data;
int Max, Min;
constraint c1{ data> Min; data<Max; }
constraint c2 { Max> Min; }
task set(int Min, Max);
this.Min=Min;
this.Max=Max;
endtask
endclass

Futurewiz
www.futurewiz.co.in
Example5

initial begin
packet p1=new;
p1.set(5, 25);
repeat(5) if(p1.randomize)
$display(“Random value=%0d”, p1.data);
p1.set(35, 20);
repeat(5) if(p1.randomize)
$display(“Random value=%0d”, p1.data);
else $display(“Randomization Failed”);
end

Futurewiz
www.futurewiz.co.in
Result

# Random value=14
# Random value=18
# Random value=15
# Random value=16
# Random value=16
# Randomization Failed
# Randomization Failed
# Randomization Failed
# Randomization Failed
# Randomization Failed

Futurewiz
www.futurewiz.co.in
Random Stability

module test; repeat(5)


class A; if(a1.randomize)
rand bit [3:0] data; $display("a1.data=%0d",a1.data);
endclass repeat(5)
A a1, a2; if(a2.randomize)
$display("a2.data=%0d",a2.data);
initial begin end
a1=new; endmodule
//Random seed initialized
a2=new;
//Random seed initialized with next seed value

Futurewiz
www.futurewiz.co.in
Result

# a1.data=12
# a1.data=7
# a1.data=15
# a1.data=6
# a1.data=9
# a2.data=13
# a2.data=13
# a2.data=6
# a2.data=2
# a2.data=15

Futurewiz
www.futurewiz.co.in
Random Stability

module test; repeat(5)


class A; if(a2.randomize)
rand bit [3:0] data; $display("a2.data=%0d",a2.data
endclass );
A a1, a2; repeat(5)
if(a1.randomize)
initial begin $display("a1.data=%0d",a1.data
a1=new; );
//Random seed initialized end
a2=new; endmodule
//Random seed initialized with next seed value
Futurewiz
www.futurewiz.co.in
Result

# a2.data=13
# a2.data=13
# a2.data=6
# a2.data=2
# a2.data=15
# a1.data=12
# a1.data=7
# a1.data=15
# a1.data=6
# a1.data=9

Futurewiz
www.futurewiz.co.in
Random Stability

initial begin
module test;
class A; a1=new(3); a2=new(3);
repeat(5)
rand bit [3:0] data;
if(a1.randomize)
function new(int seed);
$display("a1.data=%0d",a1.data);
srandom(seed);
//set a particular seed repeat(5)
if(a2.randomize)
endfunction
$display("a2.data=%0d",a2.data);
endclass
end
A a1, a2; endmodule

Futurewiz
www.futurewiz.co.in
Result

# a1.data=5
# a1.data=7
# a1.data=12
# a1.data=13
# a1.data=5
# a2.data=5
# a2.data=7
# a2.data=12
# a2.data=13
# a2.data=5

Futurewiz
www.futurewiz.co.in
Relation in Constraints

 Each constraint expression should only contain 1 relation operator.

< <= == > >= -> <-> || ! &&

class bad_cons; low=20, med=224, hi=164


rand bit [7:0] low, med, hi; low=114, med=39, hi=189
constraint bad {low < med < hi;} low=186, med=148, hi=161
endclass low=214, med=223, hi=201

 lo < med is evaluated. Results in 0 or 1


 hi > (0 or 1) is evaluated.

Futurewiz
www.futurewiz.co.in
Relation in Constraints

constraint good{ low < med; low=20, med=40, hi=100


med < hi; } low=10, med=25, hi=90

 User can use == to constraint random value to a particular


expression. Using = will give compilation error.

class packet;
rand int length, data, address;
constraint len { length==address * 5};
endclass

Futurewiz
www.futurewiz.co.in
Set Membership

 User can use inside operator to set membership in a


constraint block.

 Example: To limit address in range from 1 to 5, 7 to 11 and


to a set of values 15, 18, 25.

class packet;
rand int address;
constraint limit {address inside { [1:5], [7:11], 15, 18, 25
};}
endclass

Futurewiz
www.futurewiz.co.in
Set Membership

 A ! Operator can be used to exclude set of values


class packet;
rand int address;
constraint limit { !(address inside { 6, [12:14]} ) ;}
endclass

 Using arrays to set membership.


class packet;
int arr [ ]= `{ 5, 7, 11, 13, 19};
rand int address;
constraint limit { address inside { arr }; }
endclass

Futurewiz
www.futurewiz.co.in
Set Membership

class packet;
rand int data;
constraint limit { ( (data==5) || (data==7) || (data==9) );}
endclass
There is a better way of providing such
constraints:
class packet;
rand int data;
constraint limit { data inside { 5, 7, 9}; }
endclass

Futurewiz
www.futurewiz.co.in
Weighted Distribution

 User can provide weights for random numbers to obtain


non-uniform distribution.

 := operator is used to assign same weight to all the values.

 :/ operator is used to distribute weight among all the values.

 dist operator is used to specify distribution.

 Weighted distribution does not work on randc variables.

 Example: constraint con { src dist { 0:=40, [1:3] :=60 };


dst dist { 0:/40 , [1:3] :/60 }; }
Futurewiz
www.futurewiz.co.in
Example1

class packet;
rand int data;
constraint con { data dist { 0:=40, [1:4] :=60, [6:7]:=20 }; }
endclass
//Total weight= 40 + 60 + 60 + 60 + 60 + 20 + 20=320

data=3 weight=60/320=18.75%
data=0 weight=40/320=12.5%
data=4 weight=60/320=18.75%
data=1 weight=60/320=18.75%
data=6 weight=20/320=6.25%
data=2 weight=60/320=18.75%
data=7 weight=20/320=6.25%

Futurewiz
www.futurewiz.co.in
Example2

class packet;
rand int data;
constraint con { data dist { 0:/20, [1:3] :/60, [6:7]:/20 }; }
endclass
//Total weight= 20 + 60 + 20=100

data=0 weight=20/100=20% data=3 weight=20/100=20%


data=1 weight=20/100=20% data=6 weight=10/100=10%
data=2 weight=20/100=20% data=7 weight=10/100=10%

Futurewiz
www.futurewiz.co.in
Example3

typedef enum {Red, Green, Blue} color;


class temp;
rand color col;
int redw=5, greenw=3, bluew=4;
constraint weight { col dist { Red:=redw,
Green:=greenw,
Blue:=bluew}; }
endclass

Futurewiz
www.futurewiz.co.in
Bidirectional Constraints

 Constraints are not procedural but declarative.

 All constraints should be active at same time.

rand bit [15:0] a, b, c; Solution a b c


constraint cp { a < c; S1 6 6 7
b == a; S2 6 6 8
c < 10; S3 6 6 9
b > 5; S4 7 7 8
} S5 7 7 9
S6 8 8 9
 Even though there is no direct constraint on lower value of
c, constraint on b restricts choices.
Futurewiz
www.futurewiz.co.in
Implication Constraints

constraint mode_c { if (mode == small)


len < 10;
else if (mode == large)
len > 100; }

Is equivalent to
constraint mode_c { (mode == small) -> len < 10;
(mode == large) -> len > 100; }
 If mode is small that implies length should be less than 10.
 If mode is large that implies length should be more than 100.
 Implication helps in creating case like blocks.

Futurewiz
www.futurewiz.co.in
Efficient Constraints

rand bit [31:0] addr;


constraint slow { addr % 4096 inside { [0:20], [4075:4095] };
}

rand bit [31:0] addr;


constraint fast { addr [11:0] inside { [0:20], [4075:4095]
};
}
 In slow, first addr is evaluated and then % is performed
and then constraints are applied. In fast, constraints are
directly applied on selected bits hence faster and achieves
the same result.
Futurewiz
www.futurewiz.co.in
Solution Probabilities

Probabilit
Solution x y
y
class Unconstrained; S1 0 0 1/8
rand bit x;
S2 0 1 1/8
// 0 or 1
S3 0 2 1/8
rand bit [1:0] y;
S4 0 3 1/8
// 0, 1, 2, or 3
endclass S5 1 0 1/8
S6 1 1 1/8
S7 1 2 1/8
S8 1 3 1/8

Futurewiz
www.futurewiz.co.in
Solution Probabilities

Probabilit
class Implication1; Solution x y
y
rand bit x; S1 0 0 1/2
// 0 or 1 S2 0 1 0
rand bit [1:0] y; S3 0 2 0
// 0, 1, 2, or 3 S4 0 3 0
constraint c {
S5 1 0 1/8
(x==0) -> (y==0); }
S6 1 1 1/8
endclass
S7 1 2 1/8
S8 1 3 1/8

Futurewiz
www.futurewiz.co.in
Solution Probabilities

Probabilit
class Implication2; Solution x y
y
rand bit x; S1 0 0 0
// 0 or 1 S2 0 1 0
rand bit [1:0] y; S3 0 2 0
// 0, 1, 2, or 3 S4 0 3 0
constraint c {
S5 1 0 0
y>0;
S6 1 1 1/3
(x==0) -> (y==0); }
endclass S7 1 2 1/3
S8 1 3 1/3

Futurewiz
www.futurewiz.co.in
Solve before

 A solve before keyword can be used to specify order in


which random variables would be solved.
class solvebefore; Probabilit
Solution x y
rand bit x; y
// 0 or 1 S1 0 0 1/2
rand bit [1:0] y; S2 0 1 0
// 0, 1, 2, or 3 S3 0 2 0
constraint c { S4 0 3 0
(x==0) -> (y==0); S5 1 0 1/8
solve x before y; }
S6 1 1 1/8
endclass
S7 1 2 1/8
S8 1 3 1/8
Futurewiz
www.futurewiz.co.in
Solve before

class solvebefore; Probabilit


Solution x y
rand bit x; y
// 0 or 1 S1 0 0 1/8
rand bit [1:0] y; S2 0 1 0
// 0, 1, 2, or 3 S3 0 2 0
constraint c { S4 0 3 0
(x==0) -> (y==0); S5 1 0 1/8
solve y before x; }
S6 1 1 1/4
endclass
S7 1 2 1/4
S8 1 3 1/4

Futurewiz
www.futurewiz.co.in
Controlling Constraints

 Constraints can be turned on/off during runtime.

 constraint_mode() is used to achieve this capability.

 When used with handle.constraint, this method controls a single


constraint.

 When used with just handle, it controls all constraints for an object.

 To turn off constraint, 0 is passed as an argument to constraint_mode


and to turn on, 1 is passed as an argument.

Futurewiz
www.futurewiz.co.in
Example

class Packet;
rand int length;
constraint c_short { length inside { [1:32] }; }
constraint c_long { length inside { [1000:1023]};
}
endclass

Futurewiz
www.futurewiz.co.in
Example

Packet p;
initial begin
p = new;
// Create a long packet by disabling short constraint
p.c_short.constraint_mode(0);
assert (p.randomize());
// Create a short packet by disabling all constraints
// then enabling only the short constraint
p.constraint_mode(0);
p.c_short.constraint_mode(1);
assert (p.randomize());
end

Futurewiz
www.futurewiz.co.in
Inline Constraints

 New constraints can be added to existing constraints while


calling randomize function using randomize with.

 constraint_mode can be used disable any conflicting


constraints.
class Transaction;
rand bit [31:0] addr, data;
constraint c1 { addr inside { [0:100], [1000:2000] }; }
endclass

Futurewiz
www.futurewiz.co.in
Inline Constraints

Transaction t;
initial begin
t = new(); // addr is 50-100, 1000-1500, data < 10
repeat(5)
assert(t.randomize() with { addr >= 50;
addr <= 1500;
data < 10;} );

repeat(5) // force addr to a specific value, data > 10


assert(t.randomize() with { addr == 2000;
data > 10; } );
end
Futurewiz
www.futurewiz.co.in
Constraint in Inheritance

 Additional constraints can be provided in a subclass


class(child class). Child class object has to fulfill both the
constraints (parent and child).
class base; class child extends base;
rand int data; constraint limit2 { data > 50;
constraint limit1 { data> 0; }
data< 100; } endclass
endclass
Parent: 0 < data < 100 Child: 50 < data < 100

Futurewiz
www.futurewiz.co.in
Example2

class base; class child extends base;


rand int data; constraint limit2 { data ==
constraint limit1 { data> 0; 50;
data< 100; }
} endclass
endclass

Parent: 0 < data < 100 Child: data=50

Futurewiz
www.futurewiz.co.in
Example3

class base; class child extends base;


rand int data; constraint limit2 { data > 10;
constraint limit1 { data> 40; data< 30;
data< 50; }
} endclass
endclass

Parent: 40 < data < 50 Child: 10 < data < 30

Randomization Fails because both constraints are not satisfied

Futurewiz
www.futurewiz.co.in
Example 4

class base; class child extends base;


rand int data; rand int data;
constraint limit1 { data> 40; constraint limit2 { data > 10;
data< 50; data< 30;
} }
endclass endclass

Parent: 40 < data < 50 Child: 10 < data < 30

Parent data is different as compared to child data. Data Overridden

Futurewiz
www.futurewiz.co.in
Constraint in Inheritance

 Constraints are overridden in child class if they are defined


with same name as that present in parent class.
class base; class child extends base;
rand int data; constraint limit { data > 50;
constraint limit { data> 20; data < 90; }
data< 40; } endclass
endclass

Parent: 20 < data < 40 Child: 50 < data < 90

Constraints are overridden


Futurewiz
www.futurewiz.co.in
randcase

 A randcase keyword can be used to make a weighted


choice between several actions.
initial begin
int len;
repeat(20) begin
randcase
1: len = $urandom_range(0, 2); // 10%: 0 to 2
8: len = $urandom_range(3, 5); // 80%: 3 to 5
1: len = $urandom_range(6, 7); // 10%: 6 to 7
endcase
$display("len=%0d", len); end
end
Futurewiz
www.futurewiz.co.in
randsequence

 The random sequence generator is useful for randomly


generating structured sequences of stimulus.

 randsequence is composed of one or more productions.

 Each production contains a name and one or more


production list.

 Production list contains one or more production_item.

Futurewiz
www.futurewiz.co.in
Example1

module rand_sequence1();
initial begin
repeat(5) begin
randsequence( main ) //main is production
main : one two three ; //main contains one production list
one : {$write("one");}; //one two three are production items
two : {$write("two");};
three: {$display("three");};
endsequence
end
end
endmodule : rand_sequence1

Futurewiz
www.futurewiz.co.in
Result

# one two three


# one two three
# one two three
# one two three
# one two three

Futurewiz
www.futurewiz.co.in
Example2

module rand_sequence2();
initial begin
repeat(7) begin
randsequence( main ) //main contains three production list
main : one| two | three ; //one two three are production list
one : {$display("one"); }; //one list will be chosen randomly
two : {$display("two"); };
three: {$display("three"); };
endsequence
end
end
endmodule : rand_sequence2

Futurewiz
www.futurewiz.co.in
Result

# one
# one
# one
# one
# three
# one
# two

Futurewiz
www.futurewiz.co.in
Example3

module rand_sequence3();
initial begin
repeat(50) begin
randsequence( main )
main : one:=5 | two:=2 | three:=3 ; //production list with
weights
one : {$display("one");};
two : {$display("two");};
three: {$display("three");};
endsequence
end
end
endmodule : rand_sequence3 Futurewiz
www.futurewiz.co.in
Example4

module rand_sequence4();
int one_1, two_2, three_3; bit on;
initial begin
repeat(100) begin
randsequence( main )
main : one three;
one : if(on) incr_one else incr_two;
incr_one : {one_1 ++; on=~on;};
incr_two : {two_2 ++; };
three: {three_3++;};
endsequence end end
endmodule : rand_sequence4

Futurewiz
www.futurewiz.co.in
Example5

module rand_sequence5();
initial for (int i = 0 ; i < 10 ; i++)
randsequence( main )
main : case(i %3)
0 : zero;
1, 2 : non_zero;
default : def;
endcase
zero : {$display("zero");};
non_zero : {$display("non_zero");};
def : {$display("default");};
endsequence
endmodule : rand_sequence5

Futurewiz
www.futurewiz.co.in
System Verilog
PROGRAM BLOCK & INTERFACE
Program Block

 Verilog module works well for design but when used for
Test benches may lead to race-around condition between
design and Test bench.

 System Verilog adds program block which is used meant


for writing Test Bench.

 program and endprogram keywords are used to define a


program block.

Futurewiz
www.futurewiz.co.in
Program Block

 program block has following features:


o They separate test benches from design unit.
o Statements are executed in Reactive Region.
o always blocks are not allowed in program block.
o They can be instantiated inside other modules.
o Instance of module or program block is not allowed inside
program block.
o They have access to variables present inside a module
where they are instantiated but vice versa is not true.
o Implicit system task $exit is called when program block
terminates.
Futurewiz
www.futurewiz.co.in
Program Block Region

Preponed Active

Test Bench runs


Inactive
From Current Time once all design
Slot
NBA related activities
are over.
Observed

Re-Active
Program Block
To Next Time
Slot Re-Inactive Runs Here

Postponed Re-NBA

Futurewiz
www.futurewiz.co.in
Example1

module tb;
reg clk=0, t=1;
module tff (q, clk, t);
wire q=0;
input clk, t;
output reg q=0; always #5 clk=~clk;

tff u0 (q, clk, t);


always @ (posedge clk)
if(t) q<= ~ q; always @ (posedge clk)
endmodule $display($time, “q=%d”, q);

endmodule
Futurewiz
www.futurewiz.co.in
Example1

Result:
5 q= 0
15 q= 1
25 q= 0
35 q= 1
45 q= 0
55 q= 1

Futurewiz
www.futurewiz.co.in
Example2

program tb (input clk);


module tff (q, clk, t);
input clk, t; initial //always not
allowed
output reg q=0;
begin
forever @ (posedge clk)
always @ (posedge clk)
$display($time, “q=%d”, q);
if(t) q<= ~ q;
end
endmodule
initial t=1;

endprogram
Futurewiz
www.futurewiz.co.in
Example2

module top;
reg clk=0, t;
wire q;

always #5 clk=~clk;

tff u0 (q, clk, t);


tb u1 (clk); //program has access to t and
q

endmodule
Futurewiz
www.futurewiz.co.in
Example2

Result:
5 q= 1
15 q= 0
25 q= 1
35 q= 0
45 q= 1
55 q= 0

Futurewiz
www.futurewiz.co.in
Example3

program tb;
int a;
initial $monitor(“result is %d”,
Result : result is 2
a);
a=5
initial begin
#3 a= a + 2; $monitor does not execute
#4 a= a + 3; for a=5 because of implicit
end $exit

endprogram
Futurewiz
www.futurewiz.co.in
Example4

program tb;
int a;
initial $monitor(“result is %d”, a);

initial begin
#3 a= a + 2;
Result :
#4 a= a + 3;
result is 2
#1 ;
result is 5
end

endprogram

Futurewiz
www.futurewiz.co.in
Interface

 Interface is used to encapsulate communication between design


blocks, and between design and verification blocks.

 Encapsulating communication between blocks facilitates design reuse.


Interfaces can be accessed through ports as a single item.

 Signals can be added to and remove easily from an interface without


modifying any port list.

 Interface can contain the connectivity, synchronization, and optionally,


the functionality of the communication between two or more blocks.

Futurewiz
www.futurewiz.co.in
Design

module adder (input bit clk,


input logic [3:0] a, b,
output logic [4:0] sum);

always @ (posedge clk)


sum= a + b;

endmodule

Futurewiz
www.futurewiz.co.in
Test Bench

program tb (input bit clk,


input logic [4:0] sum,
output logic [3:0] a, b);

initial
begin
$monitor (“a=%0d b=%0d sum=%0d”, a, b, sum);
forever begin a=$random; b=$random; #10; end
end

endprogram

Futurewiz
www.futurewiz.co.in
Top Level

module top ();


bit clk=0;
Now in case you have to add
logic [3:0] a, b; one more input c, you have to
logic [4:0] sum; define c at three place adder, tb
and top.
always #5 clk=~clk;

adder a0 (.*); //connect variables to ports that


have
tb t0 (.*); // same name and same data type
endmodule
Futurewiz
www.futurewiz.co.in
Defining Interface

interface intf (input bit


clk);

logic [3:0] a, b;
logic [4:0] sum;

endinterface : inf

Futurewiz
www.futurewiz.co.in
Design

module adder (intf inf);

always @ (posedge
inf.clk)
inf.sum= inf.a + inf.b;

endmodule : adder

Futurewiz
www.futurewiz.co.in
Test Bench

program tb (inft inf);

initial begin
$monitor (“a=%0d b=%0d sum=%0d”, inf.a, inf.b,
inf.sum);
forever begin
inf.a=$random;
inf.b=$random;
#10; end
end

endprogram : tb
Futurewiz
www.futurewiz.co.in
Top Level

module top ();


bit clk=0;

always #5 clk=~clk;

intf inf(clk); //inf is interface instance


adder a0 (inf);
tb t0 (inf);

endmodule

Futurewiz
www.futurewiz.co.in
Modport

 modport construct is to used to provide direction


information for module ports.
interface intf (input bit clk);

logic [3:0] a, b;
logic [4:0] sum;
//incase of inout port use wire
modport DUT (input clk, a, b, output sum);
modport TB (input clk, sum, output a, b);

endinterface : intf
Futurewiz
www.futurewiz.co.in
Design

module adder (intf.DUT inf);

always @ (posedge inf.clk)


inf.sum= inf.a + inf.b;

endmodule : adder

Futurewiz
www.futurewiz.co.in
Test Bench

program tb (intf.TB inf);

initial begin
$monitor (“a=%0d b=%0d sum=%0d”, inf.a, inf.b,
inf.sum);
forever begin
inf.a=$random;
inf.b=$random;
#10; end
end

endprogram : tb
Futurewiz
www.futurewiz.co.in
Top Level

module top ();


bit clk=0;

always #5
clk=~clk;

intf i0 (.*);
adder a0 (.*);
tb t0 (.*);

endmodule
Futurewiz
www.futurewiz.co.in
Clocking Block

 Clocking block construct identifies clock signals and


captures the timing and synchronization requirements of
the blocks being modeled.

 Clocking block assembles signals that are synchronous to


a particular clock and makes their timing explicit.

 Clocking block separates the timing and synchronization


details from the structural, functional, and procedural
elements of a test bench.

Futurewiz
www.futurewiz.co.in
Clocking Block

 In case of synchronous circuits, input should be sampled


just before the clock and output should be driven just after
the clock.

 So from test bench point of view, design outputs should be


sampled just before the clock and design inputs should be
driven just after the clock.

 By default design outputs are sampled at #1step (Prepone


Region) and design inputs are driven at #0 (Inactive /Re-
Inactive Region).
Futurewiz
www.futurewiz.co.in
Clocking Block

interface intf(input bit clk);


…………
modport TB (input clk, clocking cb);
clocking cb @ (posedge clk); //specifying active clock
edge
input sum; //sampled in prepone region
output a, b; //driven in inactive region
endclocking : cb //Directions w.r.t Test Bench
…………
endinterface
Futurewiz
www.futurewiz.co.in
Clocking Block

Clk

en
Output of Test Bench

en

Output of Clocking Block / Input to


DUT Futurewiz
www.futurewiz.co.in
Clocking Block

Clk

count 1 2 3 4 5 6 7

Output of DUT/ Input to Clocking


Block

count 0 1 2 3 4 5 6

Input to Test Bench

Futurewiz
www.futurewiz.co.in
Clocking Block

………………………
clocking cb @ (posedge clk); //specifying active clock edge
default input #3ns output #2ns;
//Specifying user default for sampling and driving

input sum, reset; //sampled 3ns before active clock edge


output a, b; //driven 2ns after active clock edge
endclocking : cb
…………………………

Futurewiz
www.futurewiz.co.in
Clocking Block

………………………
clocking cb @ (posedge clk); //specifying active clock edge
default input #3ns output #2ns;
//Specifying user default for sampling and driving

input sum; //sampled 3ns before active clock edge


output a, b; //driven 2ns after active clock edge
input negedge reset; //Overriding default sampling for reset
endclocking : cb
…………………………

Futurewiz
www.futurewiz.co.in
Interface

interface intf(input bit clk);


logic [3:0] count; logic en;

modport DUT (input clk, en, output count); //DUT


modport TB (input clk, clocking cb); //Test Bench

clocking cb @ (posedge clk); //Clocking Block


input count;
output en;
endclocking
endinterface

Futurewiz
www.futurewiz.co.in
Design

module counter (intf.DUT inf);

always @ (posedge inf.clk)


if(inf.en)
inf.count+=1;

endmodule : counter

Futurewiz
www.futurewiz.co.in
Test Bench

program tb (intf.TB inf);

initial begin
@inf.cb; //continue on active edge in cb
#3 inf.cb.en<=1; // use NBA for signals in cb
##8 inf.cb.en<=0; //wait for 8 active edges in cb
repeat(2) @inf.cb; //wait for 2 active edges in cb
inf.cb.en<=1;
wait (inf.cb.count==3) inf.cb.en<=0; //wait for count to become 3
end
endprogram : tb

Futurewiz
www.futurewiz.co.in
Parameterized Interface

interface intf #(size=3, type typ=logic) (input bit clk);


typ [size-1:0] count;
typ en;

modport DUT (input clk, en, output count); //DUT


modport TB (input clk, count, output en); //Test Bench

endinterface

Futurewiz
www.futurewiz.co.in
Virtual Interface

 A virtual interface is a variable that represents an interface instance.


This interface is not use to represent physical connections.

 Virtual interface variables can be passed as arguments to tasks, and


functions.

 Tasks and functions can modify variables present in a virtual interface


which has the same effect as accessing physical interface.

 A virtual interface can be declared as class property, should be initialize


before usage.

Futurewiz
www.futurewiz.co.in
Virtual Interface

interface intf (input bit clk);


logic req, gnt;

always @(posedge clk); //functionality inside


interface
if(req) begin
repeat(2) @(posedge clk);
gnt<=1; end
else gnt<=0;
endinterface

Futurewiz
www.futurewiz.co.in
Virtual Interface

task gen_req(virtual intf a);


module test;
@(posedge a.clk) a.req<=1;
bit clk=0;
@(posedge a.clk) a.req<=0;
always #5 clk=~clk;
repeat (5) @(posedge a.clk);
intf inf(clk);
a.req<=1;
initial
@(posedge a.clk) a.req<=0; endtask
fork task rec_gnt(virtual intf b);
gen_req(inf); forever begin
rec_gnt(inf); @(posedge b.gnt)
join $display($time, “ grant asserted ”);
endmodule end
endtask Futurewiz
www.futurewiz.co.in
Virtual Interface

module top;
class test;
bit clk=0;
virtual intf t1 ;
always #5 clk=~clk;
function new(virtual intf t2); intf inf(clk);
t1=t2; //initializing virtual initial begin
//interface test c1= new(inf);
endfunction fork
//task gen_req; c1.gen_req;
//task rec_gnt; c1.rec_gnt;
join end
endclass endmodule
Futurewiz
www.futurewiz.co.in
System Verilog
PROCESSES
final block

 final block is a procedural statement that occurs at the end


of simulation.

 Delays are not allowed inside final block.

 Final block can only occur once during simulation.

 $finish can be used to trigger final block.


final
begin
$display(“Simulation ends”);
$display(“No of errors=%0d”, error);
end Futurewiz
www.futurewiz.co.in
Block Statements

 Block statements are used to group procedural statements


together.

 There are two types of blocks :


o Sequential blocks (begin - end)
o Parallel blocks (fork - join)

 System Verilog introduces three types of Parallel blocks:


o fork – join
o fork – join_any
o fork – join_none
Futurewiz
www.futurewiz.co.in
fork - join

 In fork-join, the process executing the fork statement is


blocked until the termination of all forked processes.
module test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join
$display(“Out of Fork at %0d”, $time); end
endmodule
Futurewiz
www.futurewiz.co.in
fork - join

Result :
Before Fork
#3 occurs at 3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8
Out of Fork at 8

Futurewiz
www.futurewiz.co.in
fork – join_any

 In fork-join_any, the process executing the fork statement is


blocked until any one of the processes spawned by fork
completes.
module test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join _any
$display(“Out of Fork at %0d”, $time); end
endmodule
Futurewiz
www.futurewiz.co.in
fork – join_any

Result :
Before Fork
#3 occurs at 3
Out of Fork at 3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8

Futurewiz
www.futurewiz.co.in
fork – join_none

 In fork-join_none, the process executing the fork statement


continues to execute with all processes spawned by fork.
module test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join_none
$display(“Out of Fork at %0d”, $time); end
endmodule
Futurewiz
www.futurewiz.co.in
fork – join_none

Result :
Before Fork
Out of Fork at 0
#3 occurs at 3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8

Futurewiz
www.futurewiz.co.in
wait fork

program test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join_none
$display(“Out of Fork at %0d”, $time); end
endprogram
program block exits simulation once it reaches end of initial
block
Futurewiz
www.futurewiz.co.in
wait fork

Result :
Before Fork
Out of Fork at 0

Futurewiz
www.futurewiz.co.in
wait fork

program test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join_none
$display(“Out of Fork at %0d”, $time);
wait fork; end
endprogram

Waits till all forked processed are completed


Futurewiz
www.futurewiz.co.in
wait fork

Result :
Before Fork
Out of Fork at 0
#3 occurs at 3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8

Futurewiz
www.futurewiz.co.in
disable fork

module test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time); end
begin #6 $display(“#6 occurs at %0d”, $time); end
begin #8 $display(“#8 occurs at %0d”, $time); end
begin #5 $display(“#5 occurs at %0d”, $time); end
join_any
$display(“Out of Fork at %0d”, $time);
disable fork; end
endmodule
Disable fork kills all forked processes
Futurewiz
www.futurewiz.co.in
disable fork

Result :
Before Fork
#3 occurs at 3
Out of Fork at 3

Futurewiz
www.futurewiz.co.in
Conditional Event Control

 @ event control can have an iff qualifier.


 event expression only triggers if the expression after the iff
is true.

always @(a iff en==1) always @(posedge clk iff en)


begin begin
y<= a; y<=din;
end end

Both the event expression (@a and (@posedge clk))


occurs only if en==1
Futurewiz
www.futurewiz.co.in
Sequence Event Control

 A sequence instance can be used in event expressions to


control the execution of procedural statements based on
the successful match of the sequence.

sequence abc;
@ (posedge clk) a ##1 b ##1 c;
endsequence

always @(abc)
$display(“event occurred on a, b and c in order”);

Futurewiz
www.futurewiz.co.in
Named Events

 System Verilog allows used to define events and trigger


them.

 There are two ways to trigger an event


o Blocking (->)
o Non-Blocking(->>)

 There are two ways to wait for an event


o @ (event_name)
o wait(even_name.triggered)

Futurewiz
www.futurewiz.co.in
Example1

event myevent; //User defined event


int count=0;

initial
begin
-> myevent; //Triggering event Result :
#3 -> myevent; count=2
end

always @(myevent) //waiting for event


count+=1;

Futurewiz
www.futurewiz.co.in
Example2

event myevent; //User defined


event
int count=0;
Result :
initial count=0
begin
-> myevent; //Triggering event
@(myevent) //waiting for event
count+=1;
end
while using @, waiting should start before event is
triggered
Futurewiz
www.futurewiz.co.in
Example3

event myevent; //User defined


event
int count=0;
Result :
initial count=0
begin
@(myevent) //waiting for event
-> myevent; //Triggering event
count+=1;
end
@ is waiting for event but event is never triggered.

Futurewiz
www.futurewiz.co.in
Example4

event myevent; //User defined event


int count=0;
Result :
initial count=1
begin
->>myevent; //Triggering event in NBA region
@(myevent) //waiting for event
count+=1;
end
Event is scheduled to triggered in NBA region because of
which waiting starts before triggering and count
increments

Futurewiz
www.futurewiz.co.in
Example5

event myevent; //User defined event


int count=0;

initial
fork
->myevent; //Triggering event
@(myevent) //waiting for event
count+=1;
join
count value depends upon which statement is executed
first result varies from simulator to simulator.

Futurewiz
www.futurewiz.co.in
Example6

event myevent; //User defined event


int count=0;
Result :
initial count=1
begin
->myevent; //Triggering event
wait (myevent.triggered) //waiting for event
count+=1;
end
When using .triggered, waiting should start before or at
same time when event is triggered.

Futurewiz
www.futurewiz.co.in
Example7

event myevent; //User defined event


int count=0;
Result :
initial count=1
fork
->myevent; //Triggering event
wait(myevent.triggered) //waiting for event
count+=1;
join

Futurewiz
www.futurewiz.co.in
always_comb

 System Verilog provides always_comb procedure for modeling


combinational logic behavior.
always_comb
c= a & b;
 There is an inferred sensitivity list.

 The variables written on the left-hand side of assignments shall not be


written to by any other process.
 The procedure is automatically triggered once at time zero, after all
initial and always procedures.
 Software tools will perform additional check to warn if behavior within
always_comb does not match a combinational logic.

Futurewiz
www.futurewiz.co.in
always_latch

 System Verilog provides always_latch procedure for


modeling latched logic behavior.

always_latch
if(en) b=a;

 This construct is identical to always_comb, except that the


tools will perform additionsal check to warn if behavior
does not match a latch logic.

Futurewiz
www.futurewiz.co.in
always_ff

 always_ff procedure can be used to model synthesizable sequential


logic behavior.

always_ff @ (posedge clk iff !rst or posedge rst)


if(rst)
q<=0;
else
q<=d;
 The always_ff procedure imposes the restriction that it contains one
and only one event control and no blocking timing controls.

 Tools should perform additional checks to warn if the behavior does not
represent sequential logic.

Futurewiz
www.futurewiz.co.in
Fine Grain process control

 A process is a built-in class that allows one process to


access and control another process once it has started.

 Users can declare variables of type process and safely


pass them through tasks.

 Objects of type process are created internally when


processes are spawned. An attempt to call new() would
give error.

Futurewiz
www.futurewiz.co.in
Fine Grain process control

 self() function returns handle to current process.

 status() function returns process status which could be any


of the following:
o FINISHED : Terminated Normally
o RUNNING : Currently Running
o WAITING : Waiting in a blocking statement
o SUSPENDED : Stopped, Waiting for resume
o KILLED : Forcibly terminated

Futurewiz
www.futurewiz.co.in
Fine Grain process control

 kill() function terminates the current process and all its sub
processes.

 await() task allows one process to wait for completion of


another process.

 suspend() function allows a process to suspend either its


own execution or that of another process.

 resume() function restarts previously suspended process.

Futurewiz
www.futurewiz.co.in
Example

module test; task run1();


process p1, p2; p1=process :: self();
int count, i=1; forever
//task definitions #2 count+=1;
//On next slide end
endmodule endtask

Futurewiz
www.futurewiz.co.in
Example

task run2 (ref process p2); initial begin


p2=process :: self(); $monitor($time, count,
repeat (6) i);
begin fork
#4 i*=2; run1();
end run2(p2);
endtask join
end

Futurewiz
www.futurewiz.co.in
Example

initial begin
#3 p1.suspend();
#10 p2.suspend();
#5 p1.resume();
$display(“%s”,p1.status());
$display(“%s”,p2.status());
#2 p2.resume();
#1 p2.await();
#1 p1.kill();
end
Futurewiz
www.futurewiz.co.in
System Verilog
COVERAGE
Coverage

 Coverage is the metric of completeness of verification.

 Why we need coverage?


o Direct Testing is not possible for complex designs.
o Solution is constrained random verification but :
o How do we make sure what is getting verified?
o Are all importance design states getting verified?

 Types of Coverage's:
o Code Coverage.
o Functional Coverage.

Futurewiz
www.futurewiz.co.in
Code Coverage

 Code Coverage is a measure used to describe how much part of


code has been covered (executed).

 Categories of Code Coverage


o Statement coverage
o Checks whether each statement in source is executed.

o Branch coverage
o Checks whether each branch of control statement (if, case)
has been covered.
o Example: choices in case statements.

Futurewiz
www.futurewiz.co.in
Code Coverage

o Condition coverage
o Has Boolean expression in each condition evaluated to both true
and false.
o Toggle coverage
o Checks that each bit of every signal has toggled from 0 to 1 and 1
to 0.
o Transition coverage
o Checks that all possible transitions in FSM has been covered.

o State coverage
o Checks that all states of FSM has been covered.

Futurewiz
www.futurewiz.co.in
Functional Coverage

 Functional Coverage is used to verify that DUT meets all the


described functionality.

 Functional Coverage is derived from design specifications.


o DUT Inputs : Are all interested combinations of inputs
injected.

o DUT Outputs : Are all desired responses observed from


every output port.

o DUT internals : Are all interested design events verified.


e.g. FIFO full/empty, bus arbitration.

Futurewiz
www.futurewiz.co.in
Examples

 Have I exercised all the protocol request types and combinations?


o Burst reads, writes etc.

 Have we accessed different memory alignments?


o Byte aligned, word aligned, dword aligned, etc.

 Did we verify sequence of transactions?


o Reads followed by writes.

 Did we verify queue full and empty conditions?


o input and output queues getting full and new requests getting
back pressured.

Futurewiz
www.futurewiz.co.in
Code vs. Functional Coverage
Functional Coverage

Needs more Functional


High

Coverage points, Check Good Coverage


for unused code
Low

Start of Project Code may be incomplete

Low High

Code Coverage
Futurewiz
www.futurewiz.co.in
Coverage Driven Verification

From Create initial cover metrics


Verification
Plan Generate Random Tests

Run Tests, Collect Coverage

Coverage Met ?
YES
NO
Verification
Identify Coverage Holes
Complete
Add tests to target holes,
Enhance stimulus generator,
Enhance cover metrics if
required Futurewiz
www.futurewiz.co.in
SV Functional Coverage Support

 The System Verilog functional coverage constructs provides:


o Coverage of variables and expressions, as well as cross coverage
between them.

o Automatic as well as user-defined coverage bins.

o Associate bins with sets of values, transitions, or cross products.

o Events and sequences to automatically trigger coverage


sampling.

o Procedural activation and query of coverage.

o Optional directives to control and regulate coverage.


Futurewiz
www.futurewiz.co.in
covergroup

 covergroup construct encapsulates the specification of


a coverage model.

 covergroup is a user defined type that allows you to


collectively sample all variables/transitions/cross that
are sampled at the same clock (or sampling) edge.

 It can be defined inside a package, module, interface,


program block and class.

 Once defined, a covergroup instance can be created


using new() - just like a class.
Futurewiz
www.futurewiz.co.in
Example

Syntax:
covergroup cg_name [(port_list)]
[coverage_event];
//coverage_specs;
//coverage_options;
endgroup [ : cg_name]
Example:
covergroup cg;
……
endgroup

cg cg1=new;
Futurewiz
www.futurewiz.co.in
Coverpoint

 A coverage point (coverpoint) is a variable or an


expression that functionally covers design
parameters.

 Each coverage point includes a set of bins associated


with its sampled values or its value-transitions.

 The bins can be automatically generated or manually


specified.

 A covergroup can contain one or more coverpoints.

Futurewiz
www.futurewiz.co.in
Example

Syntax:
[label : ] coverpoint expression [ iff
(expression)]
[{
//bins specifications;
}] ;
Example:
covergroup cg;
coverpoint a iff (!reset);
endgroup

Futurewiz
www.futurewiz.co.in
bins

 bins are buckets which are used to collect number of times a particular
value/transaction has occurred.

 bins allows us to organize coverpoint sample values in different ways.


o Single value bins.
o Values in a range, multiple ranges.
o Illegal values, etc.

 If bins construct is not used inside coverpoint then automatic bins are
created based on the variable type and size.

 For a n-bit variable, 2 ^ n automatic bins are created.

Futurewiz
www.futurewiz.co.in
Example1

bit [3:0] temp;


covergroup cg;
coverpoint temp; //16 - Automatic bins created
endgroup

cg cg1;
initial cg1=new;

bin[0] to bin[15] are created where each bin stores information


of how many times that number has occurred.

Futurewiz
www.futurewiz.co.in
Example2

bit [3:0] temp;


covergroup cg;
coverpoint temp
{
bins a= { [0 : 15] }; //creates single bin for values 0-15
bins b [ ]= { [0 : 15] }; //creates separate bin for each
//value 0-15
}
endgroup

Futurewiz
www.futurewiz.co.in
Example3

bit [3:0] temp;


covergroup cg;
coverpoint temp
{
bins a [ ]= { 0, 1, 2 }; //creates three bins 0, 1, 2
bins b [ ]= { 0, 1, 2, [1:5] }; //creates eight bins 0, 1, 2,
//1, 2, 3, 4, 5
}
endgroup

Futurewiz
www.futurewiz.co.in
Example4

bit [3:0] temp;


covergroup cg;
coverpoint temp
{
bins a [4]= { [1:10], 1, 5, 7 };
//creates four bins with distribution <1, 2, 3> <4, 5, 6>
<7, 8, 9> <10, 1, 5, 7>
}
endgroup

Futurewiz
www.futurewiz.co.in
Example5

bit [9:0] temp;


covergroup cg;
coverpoint temp
{
bins a = { [0:63], 65 }; // single bin
bins b [ ]={ [127:150], [148:191] }; // overlapping multiple bins
bins c [ ]={ 200, 201, 202 }; // three bins
bins d [ ]={ [1000:$] }; // multiple bins from 1000
// to $(last value:1023)
bins others [ ] = default; // bins for all other value
}
endgroup

Futurewiz
www.futurewiz.co.in
Questa (How to obtain coverage)

vlog +cover filename.sv


vsim –c modulename –do “run time; coverage report –details;”
//Provides Function coverage, -details switch is used to observe
bins

vsim –c –cover modulename –do “run time; coverage report


–details; ” // -cover switch enables code coverage

vsim –c –cover modulename –do “run time; coverage report


–details –html;” //create html report for coverage

Futurewiz
www.futurewiz.co.in
Covergroup Arguments

 Parameterized Covergroups can be written using


arguments.

 Useful if similar covergroups are needed with different


parameters or covering different signals.

 Example: covergroup for all basic FIFO conditions.

 Actual values can be passed to formal arguments while


covergroup is instantiated.

 ref keyword is required if a variable is passed as an


argument.

Futurewiz
www.futurewiz.co.in
Example

bit [16:0] rdAddr, wrAddr;

covergroup addr_cov (input int low, int high, ref bit [16:0] address)
@ (posedge clk);
addr_range : coverpoint address {
bins addrbin= { [low: high] };
}
endgroup

addr_cov rdcov=new ( 0, 31, rdAddr );


addr_cov wrcov=new ( 64, 127, wrAddr );

Futurewiz
www.futurewiz.co.in
Covergroup inside a class

 By embedding covergroup inside class, coverage can


be collected on class members.

 Very useful as it is a nice way to mix constrained


random stimulus generation along with coverage.

 A class can have multiple covergroups.

 For embedded covergroups, instance must be created


be inside the new() of class.

Futurewiz
www.futurewiz.co.in
Example

class xyz;
bit [3:0] m_x;
int m_y;
bit m_z;
covergroup cov1 @ (m_z); //Embedded Covergroup
coverpoint m_x; //16 bins
coverpoint m_y; //2^32 bins
endgroup
function new(); cov1=new; endfunction
endclass
Futurewiz
www.futurewiz.co.in
Example

class c1;
bit [7:0] x;
covergroup cv (input int arg) @ (posedge clk);
option.at_least=arg;
coverpoint x;
endgroup
function new (int p1); cv=new(p1); endfunction
endclass

initial c1 obj=new(4);
Futurewiz
www.futurewiz.co.in
Bins for Transition

 In many cases, we are not only interested in knowing if


certain values or value ranges happen.

 But, we are also interested in knowing if transition


between two values or two value ranges happen.

 Transition coverage is often more interesting in control


scenarios, whereas value coverage is more interesting
in data path scenarios.

Futurewiz
www.futurewiz.co.in
Specifying Transition

 Single Value Transition


(value1=> value2)

 Sequence of Transitions
(value1=> value2 => value3=> value4)

 Set of Transitions
(value1, value2 => value3, value4)

 Consecutive repetition of Transitions


value[*repeat_time]
Futurewiz
www.futurewiz.co.in
Example1

bit [4:1] a;
covergroup cg @ (posedge clk);
coverpoint a
{ bins sa [ ]= ( 4=>5=>6 ), ( [7:9],10=>11,12) ;
bins allother= default sequence;
}
endgroup
Sa will be associated with individual bins (4=>5=>6) ,
(7=>11), (7=>12), (8=>11), (8=>12), (9=>11), (9=>12),
(10=>11), (10=>12)
Futurewiz
www.futurewiz.co.in
Example2

 Consecutive Repetition
bins sb={ 4 [*3] } ;
// (4=>4=>4)
bins sc [ ]={ 3 [*2:4] };
// (3=>3) , (3=>3=>3), (3=>3=>3=>3)

 Non-Consecutive Repetition
bins sd [ ]={ 2 [->3] };
//2=>…. =>2 …. =>2

Futurewiz
www.futurewiz.co.in
Automatic Bin creation

 System Verilog creates implicit bins when coverpoint


does not explicitly specifies it.

 The size of automatic bin creation is:


o In case of enum coverage point it is same as number
of elements in enum.
o In case of integral coverage point it is minimum of 2
^ no. of bits and value of auto_bin_max option.
o Automatic bins creation only considers two state
value.
o If auto_bin_max is less than 2 ^ no. of bits, then
values are equitably distributed among the bins.
Futurewiz
www.futurewiz.co.in
Wildcard Bins

 Wildcard bins are where X, Z or ? will be treated as


don’t care.

bit [2:0] num;

covergroup cg;
coverpoint num
{ wildcard bins even={3’b??0};
wildcard bins odd={3’b??1};
}
endgroup

Futurewiz
www.futurewiz.co.in
Wildcard Bins

bit [3:0] count1;


bit [1:0] count2;

covergroup cg;
coverpoint count1
{ wildcard bins n12_15={4’b11??};
//1100 || 1101 || 1110 || 1111
}
coverpoint count2
{ wildcard bins t =(2’b0x=>2’b1x);
//(0, 1=>2, 3)
}
endgroup
Futurewiz
www.futurewiz.co.in
Excluding bins

 In some cases all the bins may not be of interest, or


design should never have a particular bin.

 These are two ways to exclude bins :


o ignore_bins
o illegal_bins

Futurewiz
www.futurewiz.co.in
Ignore Bins

 All values or transitions associated with ignore_bins


are excluded from coverage.

 Ignored values or transitions are excluded even if they


are also included in another bin.

bit [3:0] num;


covergroup cg;
coverpoint num {
bins val [ ]={ [1:15] }; //7 and 8 are ignored
ignore_bins bins ignoreval={ 7, 8 }; //ignore 7 and 8
ignore_bins bins ignoretran=(3=>4=>5); //ignore transition
} endgroup

Futurewiz
www.futurewiz.co.in
Ignore Bins

bit [2:0] num;

covergroup cg;
coverpoint num {
option.auto_bin_max=4;
//<0:1> , <2:3>, <4:5>, <6:7>
ignore_bins bins hi={6, 7};
// bins 6 and 7 are ignored from
coverage
}
endgroup

Futurewiz
www.futurewiz.co.in
Illegal Bins

 All values or transitions associated with illegal_bins are excluded from


coverage and run-time error is issued if they occur.

 They will result in a run-time error even if they are also included in
another bin.
bit [3:0] num;
covergroup cg;
coverpoint num {
illegal_bins bins illegalval={ 2, 3 }; //illegal bins 2 and 3
illegal_bins bins illegaltran=(4=>5); //4 to 5 is illegal
//transition
} endgroup

Futurewiz
www.futurewiz.co.in
Cross Coverage

 Coverage points measures occurrences of individual values.

 Cross coverage measures occurrences of combination of


values.

 Interesting because design complexity is in combination of


events and that is what we need to make sure is exercised
well.

 Examples:
o Was write enable 1 when address was 4’b1101.
o Have we provide all possible combination of inputs to a Full
Adder.

Futurewiz
www.futurewiz.co.in
Example1

 Cross coverage is specified between two or more


coverpoints in a covergroup.

bit [3:0] a, b;
covergroup cg @ (posedge clk);
cross_cov: cross a , b;
endgroup

 16 bins for each a and b.

 16 X 16=256 bins for cross_cov


Futurewiz
www.futurewiz.co.in
Example2

 Cross coverage is allowed only between coverage points


defined within the same coverage group.

bit [3:0] a, b, c;
covergroup cg @ (posedge clk);
cov_add: coverpoint b+c;
cross_cov: cross a , cov_add;
endgroup

 16 Bins for each a, b and c. 32 bins for b + c.


 16 X 32=512 bins for cross_cov.

Futurewiz
www.futurewiz.co.in
Example3

bit [31:0] a;
bit [3:0] b;
covergroup cg @ (posedge clk);
cova: coverpoint a { bins low [ ]={ [0:9] }; }
cross_cov: cross b, cova;
endgroup

 16 bins for b. 10 bins for cova.


 10 X 16=160 bins for cross_cov.

Futurewiz
www.futurewiz.co.in
Cross Coverage

 Cross Manipulating or creating user-defined bins for


cross coverage can be achieved using bins select-
expressions.

 There are two types of bins select expression :


o binsof
o intersect

Futurewiz
www.futurewiz.co.in
binsof and intersect

 The binsof construct yields the bins of expression passed


as an arguments. Example: binsof (X)

 The resulting bins can be further selected by including or


excluding only the bins whose associated values intersect
a desired set of values.

 Examples:
o binsof(X) intersect { Y } , denotes the bins of coverage
point X whose values intersect the range given by Y.
o ! binsof(X) intersect { Y } , denotes the bins of
coverage point X whose values do not intersect the
range given by Y.
Futurewiz
www.futurewiz.co.in
binsof and intersect

 Selected bins can be combined with other selected bins


using the logical operators && and ||.

bit [7:0] a, b;
covergroup cg @ (posedge clk);
cova : coverpoint a
{
bins a1 = { [0:63] };
bins a2 = { [64:127] };
bins a3 = { [128:191] };
bins a4 = { [192:255] };
} endgroup
Futurewiz
www.futurewiz.co.in
binsof and intersect

covb : coverpoint b
{
bins b1 = { 0 };
bins b2 = { [1:84] };
bins b3 = { [85:169] };
bins b4 = { [170:255] };
}

Futurewiz
www.futurewiz.co.in
binsof and intersect

covc : cross cova, covb


{
bins c1= !binsof(cova) intersect { [100:200] };
//a1*b1, a1*b2, a1*b3, a1*b4
bins c2= binsof(cova.a2) || binsof(covb.b2);
//a2*b1, a2*b2, a2*b3, a2*b4
//a1*b2, a2*b2, a3*b2, a4*b2
bins c3= binsof(cova.a1) && binsof(covb.b4);
//a1*b4
}
endgroup
Futurewiz
www.futurewiz.co.in
Excluding Cross products

 A group of bins can be excluded from coverage by specifying a


select expression using ignore_bins.

covergroup cg;
cross a, b
{
ignore_bins bins ig=binsof(a) intersect { 5, [1:3] };
}
endgroup
 All cross products that satisfy the select expression are
excluded from coverage even if they are included in other
cross-coverage bins of the cross.
Futurewiz
www.futurewiz.co.in
Illegal Cross products

 A group of bins can be marked illegal by specifying a


select expression using illegal_bins.

covergroup cg (int bad);


cross a, b
{
illegal_bins bins invalid=binsof(a) intersect { bad
};
}
endgroup

Futurewiz
www.futurewiz.co.in
Coverage Options

 Options can be specified to control the behaviour of the


covergroup, coverpoint and cross.

 There are two types of options:


o Specific to an instance of a covergroup.
o Specify for the covergroup.

 Options placed in the cover group will apply to all cover


points.

 Options can also be put inside a single cover point for


finer control.

Futurewiz
www.futurewiz.co.in
option.comment

 Comments can be added to make coverage reports


easier to read.

covergroup cg;
option.comment=“Cover group for data and address”;
coverpoint data;
coverpoint address;
endgroup

Futurewiz
www.futurewiz.co.in
per instance coverage

 If your test bench instantiates a coverage group multiple


times, by default System Verilog groups together all the
coverage data from all the instances.

 Sometime you would that all coverpoints should be hit on


all instances of the covergroup and not cumulatively.

covergroup cg;
option.per_instance=1;
coverpoint data;
endgroup
Futurewiz
www.futurewiz.co.in
at_least coverage

 By default a coverpoint is marked as hit (100%) if it is hit


at least one time.

 Some times you might want to change this to a bigger


value.

 Example: If you have a State machine that can handle


some kind of errors. Covering an error for more number
of times has more probability that you might also test
error happening in more than one state.

option.at_least=10
Futurewiz
www.futurewiz.co.in
Coverage goal

 By default a covergroup or a coverpoint is considered


fully covered only if it hits 100% of coverpoints or bins.

 This can be changed using option.goal if we want to settle


on a lesser goal.

bit [2:0] data;


covergroup cg;
coverpoint data;
option.goal=90; //settle for partial coverage
endgroup

Futurewiz
www.futurewiz.co.in
option.weight

 If set at the covergroup level, it specifies the weight of this


covergroup instance for computing the overall instance
coverage.

 If set at the coverpoint (or cross) level, it specifies the


weight of a coverpoint (or cross) for computing the
instance coverage of the enclosing covergroup.

 Usage: option.weight=2 (Default value=1)

 Usage: Useful when you want to prioritize certain


coverpoints /covergroups as must hit versus less
important.
Futurewiz
www.futurewiz.co.in
Example

covergroup cg;
a: coverpoint sig_a { bins a0= {0};
option.weight=0; //will not compute to
//coverage
}
b: coverpoint sig_b { bins b1= {1};
option.weight=1;
}
ab: cross a , b { option.weight=3; }
endgroup

Futurewiz
www.futurewiz.co.in
option.auto_bin_max

 Limiting autobins for coverpoints and crosses

 Usage: option.auto_bin_max = <number> (default=64)

 Usage: option.cross_auto_bin_max =<number>


(default= unbounded)

Futurewiz
www.futurewiz.co.in
Predefined Coverage Methods

Futurewiz
www.futurewiz.co.in
Example1

covergroup packet_cg;
coverpoint dest_addr;
coverpoint packet_type;
endgroup

packet_cg pkt;
initial pkt=new;

always @ (pkt_received)
pkt.sample();

Futurewiz
www.futurewiz.co.in
Example2

covergroup packet_cg;
coverpoint dest_addr;
coverpoint packet_type;
endgroup

packet_cg pkt;
initial pkt=new;

always @ (posedge clk)


if (port_disable) pkt.stop();
else (port_enable)
pkt.start();
Futurewiz
www.futurewiz.co.in
Coverage system tasks and functions

 $set_coverage_db_name ( name )
Sets the filename of the coverage database into which
coverage information is saved at the end of a simulation
run.

 $load_coverage_db ( name )
Load from the given filename the cumulative coverage
information for all coverage group types.

 $get_coverage ( )
Returns as a real number in the range 0 to 100 that
depicts the overall coverage of all coverage group types.
Futurewiz
www.futurewiz.co.in
Cover property

 The property that is used an assertion can be used for


coverage using cover property keyword.

property ab;
@(posedge clk) a ##3 b;
endproperty

cp_ab: cover property(ab) $info(“coverage passed”);

Futurewiz
www.futurewiz.co.in
Effect of coverage on performance

 Be aware that enabling Functional Coverage slows down the simulation.


 So know what really is important to cover :
o Do not use auto-bins for large variables.
o Use cross and intersect to weed out unwanted bins.
o Disable coverpoint/covergroup during reset.
o Do not blindly use clock events to sample coverpoint variables,
instead use selective sampling() methods.
o Use start() and stop() methods to decide when to start/stop
evaluating coverage.
o Do not duplicate coverage across covergroups and properties.

Futurewiz
www.futurewiz.co.in
System Verilog
ASSERTIONS
Assertions and Coverage

 Assertions
 These are checks which used to verify that your design meets the
given requirements.
 Example: grant should be high two clock cycles after request.

 Coverage
 These are used to judge what percentage of your test plan or
functionality has been verified.
 They are used to judge quality of stimulus.
 They help us in finding what part of code remains untested.

Futurewiz
www.futurewiz.co.in
Assertions

Design Rule : Grant should be asserted 2 clock cycles after


request

Clock

Request

Assertion Passed
Grant

Assertion Failed
Grant

Futurewiz
www.futurewiz.co.in
Assertions

 Types of Assertions
Immediate Assertions.
Concurrent Assertions.

Futurewiz
www.futurewiz.co.in
Immediate Assertions

 These are used to check condition at current time.

 These checks are Non Temporal i.e. checks are not performed across
time or clock cycles.

 These are used inside procedural blocks (initial/always and


tasks/functions).

 Assertion fails if expression evaluates to 0, X or Z.

[Label] : assert (expression) [pass _statement];


 In case fail_statement is not provided and assertion fails, then in that
[else fail_statement;]
case an error is reported during runtime.

Futurewiz
www.futurewiz.co.in
Example

Design Rule : State Machine should go to REQ state only if


req1 or
req2 is high.

clk

req1

req2

state IDL RE IDL RE IDL RE


E Q E Q E Q

Futurewiz
www.futurewiz.co.in
Example

always @ (posedge clk)


if (state==REQ) //if current state is
REQ
assert ( req1 || req2) //Check whether req1
or
//req2 is high
$info(“Correct State”);
else
$error(“Incorrect State”);

Futurewiz
www.futurewiz.co.in
Assertions Severity

 $info indicates that the assertion failure carries no specific


severity. Useful for printing some messages.

 $warning indicates runtime warning. Can be used to


indicate non severe errors.

 $error indicates runtime error. Can be used to indicate


protocol errors.

 $fatal indicates fatal error that would stop simulation.

Futurewiz
www.futurewiz.co.in
Examples

always @ (posedge clk)


assert(func(a, b)) ->myevent; else error=error + 1;
//Trigger myevent if function returns 1 else increase error count.

always @ (negedge clk)


assert (y==0) error_flag=0; else error_flag=1;
//y should not be 1 at negedge of clk

always @ (state)
assert($onehot(state)) else $fatal(“state is not one hot”);
//In a one-hot encoded state machine all states should be one-hot

Futurewiz
www.futurewiz.co.in
Concurrent Assertions

 These assertions test for a sequence of events spread over multiple


clock cycles i.e. they are Temporal in nature.

 property keyword is used to define concurrent assertions.

 property is used to define a design specification that needs to be


verified

 They are called concurrent because they occur in parallel with other
design blocks.

[Label] : assert property (property_name) [pass_statement];


[else fail_statement;]

Futurewiz
www.futurewiz.co.in
Assertions

Design Rule : Grant should be high 2 clock cycles after


request,
followed by low request and then grant in consecutive cycles.

Clk

Req

Assertion
Gnt
Passed

Gnt Assertion
Passed

Futurewiz
www.futurewiz.co.in
Example

property req_gnt;
@ (posedge clk) req ##2 gnt ##1 !req ##1 !gnt;
endproperty
assert property(req_gnt) else $error(“req_gnt property violated”);

 ## followed by a number is used to indicate no. of clock cycles.

 If gnt is not high 2 clock cycles after req goes high, violation will be
reported.

 If req and gnt come at proper time but req is not low in next clock
cycle, that will also lead to violations.

Futurewiz
www.futurewiz.co.in
Assertion Region

Preponed Active Values are sampled in


Preponed Region
Sample Data
before entering Inactive
current time
slot (#1step) NBA

From Current Time Slot Observed Evaluated in Observed


Region
To Next Time Slot
True / False statements
Re-Active
executed in Re-Active
$strobe, $monitor,
Region
PLI Calls Re-Inactive

Postponed Re-NBA

Futurewiz
www.futurewiz.co.in
Properties and Sequences

 Assertions can directly include a property.


assert property (@ (posedge clk) a ##1 b);

 Assertions can be split into assertion and property


declared separately
property myproperty;
@ (posedge clk) a ##1 b ##1 c;
endproperty
assert property (myproperty);

Futurewiz
www.futurewiz.co.in
Properties and Sequences

 A property can be disabled conditionally

property disable_property;
@ (posedge clk) disable iff (reset)
a ##1 b ##1 c;
endproperty

 property block contains definition of sequence of


events.

 Complex properties can be structured using multiple


sequence blocks.
Futurewiz
www.futurewiz.co.in
Properties and Sequences

sequence s1; sequence s2;


a ##1 b ##1 c; a ##1 c;
endsequence endsequence

property p1;
@ (posedge clk) disable iff assert
(reset) property(p1);
s1 ##1 s2;
endsequence

Futurewiz
www.futurewiz.co.in
Sequences

 Sequence is series of true/false expression spread over


one or more clock cycles.

 It acts like basic building block for creating complex


property specifications.

 Sampling edge can be specified inside a sequence. If


not defined, it is inferred from property block or assert
block.
sequence s1;
@(posedge clk) a ##1 !b ##1 c ##0 !d;
endsequence
Futurewiz
www.futurewiz.co.in
Linear Sequences

 Linear sequence is finite list of System Verilog Boolean expression


in a linear order of increasing time.

 A sequence is set to match if all these conditions are true:


o The first boolean expression evaluates to true at the first
sampling edge.
o The second boolean expression evaluates to true after the
delay from first expression.
o and so forth, up to and including the last boolean expression
evaluating to true at the last sampling edge.

 Sequence is evaluated on every sampling edge.

Futurewiz
www.futurewiz.co.in
Example

module test; program assert_test;


bit clk; initial begin
logic a=0, b=0, c=0; #4 a=1;
#10 a=0; b=1;
always #5 clk=~clk; #10 b=0; c=1;
property abc; #10 c=0;
@ (posedge clk) a ##1 b ##1 c; #10 a=1;
endproperty #20 b=1;
assert property(abc) #10 c=1;
$info(“Sequence Occurred”); #10;
//program block end
endmodule endprogram

Futurewiz
www.futurewiz.co.in
Example

clk

Error Reported Evaluation in progress Sequence Occurred


Futurewiz
www.futurewiz.co.in
Declaring Sequences

 A sequence can be declared inside:


o Module
o Interface
o Program
o Clocking block
o Package

 Syntax:
sequence sequence_name [ (arguments) ];
boolean_expression;
endsequence [ : sequence_name]
Futurewiz
www.futurewiz.co.in
Sequence Arguments

 Sequences can have optional Formal Arguments.

 Actual arguments can be passed during instantiation.

sequence s1 (data, en)


( !a && (data==2’b11)) ##1 (b==en)
endsequence

 Clock need not be specified in a sequence.

 In this case clock will be inferred from the property or


assert statement where this sequence is instantiated.

Futurewiz
www.futurewiz.co.in
Implication Operator

 Evaluation of a sequence can be pre-conditioned with


an implication operator.

 Antecedent – LHS of implication operator

 Consequent – RHS of implication operator

 Consequent will be evaluated only if Antecedent is true.

 There are two types of implication operators:


o Overlapping (Antecedent |-> Consequent )
o Non-Overlapping (Antecedent |=> Consequent )

Futurewiz
www.futurewiz.co.in
Overlapping Implication Operator

 If antecedent is true then Consequent evaluation starts


immediately.
 If antecedent is false then consequent is not evaluated
and sequence evaluation is considered as true this is
called vacuous pass.

 $assertvacuousoff [ (levels[ , list]) ] can be used to disable


vacuous pass.

property p1;
@ (posedge clk) en |-> (req ##2 ack);
endproperty

Futurewiz
www.futurewiz.co.in
Example

module test; program assert_test;


bit clk; initial begin
logic en=0, req=0, gnt=0; #4 en=1; req=1;
#10 en=0; req=0;
always #5 clk=~clk; #10 gnt=1;
property abc; #10 gnt=0;
@ (posedge clk) en |-> req ##2 gnt; #20 en=1;
endproperty #10 en=0; req=1;
assert property(abc) #10 req=0; gnt=1;
$info(“Sequence Occurred”); #10;
//program block end
endmodule endprogram

Futurewiz
www.futurewiz.co.in
Example

clk

en

re
q
gnt

Error Reported Sequence Occurred Vacuous Pass


Evaluation in progress
Futurewiz
www.futurewiz.co.in
Example

module test; program assert_test;


bit clk; initial begin
logic en=0, req=0, gnt=0; #4 en=1; req=1;
#10 en=0; req=0;
always #5 clk=~clk; #10 gnt=1;
property abc;
#10 gnt=0;
@ (posedge clk) en ##0 req ##2 gnt; #20 en=1;
endproperty #10 en=0; req=1;
assert property(abc) #10 req=0; gnt=1;
$info(“Sequence Occurred”); #10;
//program block end
endmodule endprogram
Futurewiz
www.futurewiz.co.in
Example

clk

en

re
q
gnt

Error Evaluation in Sequence Occurred


Reported progress Futurewiz
www.futurewiz.co.in
Non-Overlapping Implication Operator

 If antecedent is true then Consequent evaluation


starts in next clock cycle.

 If antecedent is false then consequent is not


evaluated and sequence evaluation is considered as
true this is called vacuous pass.

property p1;
@ (posedge clk) en |=> (req ##2
ack);
endproperty
Futurewiz
www.futurewiz.co.in
Example

module test; program assert_test;


bit clk; initial begin
logic en=0, req=0, gnt=0; #4 en=1; req=1;
#10 en=0; req=0;
always #5 clk=~clk; #10 gnt=1;
property abc;
#10 gnt=0;
@ (posedge clk) en |=> req ##1 gnt;
#20 en=1;
endproperty #10 en=0; req=1;
assert property(abc) #10 req=0; gnt=1;
$info(“Sequence Occurred”); #10;
//program block end
endmodule endprogram
Futurewiz
www.futurewiz.co.in
Example

clk

en

re
q
gnt

Vacuous Pass
Error Reported Evaluation in progress Sequence Occurred
Futurewiz
www.futurewiz.co.in
Example

module test; program assert_test;


bit clk; initial begin
logic en=0, req=0, gnt=0; #4 en=1; req=1;
#10 en=0; req=0;
always #5 clk=~clk; #10 gnt=1;
property abc;
#10 gnt=0;
@ (posedge clk) en ##1 req ##1 gnt; #20 en=1;
endproperty #10 en=0; req=1;
assert property(abc) #10 req=0; gnt=1;
$info(“Sequence Occurred”); #10;
//program block end
endmodule endprogram
Futurewiz
www.futurewiz.co.in
Example

clk

en

re
q
gnt

Error Evaluation in Sequence


Reported progress Occurred Futurewiz
www.futurewiz.co.in
Sequence Operators

 ## n represents n clock cycle delay (or number of


sampling edges).

 ## 0 means same clock cycle (overlapping signals).

 ## [min : max] specifies a range of clock cycles


o min and max must be >=0.
sequence s1;
@ (posedge clk) a ## [1:3] b;
endsequence

Equivalent to: (a ##1 b) || (a ##2 b) || (a ##3 b)


Futurewiz
www.futurewiz.co.in
Example

clk

a
Assertion
b
Passed
Assertion
b Passed
Assertion
b Passed
Assertion
b Failed
Futurewiz
www.futurewiz.co.in
Sequence Operators

 $ is used to specify infinite number of clock cycles (till


end of simulation).
sequence s2;
@ (posedge clk) a ## [2:$] b;
endsequence

b must be high after 2 or more clock cycle after a is


asserted.

Futurewiz
www.futurewiz.co.in
Sequence Operators

 Sequence of events can be repeated for a count using [*n].


sequence s3;
@ (posedge clk) a ##1 b [*2];
endsequence

Equivalent to : a ##1 b ##1 b

b must be true for two consecutive clock cycles after a goes high
a ##1 (b ##1 c) [*2];

Equivalent to : a ##1 b ##1 c ##1 b ##1 c


Futurewiz
www.futurewiz.co.in
Sequence Operators

 Sequence of events can be repeated for a range of


count using [*m : n].
o n should be more than 0 and cannot be $
sequence s4;
@ (posedge clk) a ##1 b [*2:5];
endsequence
Equivalent to : b must be true for minimum
(a ##1 b ##1 b ) || 2 and maximum 5
(a ##1 b ##1 b ##1 b) || consecutive clock cycles
(a ##1 b ##1 b ##1 b ##1 b) || after a is asserted
(a ##1 b ##1 b ##1 b ##1 b ##1 b) ||
Futurewiz
www.futurewiz.co.in
Sequence Operators

 [=m] operator can be used if an event repetition of m


non-consecutive cycles are to be detected.
o m should be more than 0 and cannot be $

sequence s5;
@ (posedge clk) a ##1 b [=2];
endsequence

b must be true for 2 clock cycles, that may not be


consecutive.
Futurewiz
www.futurewiz.co.in
Example

clk

b
Assertion
Passed
b
Assertion
Passed
Futurewiz
www.futurewiz.co.in
Sequence Operators

 [=m : n] operator is used if an event repetition of m


(minimum) to n (maximum) non-consecutive cycles are
to be detected.

sequence s6;
@ (posedge clk) a ##1 b [=2: 3];
endsequence

b must be true for minimum of 2 and maximum of 3 clock


cycles,
Equivalent to : (a ##1 b [=2] ) || (a ##1 b [=3] )
that may not be consecutive.
Futurewiz
www.futurewiz.co.in
AND Operator

 Use and operator if two sequences needs to match.

seq1 and seq2

 Following should be true for resultant sequence to


matches:
o seq1 and seq2 should start from same point.
o Resultant sequence matches when both seq1 and
seq2 matches.
o The end point of seq1 and seq2 can be different.
o The end time of resulting sequence will be end time of
last sequence.
Futurewiz
www.futurewiz.co.in
Example

(a ##2 b) and (c ##1 d ##2 e)

clk
a
b
Seq1detecte
d Resultant Sequence
c Detected

d
e
Seq detection started Seq2 detected
Futurewiz
www.futurewiz.co.in
Example

(a and b)

clk

Seq1 Seq2 Detected Resultant Sequence


Detected Detected
Futurewiz
www.futurewiz.co.in
Example

(a ##[2:4] b) and (c ##1 d ##2 e)

clk
a
b
Seq detection started
c

d
e
Seq1 Seq2 Detected Resultant Sequence
Detected Detected Futurewiz
www.futurewiz.co.in
Intersect Operator

seq1 intersect seq2

 Following should be true for resultant sequence to


matches:
o seq1 and seq2 should start from same point.
o Resultant sequence matches when both seq1 and
seq2 matches.
o The end point of seq1 and seq2 should be same.

Futurewiz
www.futurewiz.co.in
Example

(a ##[2:4] b) intersect (c ##1 d ##2 e)

clk
a
b
Seq detection
c started

d
e
Seq1 Seq2 Detected Resultant Sequence
Detected Detected Futurewiz
www.futurewiz.co.in
OR Operator

 Use or operator when at least one of the sequences


needs to match.

seq1 or seq2

 Following should be true for resultant sequence to


matches:
o seq1 and seq2 should start from same point.
o Resultant sequence matches when either seq1 or
seq2 matches.
o The end point of seq1 and seq2 can be different.
o The end time of resulting sequence will be end time of
last sequence.
Futurewiz
www.futurewiz.co.in
Example

(a ##2 b) or (c ##1 d ##2 e)

clk
a
b
Seq1detecte
d Resultant Sequence
c Detected

d
e
Seq detection started Seq2 detected
Futurewiz
www.futurewiz.co.in
Example

(a or b)

clk

Seq1 Seq2 Detected Resultant Sequence


Detected Detected
Futurewiz
www.futurewiz.co.in
Example

(a ##[2:4] b) or (c ##1 d ##2 e)

clk
a
b
Seq detection started
c

d
e
Seq1 Seq2 Detected Resultant Sequence
Detected Detected Futurewiz
www.futurewiz.co.in
throughout Operator

 Useful for testing a condition that an expression has to


be true throughout the sequence.

expr1 throughout seq1

 Left of throughout cannot be a sequence.

(!c) throughout a ##3 b

Futurewiz
www.futurewiz.co.in
First_match Operator

 first_match operator matches only first of possible


multiple matches for evaluation of sequence.

a ##[2:5] b first_match(a ##[2:5] b)

Equivalent to: Sequence will match only one of


the following options, whichever
(a ##2 b) ||
occurs first
(a ##3 b) || (a ##2 b)
(a ##4 b) || (a ##3 b)
(a ##5 b) (a ##4 b)
(a ##5 b)
Futurewiz
www.futurewiz.co.in
Example

first_match(a ##[2:4] b)

clk

Seq detection Resultant sequence detected


started
Futurewiz
www.futurewiz.co.in
Example

(!c) throughout a ##3


b
clk

Detection Started Assertion Passed Assertion


Failed Futurewiz
www.futurewiz.co.in
within Operator

 Useful for testing a condition where a sequence is


overlapping in part length of another sequence.
seq1 within seq2
 seq1 should happen between start and completion of
seq2.
sequence seq1; sequence seq2;
@(posedge clk) a ##2 b; @(posedge clk) c ##1 !d ##2 e;
endsequence endsequence
property p1;
@(posedge clk) seq1 within seq2;
endproperty
Futurewiz
www.futurewiz.co.in
not Operator

 not operator is used to check that a particular sequence


should not occur.

sequence abc;
a ##1 b ##1 c;
endsequence

property nomatch;
@(posedge clk) start |-> not (abc);
endproperty

Futurewiz
www.futurewiz.co.in
not Operator

 Example c ##1 d should not occur after a ##1 b.

property incorrect;
@(posedge clk) not (a ##1 b |=> c ##1 d);
endproperty

 Will report even if a ##1 b does not occur because of


vacuous pass.

property correct;
@(posedge clk) not(a ##1 b ##1 c ##1 d);
endproperty
Futurewiz
www.futurewiz.co.in
If-else Expression

 It is possible to select property expression based on


some condition using if-else expression.

property test;
@(posedge clk) (req1 || req2) ->
if(req1)
##1 ack1;
else
##1 ack2;
endproperty

Futurewiz
www.futurewiz.co.in
Local Variables

 Local variables can be declared and used inside


property and sequence.

 These are dynamically created inside sequence


instance and removed when end of sequence occurs.

 Each instance of sequence has its own set of variables.

 A local variable is assigned a value using a comma


separated list along with other expressions.

Futurewiz
www.futurewiz.co.in
Example

sequence s1;
int i;
(data_valid, (i = tag_in))
##7 (tag_out == i);
endsequence

Local variable i is assigned a value


of tag_in when data_valid is high. This value is then
checked with the value of tag_out 7 clock ticks later.

Futurewiz
www.futurewiz.co.in
Sample Value Functions

 Special System Functions are available for accessing


sampled values of an expression.
o Functions to access current sampled value.
o Functions to access sampled value in the past.
o Functions to detect changes in sample values.

 Can also be used in procedural code in addition to


assertions.

Futurewiz
www.futurewiz.co.in
$rose, $fell

 $rose(expression [, clocking event])


o Returns true if least significant bit changes to 1 with
respect to value (0, X, Z) at previous clock else false.

 $fell(expression [, clocking event])


o Returns true if least significant bit changes to 0 with
respect to value (1, X, Z) at previous clock else false.

 Clocking event is optional usually derived from clocking


event of assertion block or procedural block.

Futurewiz
www.futurewiz.co.in
$rose vs @(posedge)

 @(posedge signal) returns 1 when signal changes from


(0, X, Z) to 1 or (0 to X) or (0 to Z).

 $rose(signal) is evaluated to true when signal changes


from (0, X, Z) to 1 across two clocking event.

property p1; property p2;


@(posedge clk) a ##2 @(posedge clk) a ##2
b; $rose(b);
endproperty endproperty

Futurewiz
www.futurewiz.co.in
$rose

property p1; property p2;


@(posedge clk) a ##2 @(posedge clk) a ##2
b; $rose(b);
endproperty endproperty

clk

p1 p2 asserted
asserted Futurewiz
www.futurewiz.co.in
$stable, $past

 $stable(expression [, clocking event])


o Returns true if value of expression did not change
from its sampled value in previous clock else false.

 $past(expression [, no of cycles] [, gating expression]


[,clocking event])
o Used to access sampled value of an expression any
number of clock cycles in past.
o no of cycles defaults to 1.
o gating expression for clocking event.
o clocking event inferred from assertion or procedural
block if not specified.
Futurewiz
www.futurewiz.co.in
System Functions and Tasks

 Following System Functions and Tasks are available


that can be used in assertions and procedural blocks:
o $onehot (expression) Returns true if only one bit of
the expression is high.

o $onehot0 (expression) Returns true if at most one bit


of the expression is high.

o $isunknown (expression) Returns true if any bit of the


expression is X or Z.
o $countones (expression) Returns number of one’s in
the expression.
Futurewiz
www.futurewiz.co.in
$asserton, $assertoff, $assertkill

 disable iff can be locally disable assertions.


 $asserton, $assertoff and $assertkill are used to control
assertions of a module or list of instance.
 $asserton, resume execution of assertions, enabled by
default.
 $assertoff, temporarily turns off execution of assertions.
 $assertkill, kills all currently executing assertions.

$asserton(level [, list of modules or instances])

Futurewiz
www.futurewiz.co.in
Properties

 A property is used to define behavior of a design.

 A property can be used for verification as an assumption, a


checker, or a coverage specification.
o assert to specify the property as a checker to ensure that the property holds for the design.
o assume to specify the property as an assumption for the environment.
o cover to monitor the property evaluation for coverage.

 A property can be declared in a module, interface, clocking


block, package or any compilation unit.

 Properties can have formal arguments like sequence


declarations.

Futurewiz
www.futurewiz.co.in
Types of Properties

 Types of Properties
o sequence
o negation
o disjunction
o conjunction
o if..else
o implication
o instantiation

Futurewiz
www.futurewiz.co.in
Sequence

 A property expression may be a simple sequence


expression.

 A sequence as a property expression is valid if the


sequence is not an empty match.

property p1; property p2;


a; a ##1 b ##1 c;
endproperty endproperty

Futurewiz
www.futurewiz.co.in
Negation

 A property is a negation if it has the form


not property_expr

 if property_expr evaluates to true, then not


property_expr evaluates to false, and

 If property_expr evaluates to false, then not


property_expr evaluates to true.

property p3;
@ (posedge clk) not ( a ##1 b ##1 c );
endproperty
Futurewiz
www.futurewiz.co.in
Disjunction (OR)

 A property is a disjunction if it has the form


property_expr1 or property_expr2

 The property evaluates to true if and only if at least one


of property_expr1 and property_expr2 evaluates to true.

property p4;
@ (posedge clk) ( (##[1:3] a) or (b |=> c) );
endproperty

Futurewiz
www.futurewiz.co.in
Conjunction (AND)

 A property is a conjunction if it has the form


property_expr1 and property_expr2

 The property evaluates to true if and only if both


property_expr1 and property_expr2 evaluate to true.

property p4;
@ (posedge clk) ( (##[1:3] b) and (c |=> d) );
endproperty

Futurewiz
www.futurewiz.co.in
If..else

if (expression) property_expr1

o Evaluates to true if expression evaluates false.


o Evaluates to true if expression evaluates true and
property_expr1 also evaluates true.
o Others evaluate to False.

if (expression) property_expr1 else property_expr2

o Evaluates to true if expression evaluates true and


property_expr1 also evaluates true.
o Evaluates to true if expression evaluates false and
property_expr2 evaluates true.
o Others evaluate False.
Futurewiz
www.futurewiz.co.in
Implication

 A property is an implication if it has either the form

o sequence_expr |-> property_expr (overlapping)


o sequence_expr |=> property_expr (non-overlapping)

property p5; property p6;


a |-> b ##1 c; a |=> b ##1 c;
endproperty endproperty

Futurewiz
www.futurewiz.co.in
Instantiation

 An instance of a property can be used inside another


property.
property p1(x,
y);
##1 x |-> y;
endproperty

property p2;
@ (posedge clk)
a ##1 b |->
if(c) p1(d, e);
else f;
endproperty Futurewiz
www.futurewiz.co.in
Recursive Properties

 A property is recursive if its declaration contains an


instance of itself.
property p7(a);
a and (1’b1 |=> p7(a));
endproperty

 a should hold true in current and next clock cycles.

assert property (@ (posedge clk) $fell(reset) |->


p7(b) );
 Assert will make sure that after reset is de-asserted the
signal b holds 1 all the time. Anytime b goes low, error is
asserted. Futurewiz
www.futurewiz.co.in
Recursive Properties

 What if we change above non-overlapping operator to


overlapping operator?

o Gets stuck in an infinite loop recursion in same cycle


resulting in a run-time error. So we need to be careful
while using recursive properties.

Futurewiz
www.futurewiz.co.in
Example

Design Rule : interrupt must hold until interrupt ack is


received.

clk

intr

Assertion
intra Passed

Assertion Failed
intra

Futurewiz
www.futurewiz.co.in
Example

property cond( intr , intra);


intra or (intr and (1’b1 |=> cond( intr,
intra)));
endproperty
 The “and” between intr and the recursive call will make
sure that if intr goes low before intra - the
property/assertion fails.

 The “or” makes sure that property passes when intra


goes high.

Futurewiz
www.futurewiz.co.in
Restriction on Recursive Property

 Operator “not” cannot be used in recursive property


instances.

property incorrect(p);
p and (1’b1 |=> not incorrect(p));
endproperty

Futurewiz
www.futurewiz.co.in
Restriction on Recursive Property

 The operator “disable iff” cannot be used in the


declaration of a recursive property.

property incorrect(p);
disable iff (a)
 Rewrite as p and (1’b1
follows |=> is not recursive.
as legal
incorrect(p));
endproperty

property correct(p); property legal(p);


p and (1’b1 |=> correct(p)); disable iff (b) correct(p));
endproperty endproperty
Futurewiz
www.futurewiz.co.in
Restriction on Recursive Property

 If p is a recursive property, then, in the declaration of


p, every instance of p must occur after a positive
advance in time.

property rec(p);
p and (1’b1 |-> rec(p));
endproperty
 The overlapping operator will make this recursion
stuck in an infinite loop

Futurewiz
www.futurewiz.co.in
Mutual Recursion

 Recursive properties can be mutually recursive.

property chk1;
a|-> b and (1’b1 |=> chk2);
endproperty

property chk2;
c |-> d and (1’b1 |=> chk1);
endproperty

 This is valid as there is time advancement (non-


overlapping implication) and there is an antecedent.

Futurewiz
www.futurewiz.co.in
Labeling Assertions

 Labeling assertions is optional but highly useful for


debugging purpose, always label use meaningfully label.

 Label gets printed during failure and also shows up in


waveform.

 Without label assertions from a module that are


instantiated multiple times will be a nightmare to debug.

ERROR_q_did_not_follow_d:
assert property
( @(posedge clk) disable iff (!rst_n) (q==$past(d)) );

Futurewiz
www.futurewiz.co.in

S-ar putea să vă placă și