Вы находитесь на странице: 1из 201

Intro To SystemVerilog

SystemVerilog for Verification

May 2006
Paul Baleme, Satya Ayyagari
Day One
Welcome

 Welcome to the “Intro to SystemVerilog for


Verification” class
 Requirements
 Some HDL programming experience
 Some Unix experience
 Familiarity with some Unix editor
 Unix account in Folsom, Chandler, Dupont, or
Penang.
 Assumes use of Modelsim.
Intel Confidential 3
Scope Of Course

 Introduction to SystemVerilog for verification


 Hands-on lab assignments
 Students will not be SystemVerilog experts at the
end of this class. Class is an introduction only.
Advanced classes go into more details.
 Next Classes:
 Coverage/Checkers

 How to write a SV Test

 How to write an SV BFM

 Length: 2 days

Intel Confidential 4
Typographic Conventions

Regular Text Course Content

Courier Bold Code examples,


command line
keyboard input

Courier Regular Screen output

Italic Placeholders for data


user should input

Intel Confidential 5
What is SystemVerilog

SystemVerilog is an IEEE extension to the


Verilog language.
SystemVerilog adds testbench features such as
classes, constraints, and temporal
expressions to Verilog.

Intel Confidential 6
Getting More Information

 SystemVerilog LRM
http://www.eda.org/sv/SystemVerilog_3.1a.pdf
 AVC Wiki
http://www-
fmec.fm.intel.com/twiki/bin/view/Chipset/SystemVerilog

 Additional Information
www.accellera.org

Intel Confidential 7
Using SystemVerilog

To setup your environment to use SystemVerilog, type the following at the


unix prompt:
% avc validation svtraining

(some users may have to do the following before the above will work)

% source /usr/users/a2fs/environment/imdenv/alias

Next, create a training directory, and create a work library:


% mkdir svtraining; cd svtraining
% vlib work
% vmap work work

Intel Confidential 8
Hello World

module helloWorld();
initial
begin: hello
$display("Hello World");
end: hello
endmodule: helloWorld

Intel Confidential 9
Compiling SystemVerilog

To compile your program, type the following:


% vlog hello.sv

Note: If you do not name your file ending in .sv,


you must use the –sv option to vlog.
To run your program, use the following
command:
% vsim -c -do "run -all;q -f" helloWorld

Intel Confidential 10
Commenting Your Code

Like C++, SystemVerilog supports two types of


comments
/* Block comments that can span
* multiple lines
*/

// And single line comments

$display(“hello”); // This is a comment

Intel Confidential 11
Lab 1: Hello World

Create a module that prints “Hello World” using


the $display command.

Intel Confidential 12
Basic Data Types
Integer Data Type
shortint 2-state (1, 0), 16 bit signed
int 2-state, 32 bit signed
longint 2-state, 64 bit signed
byte 2-state, 8 bit signed
bit 2-state, user-defined vector size
logic 4-state (1,0,x,z) user-def
reg 4-state user-defined size
integer 4-state, 32 bit signed
time 4-state, 64 bit unsigned

Intel Confidential 14
Signed/Unsigned

 byte, shortint, int, integer and longint defaults


to signed
 Use unsigned to represent unsigned integer value
Example: int unsigned ui;
 bit, reg and logic defaults to unsigned
 To create vectors, use the following syntax:
logic [1:0] L; // Creates 2 bit logic
// vector

Intel Confidential 15
Strings
 string – dynamic allocated array of bytes
 SV provides methods for working with strings

Str1 == Str2 Equality

Str1 != Str2 Inequality

<, <=, >, >= Comparison

{Str1, Str2, … Strn} Concatenation

Str1[index] indexing – return 0 if out


of range
Intel Confidential 16
String Methods

 len  atoi, atohex,


 putc atoct, atobin
 getc  atoreal
 toupper  itoa
 tolower  hextoa
 compare  octtoa
 icompare  bintoa
 substr  realtoa

Intel Confidential 17
Literal Values

 Integer Literal – Same as verilog


 value – unsized decimal value
 size’base value – sized integer in a specific radix
 Ex: 4’b0101; 4’hC; 32’hDEAD_BEEF; 2’b1Z

 Real Literal
 value.value
 Ex: 2.4

 Base Exponent ( E/e)


 Logic Value
 0, 1, [z|Z], [x|X]

Intel Confidential 18
Variable Declarations

 Variable declarations must go at the beginning of a


block. You may not have any statements before a
variable declaration. For example, the following is
illegal:

initial begin
$display(“begin”);
int i;
...
end

Intel Confidential 19
Lab 2: Data Types
Write a top level module that displays the following output.
Use of the following data types:
1. int both signed and unsigned
2. logic
3. string
Hint:
int i, h;
$display(“%d %h”, i, h);
string str; $sformat(str, “%b”, l)
$display(“Logic value in upper case %s”,str.toupper());

Output:
# The integer i is 0x00000014
# The unsigned integer ui is 0xdeadbeef
# The logic L is 1Z
# string str1 is "Hello World"
# string str2 is "Cruel World“

Intel Confidential 20
Operators

Logic Operators
& | ~ ^ ~& ~| ~^ << >>
Arithmetic Operators
+ - % / * ** <<< >>>
Assignment Operators
= += -= *= /= %= &= |= ^= <<= >>= <<<= >>>=
Example:
a += 3;
Equivalent to:
a = a + 3;

Intel Confidential 21
Operators

Auto-increment (++) Auto-decrement(--)


Example:
a = 1; a++;
a now contains 2.
Comparison Operators
== != === !== =?= !?= > < <= >=
Example:
a = 1'bZ; b = 1'bZ;
if (a != b) $display(“Z != Z”);
if (a === b) $display(“Z === Z”);

Intel Confidential 22
Concatenation

The { } operator is used for concatenation.


Example:
s = {“Hello”, “ “, “World”};
v = {32’b1, 32’b10}; // v = 64b vector
Can also be used on left hand side:
{a, b, c} = 3’b111;
Sizes of assignment have to match.
If LHS is smaller then assignment gets
truncated.

Intel Confidential 23
Lab 3: Operators

Write a SystemVerilog module to calculate the


following, and print the result as an integer to
the screen:

(1101001 XOR 11111001) ÷ 5

Ignore remainder.

Intel Confidential 24
Flow Control Constructs

How to go with the flow


SystemVerilog additions

 Verilog includes: if-(else-(if)), case,


forever, repeat, while, for, ?:
(ternary)
 SystemVerilog:
 Enhances for
 Adds do..while, foreach

Intel Confidential 26
if

Verilog ‘if’ expressions


Then branch taken for any nonzero known value of expr (no ‘x’ or
‘z’), equivalent to expr != ‘0’
Chain ‘if’ statements:
if (expr)
begin

end
else if (expr)
begin

end
else
begin

end

Intel Confidential 27
?:

Operator, but conditional


expr ? then_val : else_val
Some call this the “ternary” operator, in the
same vein as “unary” and “binary”, with 3
operands.

Ex: var_m = (x == 1) ? a : b;

Intel Confidential 28
case

 4-value exact matching, runtime evaluation, no


fallthrough, bit length of all expressions padded to
same length
case (expr)
item:
begin
statement
end
item2, item3, item4:
begin
statement
end
default: statement
endcase

Intel Confidential 29
casez, casex

Handle wild cards with either casez or casex


casez: ‘z’ bit in either item or expression will be treated
as a match for that bit
casex: ‘z’ or ‘x’ bits will both match

casex (8’bx100z011 ^ reg_a)


8’b1x1001?1: $display(“x”);
8’b01z10zx1: $display(“y”);
8’b11z01011: $display(“z”);
endcase

Intel Confidential 30
forever

Continuous execution, without end, of body


statement(s)
Used with timing controls
Usually last statement in some block

initial begin: clock_drive


clk = 1’b0;
forever #10 clk = ~clk;
end : clock_drive

Intel Confidential 31
repeat

Repeat a block ‘x’ times, no conditional test


repeat (expr) statement
What happens with expr = ‘x’ or ‘z’?

Example
x = 0;
repeat (16)
begin
$display(“%d”, x++);
end

Intel Confidential 32
while

Executes statement as long as expr evaluates to true


while (expr) statement
Example:
while (reg_i)
begin
something_happens();
reg_i = reg_i – 1;
end

Intel Confidential 33
for

‘C’ inspired for loop


for (initial_assignment; condition; step_assignment)
statement
Equivalent to
begin
initial_assignment;
while (condition)
begin
statement;
step_assignment;
end
end

Intel Confidential 34
Enhanced for

SystemVerilog adds:
Loop variable declaration
Multiple statements in init and step blocks (comma
separated)
++ and -- operators (Mentioned in operator section)

for (int i; i < arr.size(); j+=2, i++) begin


arr[i] += 200;
arrb[i]--;
end

Intel Confidential 35
foreach

Implicit loop variable(s), multiple dimensions, any array type

int arr_x[];
typedef int arr_joe[7:0][3:8]
arr_joe arr_y[$];
int arr_z[0:3*width][8*num-1:0];

initial
begin
arr_x = new[10];
foreach (arr_x[i]) statement
foreach (arr_y[m,n,p]) statement
foreach (arr_z[i,j]) statement
end

Intel Confidential 36
do..while

do statement while (expr);

What’s the difference?


x = 0;
1) while (x)
begin
$display(“%d”, x);
x--;
end
2) do
begin
$display(“%d”, x);
x--;
end
while (x);

Intel Confidential 37
Lab 4: Flow control

Write a SystemVerilog module to display the


first 20 Fibonacci numbers.

Fn = Fn-1 + Fn-2

 Hint: F1 = F2 = 1

Intel Confidential 38
User Defined Types and
Enumerated Types
User Defined Types

SystemVerilog supports a new keyword: typedef

Syntax: typedef <base_data_type> <type_identifier>

typedef int inch ; // inch becomes a new type

inch foot = 12, yard = 36; // these are 2 new variables of type ‘inch’

8-40 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Enumeration
Syntax:
enum [enum_base_type] { enum_name_declaration {,enum_name_declaration} }

enum_base_type: default is int

Enumeration is a useful way of defining abstract variables.


NOTE:
Define an enumeration with “ enum ” Default assigned values start at zero
enum {red, green, yellow} traf_lite1, traf_lite2;
0 1 2
enum {red, green, yellow} lite;
Values can be cast to integer types and auto-incremented
enum { a=5, b, c} vars; // b=6, c=7

A sized constant can be used to set size of the type


enum bit [3:0] { bronze=4’h3, silver, gold} medal; // All medal members are 4-bits

Define a new type


typedef enum {NO, YES} bool; // bool is NOT a SystemVerilog type
bool myvar; // but it just became one 
“myvar” will now be checked for valid values in all
assignments, arguments and relational operators
8-41 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Enumeration example
Modelsim now allows viewing of Example
typedef enum {red, green, blue, yellow,
enum types in
white, black} Colors;
waveforms similar to VHDL enum
types. Colors col_ps;
Colors col_ns;

To use enumerated types in


always @(col_ps)
numerical expressions col_ns = col_ps.next();
the language provides the following
functions: always @(posedge clk)
col_ps <= col_ns;
prev(), next(), first(), last(), num() and
name().

Intel Confidential 42
Casting
Casting
 A data type can be changed by using a cast
(’) operation.
 Syntax: <type>’(<value/expression>)
 Examples:
 int’(2.0 * 3.0)// real to int casting
 7’(x-2)//number of bits to change
size.
 signed(m)//changes m to signed
 inteltype’(2+3)//casting to a user
defined type [inteltype].

Intel Confidential 44
Arrays
Packed/Unpacked Arrays

 In packed arrays [range is on the left side of the


identifier] all elements are glued together and can
be overwritten by zero/sign extension of a single
literal.
 Ex: logic [3:0] m;
m = 4’b1100;
 In unpacked arrays [range is on the right side of the
identifier] each individual element is considered by
itself without any relation to other elements.
 Ex: logic m [5:0];
// each element is only 1-bit deep
 Arrays can have packed and unpacked dimensions.
 Ex: logic [3:0] m [5:0]

Intel Confidential 46
Array Literals and Default
To help in assigning literal values to arrays SV introduces the default keyword:

int k [1:1000] = '{default: 5}; // All elements “5”

For more control, consider the dimensions of the array and use { } to match those
dimensions exactly.

int k [1:3][1:4] = '{'{1,2,3,4},'{5,6,7,8},'{9,10,11,12}}; // 3 groups of 4

int m [1:2][1:3] = '{'{0,1,2},'{3{4}}}; // 2 groups of 3

8-47 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
1st new array in SV, not synthesizable
Dynamic Arrays
Dynamic declaration of one index of an unpacked array

Syntax:
data_type array_name[] ;
Declares a dynamic array array_name of type data_type

data_type array_name[] = new[ array_size ] [(array)] ;


Allocates a new array array_name of type data_type and size array_size
Optionally assigns values of array to array_name
If no value is assigned then element has default value of data_type

Examples:
bit [3:0] nibble[ ]; // Dynamic array of 4-bit vectors
integer mem[ ]; // Dynamic array of integers

int data[ ]; // Declare a dynamic array


data = new[256]; // Create a 256-element array
int addr = new[100]; // Create a 100-element array
addr = new[200](addr); // Create a 200-element array
// preserving previous values in lower 100 addresses
8-48 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Dynamic Arrays – Methods

function int size()


Returns the current size of the array

int addr[ ] = new[256];


int j = addr.size(); // j = 256

function void delete()


Empties array contents and zero-sizes it
Cannot delete selected elements
int addr[ ] = new[256];
addr.delete();

8-49 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Dynamic Array Example
module dyn_arry ();
bit data1 [];
initial
begin
// create a 128 element array
data1 = new [128];
$display("Size of array = %d",
data1.size());
data2 = new[256](data1);
$display("Size of array = %d",
data2.size());
data1.delete();
$display("Size of array = %d",
data1.size());
end
endmodule

Intel Confidential 50
3rd new array in SV, not synthesizable

Queues and Lists


SV has a built-in list mechanism which is ideal for queues, stacks, etc.
A list is basically a variable size array of any SV data type.

int q1[$]; // $ represents the ‘upper’ array boundary


int n, item;

q1 = ‘{ n, q1 }; // uses concatenate syntax to write n to the left end of q1


q1 = ‘{ q1, n }; // uses concatenate syntax to write n to the right end of q1

item = q1[0]; // read leftmost ( first ) item from list


item = q1[$]; // read rightmost ( last ) item from list

n = q1.size; // determine number of items on q1

q1 = q1[1:$]; // delete leftmost ( first ) item of q1


q1 = q1[0:$-1]; // delete rightmost ( last ) item of q1

for (int i=0; i < q1.size; i++) // step through a list using integers (NO POINTERS)
begin … end

q1 = { }; // clear the q1 list

Intel Confidential 51
Queue Methods
size() Returns the number of items in the queue. Prototype:
If the queue is empty, it returns 0. function int size();

insert() Inserts the given item at the specified index position. Prototype:
function void insert (int index, queue_type item);
Q.insert (i, e) => Q = ‘{Q[0:i-1], e, Q[i,$]}

delete() Deletes the item at the specified index position. Prototype:


function void delete (int index);
Q.delete (i) => Q = ‘{Q[0:i-1], Q[i+1,$]}

pop_front() Removes and returns the first element of the queue. Prototype:
function queue_type pop_front();
e = Q.pop_front () => e = Q[0]; Q = Q[1,$]

pop_back() Removes and returns the last element of the queue. Prototype:
function queue_type pop_back();
e = Q.pop_back () => e = Q[$]; Q = Q[0,$-1]

push_front() Inserts the given element at the front of the queue. Prototype:
function void push_front (queue_type item);
Q.push_front (e) => Q = ‘{e, Q}

push_back() Inserts the given element at the end of the queue. Prototype:
function void push_back (queue_type item);
Q.push_back (e) => Q = ‘{Q, e}

Intel Confidential 52
Queue Example
module queues ();
int q [$]; // declare the q

initial
begin: store_disp
// Push elements into the queue
q.push_back(1);
q.push_back(0);
// Display its contents
$display("Size of queue = %0d", q.size());
// Delete the element of queue at index 1
q.delete(1);
// Push to front of the queue
q.push_front (0);
// Display all the contents in the queue
for (int i = 0; i < q.size(); i++)
$display("q[%0d] = %0d", i, q[i]);

end: store_disp

endmodule: queues
Intel Confidential 53
Lab 6: Queues

 Write a SystemVerilog program with


specification as defined in lab6.sv
 The output will look as follows:
# Loading work.lab7
# run –all
# Size of queue = 3
# q[0] = 0
# q[1] = 1
# q[2] = 3
# q -f

Intel Confidential 54
Associative Arrays
 Associative arrays are used when the size of the
array is not known or the data is sparse.
 Syntax:
data_type array_name [index_type];
In other words
value_type array_name [key_type];
 It implements a lookup table of the elements of its
declared type.
 Data type used as an index serves as lookup key
and imposes an order.
 Associative array do not have their storage allocated
until it is used.

Intel Confidential 55
Index Types

 String Index Types


 Ex: int a [string];
a[“joe”] = 21;

 Integer Index Types


 Ex: bit [1:0] a [int];
a[5] = 2’b11;

Intel Confidential 56
Associative Array Methods
Function Use
num() Returns number of entries

delete(<index>) Index for delete optional. When


specified used to delete given index
else whole array.
exists (<index>) Returns 1 if element exists at index
else 0
first (<index>), last (<index>) assigns to the given index variable the
value of the first/last (smallest/largest)
index in the associative array.
It returns 0 if the array is empty, and 1
otherwise.
next (<index>), prev (<index>) finds the entry whose index is
greater/smaller than the given index.

Intel Confidential 57
Associative array methods - Example
module asoc_arry ();
int db [string]; // Define an associative array
initial
begin: test
string s;
db ["joe"] = 21; // store values at indexes of associative array
db ["jill"] = 19;
// Display the size of the associative array
$display("Size of hash = %0d", db.num());
if (db.exists("jill")) // check if index exists and change value
begin
db["jill"] = 25;
end
// print the contents of associative array
if (db.first(s))
do
begin
$display("Name = %s -- Age = %0d", s, db[s]);
end
while (db.next(s));
end: test
endmodule: asoc_arry
Intel Confidential 58
Lab 7: Associative Arrays

1. Define an associate array named 'assoc'


assoc has the following attributes:
INDEX - Name of person
VALUE - Age
2. Make the following entries into assoc
NAME AGE
----------------
John 25
James 30
Jane 24
3. Display the size of the hash using $display statement
4. Check if name Jane exists in the associative array and if it does
change her age to 40.
5. Print the contents of the associative array.

Intel Confidential 59
Procedural Blocks
Triggering sensitivity
 @(<signal>) waits for an edge on <signal> before
executing the next statement
 Edge-sensitive signal detection

 @(posedge clk) – waits for a rising edge clock

 @(negedge rstb) – waits for a falling edge on rs

 wait(<signal>) waits for a condition to become true


before executing the next statement.
 Level-sensitive signal detection

 If the signal is already true, execution continues


without stopping

Intel Confidential 61
Initial Block
 An initial block starts at time 0,
executes exactly once during a Example
simulation, and then does not module stimulus;
execute again. reg a,b;
 If there are multiple initial initial
blocks, each block starts to begin
execute concurrently at time 0. #5 a = 1’b1;
#25 b = 1’b0;
 Each block finishes execution
end
independently of other blocks.
endmodule
 Multiple behavioral statements
must be grouped, typically
using begin and end.

Intel Confidential 62
Always Block

 The always block


statement starts Example
module clock_gen;
evaluating sensitivity bit clock;
list at time 0 and initial
begin
executes statements in
clock = 1’b0;
the always block forever #10 clock = ~clock;
continuously in a end
always @(posedge clk)
looping fashion. begin
 This statement is used <statements>;
end
to model a block of endmodule
activity that is repeated
continuously.
Intel Confidential 63
Final Blocks

 The final block is like an Example


final
initial block, defining a
begin
procedural block of $display("Number of cycles
statements, except that it executed %d",$time/period);
occurs at the end of $display("Final PC = %h",PC);
simulation time and end
executes without delays.
 A final block is typically
used to display statistical
information about the
simulation.

Intel Confidential 64
Lab 8: Procedural Blocks
Create a SystemVerilog module:
1. Define an initial block such that it generate a clock clock time
period = 10ns
NOTE: Need to initialize clock even though the bit data type is
automatically done.
2. Create an always blocks that pushes the value of signal 'clk' into
queue 'q' at positive edge of the clock.
3. Increment 'counter' when always block is triggered
4. When counter reaches 4 call $finish system call
Hint: Use if statement
5. Define a final block to print the size of 'q' at the end of simulation
Hint: Use final blocks

 Output:
# Size of q = 4

Intel Confidential 65
Types of Assignment

Blocking
Nonblocking
Blocking Assignment

Example
 The simulator completes a initial
blocking assignment (=) in begin
one pass [execution and a = 30;
#10;
assignment].
a = 5;
 Execution flow is blocked c = #10 a;
until a given blocking b = 2;
assignment is complete. end
// at time 0
 If there is a time delay on a
a = 30
statement then the next //at time 10
statement will not be a = 5, b = x, c = x
executed until this delay is // at time 20
over. a = 5, b = x, c = 5
// at time 20
a = 5, b = 2, c = 5
Intel Confidential 67
Nonblocking Assignment

 The simulator Example


initial
completes a non-
begin
blocking assignment a = 30;
(<=) in two passes. #10;
 Right-hand side of the a <= 5;
assignment is sampled c <= #10 a;
immediately. b <= 2;
end
 Assignment to the left-
// at time 0
hand side is postponed
a = 30
until other evaluations in
//at time 10
a given simulation time
a = 5, b = 2, c = x
step are complete. // at time 20
a = 5, b = 2, c = 30

Intel Confidential 68
Tasks and Functions
Tasks
SystemVerilog makes a number of extensions to basic Verilog syntax.

automatic tasks allocate memory


dynamically at call time. Default port direction is input

ANSI style portlists


task automatic my_task( input int local_a,
Implied int local_b);
begin…end if (local_a == local_b)
begin Arguments can be ANY
my_task(local_a-1,local_b+1); SV type, even structs, etc.
return; // end ‘this’ copy of task
end
global_a = local_a;
return keyword is supported and
global_b = local_b;
terminates task at that point

endtask

Full recursion is supported (automatic variables/arguments stored on stack)


• Can do concurrent calls
• Can do recursive calls
8-70 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Task usage examples [1]
Example of a static task Example of an automatic task
module task_reentry(); module task_reentry();
task reentry(); task automatic reentry();
int counter; int counter;
counter++; counter++;
counter++; counter++;
counter++; counter++;
counter++; counter++;
counter++; counter++;
$display("Value of counter = %0d", $display("Value of counter = %0d",
counter); counter);
endtask endtask

initial initial
begin begin
reentry(); reentry();
reentry(); reentry();
reentry(); reentry();
reentry(); reentry();
end end
endmodule: task_reentry endmodule: task_reentry

What will be the value of counter for each What will be the value of counter for each
call to reentry()? call to reentry()?
Intel Confidential 71
Task usage examples [2]
module task_function ();
int i, j, z;

initial
begin
i = 5;
j = 3;
end
initial
begin
#10;
tsk (i, z, j);
$display("Z = %0d, J = %0d", z, j); // prints Z = 50, J = 4
end

task tsk (input int t1, output int t2, inout int t3);
t2 = 10 * t1;
t3++;
endtask: tsk
endmodule

Intel Confidential 72
Functions

automatic functions allocate memory


dynamically at call time (full recursion). Default port direction is input (also supports output)

ANSI style portlists


function automatic int factorial (int n);
Implied if (n==0) return(1); // factorial 0 is 1
else return(factorial(n-1)*n); Arguments and return type
begin…end
endfunction can be ANY SV type,
even complex structs, etc.

return(value) is supported and


terminates function at that point

function void inverta();


a = !a
endfunction
Return type of void Recommended style (instead of writing a task)
reg a; means no return value! to guarantee a task executes with 0 delay.

initial
inverta(); // function called like a task
End
8-73 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Function usage examples

Example 1 Example 2
function void show_packet(); typedef enum {FALSE, TRUE} bool;
bool cache_range;
$display("=================="); function bool is_cache_range ();
$display("Packet Type = %s", if (addr > 0 & addr < 10)
context_name); begin
$display("Address = %h", addr); cache_range = TRUE;
$display("Data = %h", data); $display("addr in cache
range = %d", addr);
$display("==================="); return TRUE;
endfunction end
else begin
cache_range = FALSE;
return FALSE;
end
endfunction

Intel Confidential 74
Task and Functions Usage - Summary
 Tasks
 Tasks can enable other tasks and functions
 Tasks may execute in non-zero simulation time.
 Tasks may have zero or more arguments of type input, output
and inout.
 Functions
 Function can enable other functions only. Task cannot be called
from functions.
 Functions should execute in zero simulation time.
 Functions have only one return value but SystemVerilog also
allows functions to have input, output or inout types.
 Both tasks and functions support passing arguments by
reference. By default arguments are passed by value. [Pass by
reference not supported in Modelsim 6.1]

Intel Confidential 75
Task and function argument passing

 Passing by value is the Example


default mechanism for function int val
(byte m [3:0]);
passing arguments. <function body>;
 Copies arguments passed endfunction
into subroutine area. // a local copy of ‘m’ is
// created when ‘val’ is
 Changes to arguments in
// called.
subroutine are not visible
outside.
 When defined as automatic,
each copy retains a local
copy of argument.

Intel Confidential 76
Default argument values – Tasks/Functions

 SV allows a subroutine Example


declaration to specify task read (int j =0,
default value for each int k,int data = 1);
argument. endtask
 When subroutine is called, // task can be called using
arguments with default // following default arguments
values can be omitted from read (, 5);
the call and corresponding // equivalent: read (0, 5, 1)
default values are used. read (2, 5);
// equivalent: read (2, 5, 1)
 BKM: Default arguments
read ();
should be optional // error since k has no default
arguments and should be // value
the final set of arguments.

Intel Confidential 77
Lab 9a
 Create a SystemVerilog module as described
below:
1. Define a queue 'q' of string type.
2. Define a named initial block "store_info"
3. Store the following values into the queue
1. index =0, str = "Intel Chandler"
2. index =1, str = "Intel Folsom"
4. Display the size of the queue.
5. Define a function named "change_str" which does the following:
1. Takes queue and index ‘i’ as input
2. changes the value of str stored in queue at index i to "Intel Ireland“.
3. returns the value of 1 indicating success.
6. Call the change_str function, passing q and the value 1 for the index so
that “Intel Folsom” is changed to “Intel Ireland”.

Intel Confidential 78
Lab 9b
6. Define a task named “show" which does the following:
1. Takes queue and return value from "change_str" as inputs
2. The default inital value [task input argument: ret_value] shall be
set to 0.
3. When the return value from "change_str" function is 1, prints the
elements stored in the queue using the following format:
q[%0d] = %s"
7. Notes: "change_str" and “show" are called from named initial
block "store_info".

 Output:
# Loading work.lab9
# run –all
# Size of storage q = 2
# q[0] = Intel Chandler
# q[1] = Intel Ireland
# q -f

Intel Confidential 79
Hierarchy

Who comes first


Modules

The basic hardware unit in Verilog.


Hierarchy of design
Ports represent communication

Inout

Inputs
Outputs
Module

Intel Confidential 81
Ports

Connections
Direction – input, output, inout
Type – wire, bit, logic, user-defined, etc.
Examples:
input bit[3:0] x, y, z;
input bit w[3:0];
output logic q;
inout logic s;
input int x;
output reg r;

Intel Confidential 82
Module syntax Example
module cpu
(inout logic[63:0] data,
output logic[63:0] addr,
module x (port_list); output logic w_or_rb
module_body );
endmodule : x initial
begin : place_holder
Instantiation $display(“A NOTHING CPU”);
x x1 (port_binding_list); end : place_holder
endmodule : cpu

// Error prone
cpu cpu_inst1(addr, data, w_or_rb);
// Better
cpu cpu_inst2(.addr(addr),
.data(data),
.w_or_rb(w_or_rb)
);
// Newer
cpu cpu_inst3( .* );

Intel Confidential 83
Parameters

Generic parameters (ala VHDL generics)


Elaboration time constants
Separate “ports” on a module
Example
module xyz
#(parameter int width = 8)
(input x[width-1:0], output y));
assign y[width-1:0] = x[width-1:0]^ 8’hAE;
endmodule
xyz #(.width(14)) xyz1 (.x(inp), .y(outp));

Intel Confidential 84
Multiple drivers

 Most nets have only one driver


 Nets with multiple drivers need to have a
resolution function
 In SystemVerilog there is a wire type that
includes a resolution function
Example
wire x;
dut dut1(.outp(x));
dut dut2(.outp(x));

Intel Confidential 85
Interfaces
Great coding efficiency can be achieved by modeling the blocks of a system at different
levels of abstraction, behavioral, rtl, gate, etc.
In Verilog, the I/O between these blocks has always remained at the lowest “wire” level.
High-performance system-level simulation requires the abstraction of inter-block
communication.
module mmu(d, a, rw_, en); interface interf;
output [15:0] a; logic [7:0] data;
output rw_, en; logic [15:0] addr;
data inout [7:0] d; logic ena, rw_;
... endinterface
addr endmodule
ad adr
MMU rw_ MEM module mmu(interf io);
module mem(d, a, rw_, en); io.addr <= ad;
ena
input [15:0] a; ...
input rw_, en; endmodule
inout [7:0] d;
interface ... module mem(interf io);
endmodule Traditional adr = io.addr;
Verilog ...
module system; endmodule SystemVerilog
At it’s simplest wire [7:0] data;
an interface is wire [15:0] addr; module system;
like a module wire ena, rw_; interf i1;
mmu U1 (i1);
for ports/wires mmu U1 (data, addr, rw_, ena); mem U2 (i1);
mem U2 (data, addr, rw_, ena); endmodule
endmodule

8-86 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
IO Abstraction
source sink
reg a; a a Traditional Verilog approach
a if ( a == 1) • Simple netlist-level IO
… • source/sink can be abstracted
a = 0;
but IO must stay at low level
• IO operations are cumbersome

source interface intf sink


Simple “bundle” interface
intf.a = 0; a reg a; if ( intf.a == 1) • All accesses are through interface
… • Simplifies source/sink declarations

Enhanced interface with methods


source interface intf sink • source/sink only call methods
• source/sink don’t see low-level
a reg a;
intf.wrt_a(0); if (intf.rd_a() == 1) “details” like variables/structure, etc.
task wrt_a(); • Easy to swap interface abstractions
task rd_a(); without any effect on source/sink
8-87 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Interface Characteristics

• Interfaces bring abstraction-level enhancements to ports, not just


internals.

• An interface may contain any legal SystemVerilog code except


module definitions and/or instances. This includes tasks, functions,
initial/always blocks, parameters, etc.

• Bus timing, pipelining, etc. may be captured in an interface rather


than the connecting modules.

• Interfaces are defined once and used widely, so it simplifies design.


e.g. Changing a bus spec (add a new signal?) means editing the
interface only.

• Interfaces are synthesizable.

8-88 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Interface in hierarchy

 Interfaces appear as
normal module
instantiations in design
hierarchy.
 At the moment,
interfaces cannot be
instantiated in VHDL
blocks.
Interface instances
interface name: bfm_interface
Instantiated twice: bi1, bi2

Intel Confidential 89
Example
modport interface i2;
wire a, b, c, d;
modport master (input a, b,
output c, d);
modport slave (output a, b,
 Different users of input c, d);
interface need endinterface : i2

different views module m (i2.master itf);


 Master/Slave …
endmodule: m
 Restrict access to
module s (i2.slave itf);
internal interface …
signals endmodule: s

 Protect module top();


implementation i2 i();
signals from
m u1(.itf(i.master));
corruption s u2(.itf(i.slave));
endmodule: top

Intel Confidential 90
Lab 10

Create modules moda and modb.


moda has an input named a, and an output
named b
modb has an input named b, and an output
named a
Use an interface to connect

Intel Confidential 91
Clocking blocks

Synchronous blocks can have race conditions


when all trying to evaluate blocks in same
time step
Clocking blocks capture timing and
synchronization requirements

Intel Confidential 92
Clocking block syntax

clocking block_name clocking_event;


item list;
endclocking : block_name

clocking bus @(posedge clock1);


default input #10ns output #2ns;
input data, ready,
enable=top.mem1.enable;
output negedge ack;
input #1 addr;
endclocking

Intel Confidential 93
Program Blocks

A program block is similar to a module. It is used for


testbench code.
program helloWorld();
initial
begin: hello
$display("Hello World");
end

initial
begin: there
$display(“Hello There”);
end
endprogram: helloWorld

Intel Confidential 94
Program Blocks

Programs can be instantiated inside modules,


but not the other way around.
Program blocks may contain one or more initial
blocks, but may not contain always, UDPs,
modules, interfaces, or other programs.
Programs may be explicitly exited using the
$exit task.
When all program blocks complete the
simulation ends.

Intel Confidential 95
Day Two
Classes

SystemVerilog and Object


Oriented Programming

Testbench Only
Object Oriented Primer
A Class is a description of some group of things that
have something in common.
Objects are individual instances of “classes”.
 Example: A class might be “Automobile”. Instances of the
“Automobile” class might be “Joe’s car”, “Bob’s car”,
“Sally’s truck”, etc.
Objects/Classes have:
 Data/Properties
 Color, speed, direction, etc.
 Operations/Methods
Start, stop, increaseSpeed, turn, etc.

Encapsulation:
 Encapsulate implementation details internal to the
object/class.

Intel Confidential 98
Classes
Inheritance: (is-a relationship)
 Allows users to extend existing classes, making minor
modifications. Extending the “Automobile” class example,
users might create subclasses for “sedan”, “truck”, “van”,
etc. The “van” class might also have a “minivan” subclass.
Etc. In these cases, the subclass IS-A superclass. i.e. a
“sedan” is a “Automobile”.
 When using inheritance, the sub-class “inherits” all the
parents public/protected data properties and methods. It is
allowed to override them, or use them as-is.
Composition: (has-a relationship)
 Composition is used for the case where one object HAS-A
instance of another class. For example, an “Automobile”
class might have 4 instances of a “wheel” class. In this
case, a wheel is not an “Automobile”, so inheritance should
not be used.

Intel Confidential 99
Classes

Polymorphism:
 Most common definition of polymorphism is the ability of
the language to process objects differently depending on
their data type or class. SystemVerilog can only process
objects differently depending on their class.

Intel Confidential 100


Class Format
class classname [extends superclass];
property declarations;

constructor;

methods;

endclass: classname

Intel Confidential 101


Example Class
class myPacket extends BasePacket; // inheritance
byte data[$];
bit [3:0] command;

function new();
super.new();
command = IDLE;
data = ’{1,2,3,4};
endfunction: new

virtual task myTask(input byte a, output byte b);


#10;
b = a + 5;
endtask: myTask;

virtual function integer myFunc(int b);


return(b – 3);
endfunction: myFunc
endclass: myPacket

Intel Confidential 102


Referencing Properties and Methods

Instance data properties and methods may be


referenced/called using the “.” operator.

myClass c;

c = new;
c.property1 = 10;
c.property2 = 11;
c.task1();
c.function1();

Intel Confidential 103


Constructors
Example constructor
function new();
command = IDLE;
data = {1,2,3,4};
endfunction: new

// Creating an instance invokes the constructor:


myInstance = new;

Constructors may take arguments.


function new(int a = 0, bit[12:0] addr = 0);

endfunction: new

When extending a class constructor, call super.new().


function new();
super.new();

endfunction: new
Only one constructor per class allowed.

Intel Confidential 104


this
The special variable this is a predefined object handle
for the current object instance. It is optional, since
the current instance is assumed if no variable is
specified.
class myPacket extends BasePacket;
int x, y, z;

virtual function integer myFunc();


x = y + z;
// Equivalent: this.x = this.y + this.z;

myOtherMethod();
// Equivalent to: this.myOtherMethod();
endfunction: myFunc
endclass: myPacket

Intel Confidential 105


Static Properties
Static properties/data members are “static” to
all instances of the class. This means that all
instances share the same value of this
variable. If one instance changes the value,
it changes the value for all instances.
class StaticExample;
static int staticProperty = 0;

virtual function void showStaticProperty();


$display(“Current value: %d”,staticProperty);
endfunction: showStaticProperty

virtual function void setStaticProperty(int val);


staticProperty = val;
endfunction: setStaticProperty
endclass: StaticExample

Intel Confidential 106


Static Methods

Static methods do not require an instance of


the class to operate on. Static methods may
only modify static properties. To invoke a
static method, use Classname::methodName
class StaticExample;
static int staticProperty = 0;

static function void staticMethod();



endfunction: staticMethod
endclass: StaticExample

StaticExample::staticMethod();

Intel Confidential 107


class BaseClass;
virtual function in myFunc(int b);
Polymorphism return(b + 10);
endfunction myFunc
endclass: BaseClass
class myFirstClass extends BaseClass;
virtual function int myFunc(int b);
Instances of subclasses return(b – 3);
may be assigned to endfunction: myFunc
variables declared of endclass: myFirstClass
the superclass type. class mySecondClass extends BaseClass;
This is useful for cases virtual function int myFunc(int b);
return(b + 3);
where the general endfunction: myFunc
algorithm is the same endclass: mySecondClass
for all the subclasses,
but only a few details BaseClass bc;
need to change. myFirstClass fc;
If the subclass overrides mySecondClass sc;
a method specified in fc = new;
the superclass, the bc = fc;
method defined in the $display(“What do I print? %d”
class of the object ,bc.myFunc(6));
instance is called. sc = new;
bc = sc;
$display(“What do I print? %d”
,bc.myFunc(6));
Intel Confidential 108
Data Hiding and Encapsulation

To make data members visible only to the


class, use the local keyword.
class myPacket extends BasePacket;
local int x;

To make data members visible only to the


class, or any subclasses, use the protected
keyword.
class myPacket extends BasePacket;
protected int x;

Intel Confidential 109


Constant Class Properties

The const keyword may be used to make class properties


unchangeable. const constants are different from
`define constants because the initial value may be
determined at runtime, and may be different per class
instance.
class myPacket extends BasePacket;
const int size; // Assignment of constant value in
// declaration makes it constant

function new(int id);


size = id * 4096; // Single assignment in
// constructor OK


Intel Confidential 110
Abstract Classes

The pure virtual keyword may be used on a


class to make the class “abstract”. An
abstract class may not be instantiated. Users
must subclass the abstract class to create
instances of the class.
pure virtual class BasePacket;

Intel Confidential 111


Typedef Class and Forward References

Sometimes it is necessary to use a class before it has


been defined. To do this, you can use a typedef
forward reference, then later define the class.
Example:
typedef class C2; // Forward declaration of C2
class C1;
C2 c2Instance;

endclass: C1
class C2;
C1 c1Instance;

endclass: C2

Intel Confidential 112


Lab 11a: Classes
Create an “Xaction” class. The Xaction class should have the following
Properties:
byte data[$]; // Queue of bytes
int length; // Length in bytes
Methods:
// Sets data to value passed and
// length to the size of queue passed.
setData(byte d[$]);

// Returns formatted representation of


// xaction. Format should be:
// Len=X, Data=0xXXXXXXXX
string toString();
Hint: $sformat(str,"Len=%d, DATA=0x%h",length,data);

Using your new class, run the following test code.


Xaction x;

x = new;
x.setData(’{1,2,3,4,5,6,7,8});
$display(“%s”,x.toString());

Intel Confidential 113


Lab 11b: Classes
Modify lab10a and create a subclass of the Xaction class that has the following
property added:
int iws; // Initiator wait states
Add a task to the class that waits for the number of time steps specified in iws:
// Wait IWS time steps
stall();
Override the toString() method, add printing the iws value. Be sure to use
super.toString, and not reimplement the toString of the parent class:
// Len=X, Data=0xXXXXXXXX, IWS=X
Execute the following testcode.
Xaction x;
SubXaction s;

s = new;
s.iws = 10;
$display(“current time = %t”,$time);
s.stall();
$display(“current time = %t”,$time);

x = s;
x.setData(’{5,6,7,8});
$display(“%s”,x.toString());

Intel Confidential 114


Virtual Interfaces

 Classes cannot have modules or interfaces, need a


specialized mechanism
 Virtual interfaces provide a mechanism for
separating test programs/BFM models from the
actual signals.
 Virtual interfaces let BFM models manipulate virtual
set of signals instead of actual RTL signals.
 Virtual interface is a variable that represents an
interface instance.
 Syntax:
virtual <interface type>
<variable name>;
Intel Confidential 115
Virtual Interfaces Example
// interface class BFM;
// definition virtual Bus bus;
interface Bus Xaction xaction;
(input logic clk);
bit req; function new (virtual Bus b);
bit grant; // need to initialize virtual interface
logic [7:0] addr; // in constructor
logic [7:0] data; bus = b;
endinterface: Bus xaction = new;
endfunction
// testbench
// interface instance task req_bus();
Bus infc_b (clk); @(posedge bus.clk);
// dut instance bus.req <= 1'b1;
dut dut1 (infc_b, clk);
$display("Req = %b @ %0t",
// class instance bus.req, $time);
BFM mybfm =
endtask: req_bus
new
(infc_b); endclass: BFM
Intel Confidential 116
Random Constraints

How to decide how random to be


Random data sources

Random exercise of stimulus allows easy


cases to be done easily
Ability to “tune” random stimulus usually gives
more coverage with less work (be careful)
Save the hard cases until the Design Under
Test (DUT) is healthier
Works hand-in-hand with functional coverage

Intel Confidential 118


Simplest randomness

$urandom system tasks


$urandom() is SV, thread stable, deterministic
$urandom returns unsigned 32-bit integers
Procedural call can be inserted wherever
needed

Intel Confidential 119


More sophisticated mechanisms

Random variables (rand modifier – classes only)


Must be properties of a class, except for some
explicit randomization
Select new random value each time
“.randomize()” is called
Example:
class x;
rand int a, b, c;
endclass : x
x x_inst = new;
initial
begin : random_loop
forever @(posedge clk) x_inst.randomize();
end : random_loop

Intel Confidential 120


What’s ‘randc’ for?

Exhaustive permutations of a variable


‘c’ is for “cyclic”, every value of the variable will
be reached before any value is duplicated

Intel Confidential 121


Constraints

Set of Boolean algebraic expressions


Relationships between random variables and:
Other random variables
Non-random state variables
Example:
constraint a_le_b { a <= b; }
constraint c_eq_10 {c == 10;}
constraint b_in_range { b >= 2 && b <= 8; }
constraint all_gt_0 {a > 0; b > 0; c > 0;}
How many permutations are now possible?

Intel Confidential 122


Constraints

Restrict range of possible values


Can use state variables to restrict range of
random variables
Example:
int x[7] = ’{3,5,6,27,10,42,1};
int z = ’hff, w = 10;
constraint c_within_set_of_x { c inside x; }
constraint b_between_w_z { b <= z && b >= w; }

Intel Confidential 123


Conflicting constraints
What happens when you impose constraints
that conflict in some way?
Example:
constraint x_gt_y { x > y; }
constraint y_gt_z { y > z; }
constraint z_gt_x { z > x; }

if ( x_inst.randomize() == 0 ) // Solver error
begin

end

Modelsim cmdline setting


-solvefaildebug
Intel Confidential 124
Constraint operators

Any Verilog boolean expression


i.e. x < y+b-c*10>>20
Other constraint operations
set membership within
implication -> or if…else…
iterative constraint foreach
variable ordering solve … before …
functions func_x()

Intel Confidential 125


Implication constraint

Uses one boolean to decide if another


constraint must hold
(trans_size == SMALL) -> (length < 10)
(trans_size == MED) ->
(length >= 10 && length <= 100)
(trans_size == LARGE) -> (length > 100)

Advanced note:
a -> b is equivalent to !a || b

Intel Confidential 126


Loop/array constraints

Constrain every element of an array in some


fashion, including reference to other elements of
array
constraint c1 {
foreach ( A[i] )
A[i] inside {2, 4, 6, 8, 10};
}
constraint c2 {
foreach ( A[k] )
(k < A.size-1) -> A[k+1] > A[k];
}

Intel Confidential 127


Arguments to .randomize()

 Normal form of .randomize()


 No arguments, randomize class members according to
declaration modifiers
 Optional arguments
 Specify the variables which are random
 Can make ‘rand’ override declaration type for this call
 Declares entire set of random variables for this run of
Constraint Solver
 ‘null’ argument forces checking constraints only
 Cannot change ‘randc’ to ‘rand’

Intel Confidential 128


.randomize with {}

 Specify inline constraints that are added to


constraint set to solve

trans.randomize() with { x < 100; z > buzz; };

Intel Confidential 129


Distribution Constraints
 Operators: := :/ dist
 Example:
constraint twsConstraint
{
tws dist
{
[0:2] :/ 10,
[3:9] :/ 1,
[10:50] :/ 9
};
}
constraint distConstraint
{
cmd dist
{
mem_write := 10,
mem_read := 5,
lrw := 1,
lrrww := 1,
io_read := 1,
io_write := 1,
idle := 1
};
}
Intel Confidential 130
Putting it all together
module test_rand;
typedef enum {SM, MED, LRG} trans_len;
class transaction {
rand bit [19:0] addr;
rand trans_len len;
rand bit [3:0] byte_len;
rand bit wr_or_rd_b;

constraint c1 { wr_or_rd_b -> len != LRG; }


constraint c2 { (len == SM) -> (byte_len <= 4); }
constraint c3 { (len == MED) -> (byte_len > 4 && byte_len <= 8);}
constraint c4 { (len == LRG) -> (byte_len > 8); }
// Mem above 16-bit is write-only IO devices
constraint c5 { (!wr_or_rd_b) -> (addr[19:16] != 0); }
constraint c6 { solve len before byte_len; }

virtual function string toString()


return sformat(“%5H: %s %d bytes”, addr, (wr_or_rd_b ? “WR” : “RD”),
byte_len);
endfunction : toString
endclass : transaction
<CONTINUED>

Intel Confidential 131


Putting it all together (cont)
initial
begin : test_body
transaction trans;
int counter = 0;

trans = new;
repeat (20)
begin : rand_gen
if (trans.randomize() == 0)
begin
$display(“ERROR: Random constraints
conflict”);
$finish;
end
$display(“%d: %s”, counter++, trans.toString());
end : rand_gen
end : test_body

endmodule : test_rand

Intel Confidential 132


Lab 12: Random Constraints
Modify the Xaction class created in lab11 and make all properties
rand.
1. Add a rand property named size, with the following enumerated
values: SMALL, MEDIUM, LARGE.
2. Add a distribution constraint that make the size:
SMALL 70%, MEDIUM 20%, LARGE 10%.
3. Add a constraint that sets the length based on the size
property:
SMALL : (length <= 10)
MEDIUM : (length >10) && (length <=20)
LARGE : (length > 20) && (length < 100)
(Note: Add a constraint saying the length must be > 0)
4. Write a loop that calls randomize() 40 times, printing the return
value of the toString() method after each randomize() call.
NOTE: use “solve size before length;” to ensure size is solved
before length.

Intel Confidential 133


Packages

 A mechanism for sharing parameters, data,


types, tasks, functions, classes, sequences,
and properties among modules, interfaces
and programs

Intel Confidential 134


Package Search Order Rules
package p;
typedef enum {FALSE, TRUE} BOOL;
BOOL c = TRUE;
endpackage

u = p::c, y = p::TRUE A qualified package identifier is visible


in any scope

import p::*; All declarations inside package p


y = FALSE; become potentially directly visible in
the importing scope:
- c, BOOL, FALSE, TRUE
import p::c The importing identifiers become
if ( ! c ) … directly visible in the importing scope:
-c

Intel Confidential 135


Package Example

 keyword module top;


 package … endpackage
import p::*;
Example:
package p; BOOL b = TRUE;
endmodule
class Data;
int a; OR
int b; module top;
endclass
p::BOOL b = p::TRUE;
typedef enum {FALSE, TRUE}
BOOL; endmodule

endpackage : p

Intel Confidential 136


Lab 13: Packages

Create two packages (one named p, the other


named q) which contains an int C and C is
initialized with two different values.

Write a top level module that prints out both C


values

Intel Confidential 137


System Tasks
Display

 $display – printf-ish, with “\n” implied


 $display (format_string, arguments);
 $write – printf-ish ($display w/out newline)
 $sformat – print formatted string (ala sprintf)
 $monitor – Implicit task to call $display any time
arguments change, only one $monitor active

Intel Confidential 139


Time

 $time – Returns 64-bit time normalized to


unit timescale, most common for error
messages
 $realtime – floating point scaled to
timescale
 $stime – least significant 32-bits of time

Intel Confidential 140


Simulation Control

$finish – end simulation (quit simulator), final blocks


$stop – halt simulation
$exit – quit execution of program block (SV-only)
Example
initial
#10000 $finish();
initial
@(posedge all_bfms_done) $finish();

Intel Confidential 141


File I/O

integer fd = $fopen(string filename, string mode)


char c = $fgetc(int fd);
int code = $ungetc(char c, int fd);
integer code = $fgets(string str, int fd);
integer code = $fscanf(int fd, FORMAT, args);
integer code = $sscanf(string str, FORMAT, args);
Example
string buf_s;
in_fd = $fopen(“input_file”, “r”);
out_fd = $fopen(“output_file”, “w”);
chars_read = $fgets(buf_s, in_fd);
if (chars_read == 0)
begin
$display(“End of file”);
$finish();
end
if (2==$sscanf(buf_s, "%x %x", hexStartAddr, hexEndAddr) )
begin
$display(“Address Range: %8x -> %8x”, hexStartAddr, hexEndAddr);
end

Intel Confidential 142


File I/O

$fclose $fopen
$fdisplay $fstrobe
$fdisplayb $fstrobeb
$fdisplayh $fstrobeh
$fdisplayo $fstrobeo
$fgetc $ungetc
$fflush $ferror
$fgets $rewind
$fmonitor $fwrite
$fmonitorb $fwriteb
$fmonitorh $fwriteh
$fmonitoro $fwriteo
$readmemb $readmemh
$swrite $swriteb
$swriteo $swriteh
$sformat $sdf_annotate
$fscanf $sscanf
$fread $ftell
$fseek

Intel Confidential 143


Random functions

$random

$dist_chi_square $dist_erlang
$dist_exponential $dist_normal
$dist_poisson $dist_t
$dist_uniform

Intel Confidential 144


Named blocks

 Blocks can be provided Example


names. By providing blocks …
with names provides the always @(CK or D)
following advantages: begin : latch_counter
 Declaration of local int count;
variables. if (CK)
 Named blocks are part of count = count + 1;
the design hierarchy. begin
 Local variables declared O = D ;
can be accessed through end
hierarchical referencing. end : latch_counter

Intel Confidential 145


Threads
Sequential Blocks
 There is the difference Example
between a sequential begin
#5 a = 1;
and a concurrent block: #5 a = 2;
 Simulator executes #5 a = 3;
statements in a sequential end
block in sequence
 It finishes the current
statement, then begins the
next
 You always know the order
in which it actually executes
the statements
 The simulator exits the
block after finishing the last
statement

Intel Confidential 147


Concurrent Blocks

 The simulator executes Example


statements in a concurrent fork
block in parallel begin
 It starts executing all $display( "First Block\n" );
statements simultaneously # 20ns;
 You can not know the order in end
which it actually executes begin
statements scheduled for the $display( "Second Block\n" );
same simulation time @eventA;
 The simulator exits the block end
after finishing the latest join
statement.
 A return statement in the
context of fork..join is illegal.

Intel Confidential 148


Dynamic Processes
Inspired by the need for software verification environments to dynamically start
and stop threads, SystemVerilog defines 2 new special cases of fork…join with
associated keywords join_any & join_none

join_any join_none

begin NOTE
fork
fork Child processes spawned by

other blocks continue … a fork…join_none do not start
… as dynamic threads join_none // no waiting at all to execute until the parent

@(sig1); process hits a blocking
join_any // any block finished end statement

8-149 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Q
Process Control – Wait Fork 6.1

With Dynamic processes SystemVerilog needed to provide more global


detection that spawned processes have completed.

The wait fork statement is used to ensure that all child processes (spawned by
the process where it is called) have completed execution.

begin
fork
task1();
task2();
join_any // continue when either task completes

fork
task3();
task4();
join_none // continue regardless

wait fork; // block until tasks 1-4 complete


end

8-150 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Q
Process Control – Disable Fork 6.1

The disable fork statement terminates all active child processes of the
process where it is called. Termination is recursive, in other words it terminates
child processes, grandchild processes, etc.

task run_tests;
fork
simul_test1;
simul_test2;
join
endtask

task test_with_timeout;
fork
run_tests(); // 2 child tasks spawned in parallel, first to finish triggers join_any
timeout( 1000 );
join_any
disable fork; // Kills the slower task (including any grandchild processes and so on)
endtask

8-151 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Events Trigger Types [1]
 Triggering an event module event_testing ();
 Named events are triggered event a, b;
bit clk;
using -> operator.
always @(posedge clk)
 Triggering an event -> a;
unblocks all processes always @(negedge clk)
currently waiting on the -> b;
event. initial
 Event can be visualized in begin
clk = 1'b0;
wave window.
forever #10 clk = !clk ;
end
endmodule

Intel Confidential 152


Waiting for an event

 @ is used to wait for an Example


module event_testing ();
event. event a, b, c;
 The @ operator blocks bit clk;
always @(posedge clk)
the calling process until -> a;
the given event is always @(negedge clk)
-> b;
triggered. always @(a or b)
-> c;
initial
begin
clk = 1'b0;
forever #10 clk = !clk ;
end
endmodule

Intel Confidential 153


Event Sequencing: wait_order()

 wait_order construct Example


bit success;
suspends the calling wait_order (a, b, c)
process until all success = 1;
specified events are else
success = 0;
triggered in the given
order [left to right]. // event must occur in the
// following order
 If any events are // ->a ->b ->c if not it fails.
triggered out of order
then it causes a fail of
the operation.

Intel Confidential 154


Event Variables [1]

 Merging Events Example


event a, b;
 When one event variable
is assigned to another, a = b;
both merge into one -> a; // also triggers b
event variable. -> b; // also triggers a
 Executing -> on either
one of the events affects
processes waiting on
either event variable.

Intel Confidential 155


Event Variables [2]

 Reclaiming Events Example


event E1 = null;
 When an event variable
is assigned the special
null value, the
association between the
event variable and the
underlying
synchronization queue is
broken.

Intel Confidential 156


Event Variables [3]

 Event Comparison Example


event E1, E2;
 Event variables can be if ( E1 )
compared against other // same as if ( E1 != null )
event variables or the E1 = E2;
special value null. if ( E1 == E2 )
$display( "E1 and E2 are the
 Equality (==) with same event" );
another event or with
null.
 Inequality (!=) with
another event or with
null.

Intel Confidential 157


Semaphores

 Can be described as counters used to control


access to shared resources by multiple
processes [threads].
Printer1
Printer1
[1]
[0]
Print
manager
Printer2
[1]
3 keys
2 keys
Printer3
[1]

Intel Confidential 158


Semaphore Methods

 Semaphore provides following built-in


methods:

Method Use
new() Create a semaphore with
specified number of keys.
put() Return one or more keys
back.
get() Obtain one or more keys.

try_get() Try to get one or more keys


without blocking.

Intel Confidential 159


Semaphore example
module semaphore_test (); initial
semaphore spr = new(2); begin:init2
#5 spr.get(2);
initial $display(" inital2 takes 2
begin:init1 keys at %0t",$time);
#1 spr.get(1); #5 spr.put(1);
$display("initial1 takes $display(" inital2 returns
1 key at %0t", $time); 1 key at %0t",$time);
#6 spr.put(1); end
$display("initial1 returns endmodule: semaphore_test
1 key at %0t",$time);
#1 spr.get(1);
$display("initial1 takes 1
key at %0t", $time);
end
Output:
# initial1 takes 1 key at 1
# initial1 returns 1 key at 7
# inital2 takes 2 keys at 7
# inital2 returns 1 key at 12
# initial1 takes 1 key at 12
# q -f
Intel Confidential 160
Mailboxes
 Mailbox is a communication mechanism that
allows messages to be exchanged between
different processes.

Process 1 Process 2

Intel Confidential 161


Mailbox Types

 Mailboxes can be classified as:


 Unbounded mailboxes
 No restrictions placed on size of mailbox.
 put() will never block.
 Ex: mailbox m = new ();
 Bounded mailboxes
 Number of entries is determined when the mailbox is
created.
 Bound value should be positive.
 put() will be blocked if the mailbox is full.
 Ex: mailbox m = new (5); // mailbox of depth = 5

Intel Confidential 162


Mailbox Methods
 Messages are placed in strict FIFO order. This
does not guarantee order of arrival but that the
arrival order shall be preserved.
 Mailboxes provides following built-in methods:
Method Use
new() Create a new mailbox.
put() Place a message in a mailbox.
get() Retrieve a message from mailbox.
try_get()/ Try to retrieve a message from the mailbox
try_peek() without blocking.
try_put() Try to place a message in mailbox without
blocking.
Useful only for bounded mailboxes.
peek() Copies a message from mailbox without actually
removing it.
Intel Confidential 163
Mailbox example
module mailbox_ex (); mb_size = mb.num();
class Xaction; for (int i=0; i<mb_size; i++)
rand bit [2:0] addr; begin: dis_l
endclass Xaction d_x;
typedef mailbox #(Xaction) mbx; mb.get(d_x);
mbx mb = new (); $display("Addr = %h",
d_x.addr);
initial end: dis_l
begin: t end: t
Xaction xaction; endmodule: mailbox_ex
int mb_size;

for (int i=0; i<5; i++)


begin
xaction = new;
xaction.addr = 3’b111;
$display("BEFORE:: Addr = %h",
xaction.addr);
mb.put(xaction);
end

Intel Confidential 164


End of Class

 Backup

Intel Confidential 165


Temporal Language
Temporal Behavior in SV - Basics [1]
0 1 2 3 4 5
req

ack

clk

 In SV, signals involved in a temporal expression are sampled.


 The resultant condition of sampling is boolean [condition satisfied/not satisfied].

!req ##1 !ack ##2 req ##1 ack


 Using above waveform,
 !req – sampled at clk 1
 !ack – sampled at clk 2
 req – sampled at clk 4
 ack – sampled at clk 5

Intel Confidential 167


Sequence
• A list of SV boolean expressions in linear order of increasing time.
• Boolean test for whether a signal matches a given sequence or not.
• Assumes an appropriate sampling clock and start/end times
• If all samples in the sequence match the simulation result
then the assertion matches. Otherwise it is said to fail.

Sequences are described efficiently using regular expressions to


specify values over time…

(req && ack) ##1 !req ##1 !ack ##1 req ##1 (req && ack)

Assuming we start e1 e2 e3 e4
with req and ack hi Sequence
SVA events are: req 1 0 0 1 1 1 matches

e1 ( !req )
e2 ( !ack )
ack 1 1 0 0 1

e3 ( req )
e4 ( ack ) clk

Sequence Sequence Sequence


start mismatch end
8-168 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Sequence Operators

Available sequence operators (in order of precedence):

[*N] / [*M:N] - consecutive repetition operator


[=N] / [=M:N] - non-consecutive repetition
[->N] / [->M:N] - goto repetition (non-consecutive, exact)

and - all sequences expected to match, end times may differ


intersect - all sequences expected to match, end times are the SAME

or - 1 or more sequences expected to match

throughout - expression expected to match throughout a sequence

within - containment of a sequence expression

## - sequence delay specifier

8-169 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Delay and Range

Delay:

##[N] // represents a sequential delay of N cycles (default 0)


a ##1 b // a is true on current tick, b will be true on next tick
a ##0 b // a is true on current tick, so is b  (Overlapping!) Same as (a && b)
a ##1 b ##1 c // a is true, b true on next tick, c true on following tick

Range:

a ##[3:5] b // a is true on current tick, b will be true 3-5 ticks from now
a ##[3:$] b // a is true on current tick, b will be true 3 or more ticks from now

$ represents a non-zero
and finite number

8-170 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Sequence Block

Sequence blocks identify and encapsulate a sequence definition

sequence s1;
@ (posedge clk)
a ##1 b ##1 c; // s1 evaluates on each successive edge of clk
endsequence

sequence s2 (data,en); // sequence with name AND arguments


(!frame && (data==data_bus)) ##1 (c_be[0:3] == en);
endsequence
Notice no clock is defined. This may be inherited from
a higher hierarchical statement like property or assert
(More on this later)

sequence s3;
start_sig ##1 s2(a,b) ##1 end_sig; // sequence as sub-expression
endsequence

Where: s3 - same as - start_sig ##1 (!frame && (a == data_bus)) ##1 (c_be[0:3] == b) ##1 end_sig;

8-171 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Procedural Sequence Controls
There are two ways to detect the endpoint of a sequence from within sequential
code. In both cases a verification directive (assert property) is implied for the
sequence.

Given: sequence abc; sequence def;


@(posedge clk) a ##1 b ##1 c; @(negedge clk) d ##[2:5] e ##1 f;
endsequence endsequence

// edge-triggered // level sensitive


always @ abc initial
$display( “abc succeeded" ); wait( abc.triggered || def.triggered )
$display( “Either abc or def succeeded" );
@ unblocks the always block each .triggered indicates the sequence has reached it’s
time the sequence endpoint is reached endpoint in the current timestep. It is set in the Observe
i.e. each time it matches Region and remains true for the rest of the time step

NOTE:
• Both controls imply an instantiation of the sequence (i.e. assert property(seq))
• Only clocked sequences are supported
• Local sequences only (Hierarchical references are not supported)
8-172 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Verification Directives
• A property (or sequence) by itself does nothing. It must appear within
a verification statement to be evaluated.

• Three types of verification statement


[always] assert property - enforces a property as "checker"
[always] cover property - tracks metrics (# attempts, # match, # fail, etc.)
[always] assume property - Used by Formal Verification tools only

• Properties can appear in modules, interfaces, programs, clocking domains


even in $root.
property p1(a,b,c);
disable iff (a) not @clk ( b ##1 c );
endproperty

assert_p1: assert property (p1(rst,in1,in2))


begin $info("%m OK"); end ACTION
else begin $error("%m Failed"); end BLOCK

8-173 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Assertions in SV - Immediate

 Immediate assertions – Example 1


Boolean expressions that get assert_foo : assert(foo)
checked at a point in
procedural code. $display("%m passed");
 The failure of an assertion can else
have a severity $fatal("%m failed");
 $fatal is a run-time fatal.
 $error is a run-time error.
 $warning is a run-time Example 2
warning, which can be assert (myfunc(a,b))
suppressed in a tool-specific count1 = count + 1;
 $info indicates that the
assertion failure carries no else
specific severity. ->event1;
 The display of $warning and
$info can be controlled through
modelsim.ini similar to VHDL.

Intel Confidential 174


Assertions in SV - concurrent

 Concurrent assertions – Example


Temporal expressions that base_rule1: assert property
get checked constantly (cont_prop)
throughout a model run.
Similar to assign $display("%m, passing");
statements. else
 The evaluation is based on $display("%m, failed");
a sampling condition e.g.,
clk or some other event in
design.
 It is necessary that
sampling condition be glitch
free to provide predictable
behavior.

Intel Confidential 175


Assertions in SV –
procedural temporal

 expect statement is a Example


initial begin
procedural blocking # 200ms;
statement that allows expect(
waiting on property @(posedge clk)
evaluation. a ##1 b ##1 c )
else
 It is an immediate $error( "expect failed" );
check in procedural ABC: ...
code which blocks end
further execution till its
completion.

Intel Confidential 176


Property Block
• Property blocks describe behavior in a design, giving it a name for reference
and allowing a range of tools to test/check/cover/etc. that behavior.
PSL “abort”
• Properties have special operators: disable iff, not, |->/|=>
They also support: and, or, if…else

• By themselves, properties do nothing… must appear in assert or cover

Optional parameters (reuse?)

Like an asynchronous reset for the property


property p1(a,b,c,d);
@ (posedge clk) disable iff (reset)
(a) |-> not ( b ##[2:3] c ##1 d );
endproperty
implication Reversal: sequence must NEVER evaluate true

Here, when a is true the b/c/d expression is forbidden

8-177 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Implication |-> |=>
Using the implication ( |->, |=> ) operators you can specify a prerequisite
sequence that implies another sequence. Typically this reduces failures
that you expect and wish to ignore.

<antecedent seq_expr> |->/|=> ( <consequent seq_expr> );

Think of it this way: If the antecedent matches, the consequent must too.
If the antecedent fails, the consequent is not tested and a true result is
forced. Such forced true results are called “vacuous” and Questa does
NOT report them as they would pollute the coverage statistics.

Two forms of the implication operator are supported:


( a ##1 b ##1 c ) |-> ( d ##1 e ); // overlapping form

• If a/b/c matches, then d is evaluated on THAT tick.

( a ##1 b ##1 c ) |=> ( d ##1 e ); // non-overlapping form


• If a/b/c matches, then d is evaluated on the NEXT tick.

8-178 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Lab 14
1. Define a module with the following ports:
clk and req. [Signals are defined on the
testbench]
2. Define a property that captures back to back
requests
1. Whenever a back2back request does not occur
an error message should be generated.
2. Hint: Use property..endproperty
3. Hint: Use assert property
4. Hint: req changes are in sync with positive edge
of clk

Intel Confidential 179


Coverage
Coverage in SV - covergroup

 A covergroup is a Example
container that can hold one covergroup cg_name
or more coverpoints. coverpoint s0 iff(!reset);
endgroup
 It can be triggered
procedurally using sample()
or through trigger events.
 Values of coverpoints inside
covergroup are sampled at
the trigger condition.
 The trigger condition can be
a sequence as well.

Intel Confidential 181


Coverage in SV - coverpoint

 A coverpoint can be an Example


integral variable or an bit [3:0] v_a;
integral expression. covergroup cg
 Each coverpoint includes a @(posedge clk);
set of bins associated with coverpoint v_a {
its sampled values or value-
transitions. bins b1 = {[0:2], [3:4]};
 The bins can be explicitly bins b2[] = {[5:10]};
defined by user or bins b3[2] = {11,
automatically created by the [12:14]};
tool. bins junk = default;
 Control of the max bins }
created can be controlled
using auto_bin_max endgroup
option. [Default is 64 bins]

Intel Confidential 182


How do coverpoints translate for
analysis?
Bins Covergroup Metric Goal/ Status
[Modelsim report]
bins b1 = {[0:2], [3:4]}; bin b1 20 1 Covered

bins b2[] = {[5:10]}; bin b2[0101] 9 1 Covered


bin b2[0110] 15 1 Covered
bin b2[0111] 7 1 Covered
bin b2[1000] 6 1 Covered
bin b2[1001] 9 1 Covered
bin b2[1010] 6 1 Covered
bins b3[2] = {11, [12:14]}; bin b3[0] 13 1 Covered
bin b3[1] 13 1 Covered

bins junk = default; default bin junk 9 Occurred


[Does not account for % covered]
coverpoint addr_ps; bin auto[0] 11 1 Covered
// addr_ps is [2:0] wide. bin auto[1] 13 1 Covered
bin auto[2] 11 1 Covered

bin auto[7] 10 1 Covered
Intel Confidential 183
Activating covergroups
covergroup cg
@(posedge clk);
 covergroups are coverpoint data {
dynamic objects and bins b1 = {[0:2], [3:4]};
bins b2[] = {[5:10]};
need be activated bins b3[2] = {11,
before they can start [12:14]};
collecting information. bins junk = default;
}
 Typically they are endgroup
activated in initial // equivalent to placing in
blocks as covergroups // initial
typically remain active cg cg1 = new ();
from the start to end of // (or)
cg cg1;
simulation. initial
cg1 = new ();

Intel Confidential 184


Coverage in SV – coverpoint
Illegal/Ignore
Example ignoring bins
 coverpoint bins can covergroup cg23;
be made illegal coverpoint a {
and/or ignored. ignore_bins
ignore_vals = {7,8};
 Illegal and ignored bins }
do not count to the endgroup
overall coverage %.
Example creating illegal bins
 When an illegal bin is covergroup cg3;
hit, the simulator issues coverpoint b {
an error [written into illegal_bins
bad_vals = {1,2,3};
transcript]. }
endgroup
Intel Confidential 185
Defining transition coverage

 Transition coverage is used Example


to specify one or more covergroup cg
ordered set of transitions. @(posedge clk);
 Single value transition coverpoint count_val_even {
value1 => value2
bins tra_1 = (0=> 1=> 2);
 Sequence value transitions
bins tra_2[] =
value1=>value3=>value8
(6 => 8 => 10),
 Set of transitions
range_list1 => range_list2 (12 => 14 => 16);
Ex: 1, 5 => 6, 7 implies ignore_bins igb_tra3 =
( 1=>6 ), ( 1=>7 ), ( 5=>6 ), (18=>20=>22);
( 5=>7 ) bins junk =
 default sequence does default sequence;
not count to coverage %. }

Intel Confidential 186


How do transition coverpoints
translate for analysis?

Bins Covergroup Metric Goal/ Status


[Modelsim report]
bins tra_1 = (0=> 1=> 2); bin tra_1 329 1 Covered

bins tra_2 [] = bin tra_2


(6 => 8 => 10), [000110=>001000=>001010] 330 1 Covered
(12 => 14 => 16); bin tra_2
[001100=>001110=>010000] 330 1 Covered
bins junk = default_seq bin junk 9220 Occurred
default sequence; [Does not account for % covered]

Intel Confidential 187


Coverage in SV –
cross coverage

 A coverage group can Example


specify cross coverage bit [31:0] a_var;
between two or more bit [1:0] b_var;
coverage points or
variables. covergroup cov3
@(posedge clk);
 The cross variables need
not be part of the cover A: coverpoint a_var {
definition but within the bins yy[] = { [0:9] };
scope. In such a case SV }
creates an implicit CC: cross b_var, A;
coverpoint for it.
endgroup
 No cross bins are created
for coverpoint bins that are
specified as default, ignored
or illegal.

Intel Confidential 188


Visualizing cross coverage [1]

variable a_var [31:0] variable b_var [1:0]


[31:0] = 2^31 = 4096 M [actual phy space] [1:0] = 2^2 = 4 [physical space]
coverpoint a_var
restricts to [0:9] = 10 [physical space]
0 1 ……. 9 0 1 2 3

cross

10x4
combinations

Intel Confidential 189


Coverage in SV –
cross coverage [2]

Another cross example c : cross a, b {


bit [7:0] v_a, v_b; bins c1 =
covergroup cg @(posedge ! binsof(a) intersect
clk); {[100:200]};
a: coverpoint v_a { // 4 cross products
bins a1 = { [0:63] }; bins c2 = binsof(a.a2)
bins a2 = { [64:127] }; || binsof(b.b2);
bins a3 = { [128:191] }; // 7 cross products
bins a4 = { [192:255] }; } bins c3 = binsof(a.a1)
&& binsof(b.b4);
b: coverpoint v_b { // 1 cross product
bins b1 = {0}; }
bins b2 = { [1:84] }; endgroup
bins b3 = { [85:169] };
bins b4 = { [170:255] }; }

Intel Confidential 190


Visualizing cross coverage [2]

[0:63] [64:127] [128:191] [192:255] 0 [1:84] [85:169] [170:255]


a1 a2 a3 a4 [0:63] [64:127] b1[128:191] b2[192:255] b3 b4
0 [1:84] [85:169] [170:255]
a1 a2 a3 a4 b1 b2 b3 b4

cross

!(binsof(a) intersect {[100:200]})

16 cross
4 cross
combinations
combinations
<a1,b1
a1,b2
a1.b3
a1,b4>

Intel Confidential 191


Visualizing cross coverage [3]

[0:63] [64:127] [128:191] [192:255] 0[0:63] [64:127]


[1:84] [128:191] [170:255]
[85:169] [192:255] 0 [1:84] [85:169] [170:255]
a1 a2 a3 a4 b1 a1 b2 a2 b3 a3 b4 a4 b1 b2 b3 b4

binsof (a.a2)
cross
[0:63] [64:127] [128:191] [192:255] 0 [1:84] [85:169] [170:255]
a1 a2 a3 a4 b1 b2 [0:63]b3 b4
[64:127] [128:191] [192:255] 0 [1:84] [85:169] [170:255]
a1 a2 a3 a4 b1 b2 b3 b4
4 cross
combinations
<a2,b1
16 cross a2, b2
binsofcombinations
(b.b2) a2.b3
binsof(a.a2)
a2,b4> || binsof (b.b2)

4 cross
combinations
<b2,11 7 cross
b2, a2 combinations
[one is common]
b2.a3
b2,a4>

Intel Confidential 192


Coverage in SV – cross
Illegal/Ignore

 A group of bins can be Example using ignore


covergroup yy;
excluded by specifying cross a, b {
a select expression ignore_bins foo =
using ignore_bins or binsof(a) intersect
marked illegal using { 5, [1:3] }; }
illegal_bins. endgroup
Example using illegal
covergroup zz(int bad);
cross x, y {
illegal_bins foo =
binsof(y) intersect {bad};
}
endgroup

Intel Confidential 193


Lab 15

1. Define a module with the following port list


clk, put, avail.
All ports are input ports
2. Define a covergroup that captures all
combinations of put and avail sampling
values at positive edges of clk

Intel Confidential 194


‘unique’ and ‘priority’ modifiers {BACKUP}

Modifiers on if and case/casex/casez selection


expressions
‘unique’ - no more than one branch may be
true for each evaluation, simulator errors if
this happens
‘priority’ - order of evaluation is important
Both modifiers require that if no fall-through
else/default statement is available, and no
branch is true, an error is generated

Intel Confidential 195


Lab 5: CRC}

Intel Confidential 196


Lab 5: CRC (cont) {BACKUP}

Implement the CRC algorithm shown in the


previous foil.
The operators << (left shift) and ^ (xor) will be
needed.
Process the bitstream given in the lab file and
report the CRC.

Intel Confidential 197


Constraint Guards {BACKUP}

Guards prevent the application of constraints,


similar to implication, but remove the constraint
from consideration of the constraint solver
Use the same implication operator, just using state
variables
(!global_reset_state && cmd) -> (cmd_type != IDLE)

Can even test obj pointers for null


(a != null && a.x > 10) ->
(y < 100 && y > a.x)

Intel Confidential 198


std::randomize() {BACKUP}

 Procedural invocation of constraint solver


 Any variables can be the random variables
 “with” block for constraints
 Normal .randomize() cannot include variables
outside scope of class

Intel Confidential 199


Disabling rand/constraints {BACKUP}

 rand_mode – method to toggle the “rand”


attribute off on a class variable
 constraint_mode – method to toggle the
application of a named constraint

Intel Confidential 200


Random Stability {BACKUP}

 SV has thread random stability

Intel Confidential 201

Вам также может понравиться