[go: up one dir, main page]

0% found this document useful (0 votes)
17 views136 pages

SystemVerilog UNIT 1 Updated

Uploaded by

aditya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views136 pages

SystemVerilog UNIT 1 Updated

Uploaded by

aditya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 136

SystemVerilog-UNIT-1

System Verilog data types, Operators, Loops,


Functions

Prof. Sowmya K B
ECE Department
RVCE, Bengaluru

Prof. Sowmya K B 1
Generations of the SystemVerilog standard
Accellera standard

Prof. Sowmya K B 2
SystemVerilog began with a version
number of 3.0 to show that …..
Verilog-1995 is the First generation of
Verilog

Verilog-2001 is the second major


generation of Verilog

SystemVerilog is the third major generation.

Prof. Sowmya K B 3
Accellera SystemVerilog 3.0 -June 2002

Accellera SystemVerilog 3.1 -May 2003

Final Accellera SystemVerilog 3.1a -May 2004

SystemVerilog 3.1a was donated to the IEEE


June 2004

IEEE 1800-2005 is the official SystemVerilog standard


Nov 2005

Prof. Sowmya K B 4
Donations to SystemVerilog

 The SUPERLOG Extended Synthesizable Subset


(SUPERLOG ESS), from
(supplier of an advanced languages and tools)

 The OpenVERA verification language from


 OpenVERA Assertions (OVA) from
 The DirectC and coverage Application Programming
Interfaces (APIs) from

 PSL assertions

 Separate compilation and $readmem extensions from

 Tagged unions and high-level language features from


Prof. Sowmya K B 5
Key SystemVerilog enhancements for hardware
design
 Interfaces to encapsulate communication and protocol checking within
a design
 C like data types, such as int
 User-defined types, using typedef
 Enumerated types
 Type casting
 Structures and unions
 Packages for definitions shared by multiple design blocks
 External compilation-unit scope declarations
 ++, --, += and other assignment operators
 Explicit procedural blocks
 Priority and unique decision modifiers
 Programming statement enhancements
 Pass by reference to tasks, functions and modules
Prof. Sowmya K B 6
Prof. Sowmya K B 7
Prof. Sowmya K B 8
Prof. Sowmya K B 9
Prof. Sowmya K B 10
Prof. Sowmya K B 11
Prof. Sowmya K B 12
Simulation time unit and precision

In verilog: forever #5 clock = ~clock;

Verilog’s timescale directive `timescale 1ns / 10ps

the software tool is instructed to use time units of 1ns,


and a precision of 10ps, which is 2 decimal places

Prof. Sowmya K B 13
Simulation time unit and precision

A problem with the the ‘timescale directive is file order dependent


Prof. Sowmya K B 14
Simulation time unit and precision

Prof. Sowmya K B 15
Simulation time unit and precision

In SystemVerilog time units specified as part of the time value


Ex: forever #5ns clock = ~clock
SystemVerilog time units

No space
Prof. Sowmya K B 16
Simulation time unit and precision

Scope-level timeunit and precision

• timeunit and timeprecision as part of module definition

Ex:
module adder (input wire [63:0] a, b, output reg [63:0] sum,
output reg carry);
timeunit 1ns;
timeprecision 10ps;
...
endmodule

Prof. Sowmya K B 17
Enhanced literal value assignments
Filling a vector in verilog with all zeros, all Xs or all Zs done very easily
Parameter width =64;
reg[ width-1:0] a;
a=0;
a=`bz;
a=`bx;
a=`b1;

data = ~0;
// one's complement operation
data = -1

System verilog:
a=`0;
a=`z;
a=`x;
a=`1;

Prof. Sowmya K B 18
Relaxed usage of variables
• These relaxed rules for using variables allow most signals in a model to be
declared as a variable. It is not necessary to first determine the context in
which that signal will be used. The type of the signal does not need to be
changed as the model evolves from system level to RTL to gate level.

• It is important to note that though SystemVerilog allows variables to be used


in places where Verilog does not, SystemVerilog does still have some
restrictions on the usage of variables.

• SystemVerilog makes it an error to have multiple output ports or multiple


continuous assignments write to the same variable, or to combine procedural
assignments with continuous assignments or output drivers on the same
variable.

• The reason for these restrictions is that variables do not have builtin resolution
functionality to resolve a final value when two or more devices drive the same
output. Only the Verilog net types, such as wire,wand (wire-and) and wor
(wire-or), have built-in resolution functions to resolve multi-driver logic. (The
Verilog-2005 standard also has a uwire net type, which restricts its usage to a
single driver, the same as with variables.)

Prof. Sowmya K B 19
Relaxed usage of variables

module compare (output logic gt, output logic lt,output logiceq,


input logic [63:0] a, b );
always @(a, b)
if (a < b) lt = 1'b1;
else lt = 1'b0;
assign gt = (a > b); // continuous assignments
comparator u1 (eq, a, b); // module instance
endmodule

module comparator (output reg eq, input [63:0] a, b);


always @(a, b)
eq = (a==b);
endmodule

Prof. Sowmya K B 20
Illegal usage of variables

module add_and_increment (output logic [63:0] sum, output logic carry,


input logic [63:0] a, b );
always @(a, b)
sum = a + b;
assign sum = sum + 1; //error
look_ahead i1 (carry, a, b);
overflow_check i2 (carry, a, b); //error
endmodule

module look_ahead (output wire carry, input logic [63:0] a, b);


...
endmodule

module overflow_check (output wire carry, input logic [63:0] a, b);


...
endmodule
Prof. Sowmya K B 21
Variable
A DATA STORAGE ELEMENT

Variable Real type C-type Size Sign Default


(Floating Value
Integer
point)
Real real double 64 bits signed 0.0
Void short real float 32 bits signed 0.0
Class $real time
String
Event
User-Defined
Enumeration
$ realtime vs $time – Depend on Timescale
Prof. Sowmya K B 22
$realtime vs $time
`timescale 1ns/10ps;

module realtimeex;
logic value;
initial
begin
$monitor(“realtime = ”, $realtime,
“/t time= ”, $time ,
“value= ”, value);
#1.55 value=0;
#1.55 value=1;
end
endmodule

Prof. Sowmya K B 23
Output:
realtime = 0.0 time= 0 value = x
realtime = 1.55 time= 2 value = 0
realtime = 3.1 time= 3 value = 1

Prof. Sowmya K B 24
Void: Non existance of Data Variable
Class: class contains properties and methods
Integer
class data;
Real
bit [3:0] abc; Void
logic [4:0] cdf;
integer pqr; Class
task clean(); String
abc=0;cdf=5’b0;pqr=0;
end task
Event
User-Defined
end class
Enumeration
Prof. Sowmya K B 25
Event
Synchronization of two or more currently active
processes
event a; //declaration
->a; // event triggered
Variable
@(a) // waiting for occurrence of the event trigger
Integer
Real
Void
Class
String
Event
User-Defined
Prof. Sowmya K B Enumeration
26
module event_ex;
event a;
Event
logic b,c;
initial
begin
b=0;
#10 b=1;
-> a;
end
initial
begin
c=1;
@(a) c=0;
end
initial
begin
$monitor($time, “b=%b” , “c=%b”, b, c);
end endmodule Prof. Sowmya K B 27
Output:
0 b=0, c=1
10 b=1, c=0

Prof. Sowmya K B 28
User-Defined
Variable
typedef data_type type_identifier;
Integer
Ex: Real
typedef int plant; Void
plant rose, jasmine; Class
String
Event
User-Defined
Enumeration
Prof. Sowmya K B 29
SystemVerilog Enumeration
Variable
Integer • An enumerated type defines a set of named values.

Real
• In the following example, color* is an enumerated
Void variable that can store one of the three possible
Class values (0, 1, 2).
String
• By default, the first name in the enumerated list gets
Event the value 0 and the following names get incremental
User-Defined values like 1 and 2.
Enumeration

Prof. Sowmya K B 30
Examples:
enum{RED, YELLOW, GREEN} color1;
// int type; RED = 0, YELLOW = 1, GREEN = 2

enum bit[1:0] {RED, YELLOW, GREEN} color2;


// bit type; RED = 0, YELLOW = 1,GREEN = 2

enum {RED=3, YELLOW, GREEN} color3;


// RED = 3, YELLOW = 4, GREEN=5

enum {RED = 4, YELLOW = 9, GREEN} color4;


// RED = 4, YELLOW = 9, GREEN = 10 (automatically assigned)

enum{RED = 2, YELLOW, GREEN = 3} color5;


// Error : YELLOW and GREEN are both assigned 3

enum bit[0:0] {RED, YELLOW, GREEN}color6;


// Error: minimum 2 bits are required

enum {1WAY, 2TIMES, SIXPACK=6} color7;


// Compilation error on 1WAY, 2TIMES

Prof. Sowmya K B 31
How to define a new enumerated data
type ?
module m1;
typedef enum {TRUE, FALSE} words;
initial
begin
words answer;
answer = TRUE;
$display ("answer = %s", answer.name);
end
endmodule

Output: answer = TRUE

Prof. Sowmya K B 32
module colors;
typedef enum {GREEN, YELLOW, RED, BLUE} color_set_1;
typedef enum {MAGENTA=2, VIOLET=7, PURPLE, PINK} color_set_2;
typedef enum {BLACK[4]} color_set_3;
typedef enum {RED[3] = 5} color_set_4;
typedef enum {YELLOW[3:5]} color_set_5;
typedef enum {WHITE[3:5] = 4} color_set_6;
initial begin
color_set_1 color1;
color_set_2 color2;
color_set_3 color3;
color_set_4 color4;
color_set_5 color5;
color_set_6 color6;
color1 = YELLOW; $display ("color1 = %0d, name = %s", color1, color1.name());
color2 = PURPLE; $display ("color2 = %0d, name = %s", color2, color2.name());
color3 = BLACK3; $display ("color3 = %0d, name = %s", color3, color3.name());
color4 = RED1; $display ("color4 = %0d, name = %s", color4, color4.name());
color5 = YELLOW3;$display ("color5 = %0d, name = %s", color5, color5.name());
color6 = WHITE4; $display ("color6 = %0d, name = %s", color6, color6.name());
end
endmodule Prof. Sowmya K B 33
Result:
color1 = 1, name = YELLOW
color2 = 8, name = PURPLE
color3 = 3, name = BLACK3
color4 = 6, name = RED1
color5 = 0, name = YELLOW3
color6 = 5, name = WHITE4

Prof. Sowmya K B 34
%d and %0d
• %d displays using a fixed width to
accommodate the largest possible value for the
expression being displayed.

• %0d displays the minimum width, suppressing


any leading 0's or spaced.

Prof. Sowmya K B 35
Enumerated-Type Methods
SystemVerilog includes a set of specialized methods to enable iterating over
the values of enumerated types.

first() function enum first(); Returns the value of the first member of the enumeration

last() function enum last(); Returns the value of the last member of the enumeration

function enum next Returns the Nth next enumeration value starting from the
next()
(int unsigned N = 1); current value of the given variable

function enum prev Returns the Nth previous enumeration value starting from
prev()
(int unsigned N = 1); the current value of the given variable

num() function int num(); Returns the number of elements in the given enumeration

Returns the string representation of the given enumeration


name() function string name();
value
Prof. Sowmya K B 36
typedef enum {GREEN, YELLOW, RED, BLUE} colors;

module tb;
initial begin
colors color;

color = YELLOW;

$display ("color.first() = %0d", color.first());


$display ("color.last() = %0d", color.last());
$display ("color.next() = %0d", color.next());
$display ("color.prev() = %0d", color.prev());
$display ("color.num() = %0d", color.num());
$display ("color.name() = %s" , color.name());
end
endmodule

Prof. Sowmya K B 37
typedef enum {GREEN, YELLOW, RED, BLUE} colors;
module tb;
initial begin
colors color;

// Assign current value of color to YELLOW


color = YELLOW;

$display ("color.first() = %0d", color.first()); // First value is GREEN = 0


$display ("color.last() = %0d", color.last()); // Last value is BLUE = 3
$display ("color.next() = %0d", color.next()); // Next value is RED = 2
$display ("color.prev() = %0d", color.prev()); // Previous value is GREEN = 0
$display ("color.num() = %0d", color.num()); // Total number of enum = 4
$display ("color.name() = %s" , color.name()); // Name of the current enum
end
endmodule

Prof. Sowmya K B 38
Output:
color.first() = 0
color.last() = 3
color.next() = 2
color.prev() = 0
color.num() = 4
color.name() = YELLOW

Prof. Sowmya K B 39
Type casting

• Verilog does not have type casting


• SystemVerilog adds a cast operator
• SystemVerilog’s cast operator goes beyond C,
however, in that a vector can be cast to a different
size, and signed values can be cast to unsigned or
vice versa.

Format:
<type>’(<expression>)
Prof. Sowmya K B 40
<type>’(<expression>)

7+ int’(2.0 * 3.0);

Y=a+b**16’(2);

int unsigned a,b;


Y=Y- signed’({a,b});

Prof. Sowmya K B 41
SystemVerilog Constants,Parameters
and `define
There are three ways to define constants:
• constants
• parameter
• `define

Prof. Sowmya K B 42
Constants
const logic [23:0] C1 = 7;
const int C2 = 15; // 32-bit constant
const real C3 = 3.14; // real constant
const C4 = 5;

Prof. Sowmya K B 43
Parameter
Parameters must be defined within module
boundaries using the keyword parameter.
A parameter is a constant that is local to a module that can optionally be
redefined on an instance. Parameters are typically used to specify the width of
variables and time delays.

Parameter example

module mem_model #(
parameter ADDR_WIDTH=8;
parameter DATA_WIDTH=32;)
(clk, addr, data);

input clk;
input [ADDR_WIDTH-1:0] addr;
output [DATA_WIDTH-1:0] data;
.....
.....
endmodule Prof. Sowmya K B 44
Parameter redefinition

Parameter values are not allowed to modify at runtime but can be modified
using the defparam statement and #delay specification with module
instantiation.

//Creates mem_1 instance with default addr and data widths.


mem_model mem_1 (.clk(clk),
.addr(addr_1),
.data(data_1));

//Creates mem_2 instance with addr width = 4 and data width = 8.


mem_model #(4,8) mem_2 (.clk(clk),
.addr(addr_2),
.data(data_2));

Prof. Sowmya K B 45
//Creates mem_3 instance with addr width = 32 and data width = 64.
mem_model #(32,64) mem_3 (.clk(clk), .addr(addr_3), .data(data_3));

//Creates mem_4 instance with default addr width and data width = 64.
mem_model #(DATA_WIDTH=64)
mem_4 (.clk(clk), .addr(addr_3), .data(data_3));

Prof. Sowmya K B 46
Macro
• The term ‘macro’ refers to the substitution of a line or a few lines of
text code.

• The directive “ `define” creates a macro for substitution code.

• Once the macro is defined, it can be used anywhere in a compilation


unit scope, wherever required.

• It can be called by (`) character followed by the macro name.

• A macro can be defined with argument(s). Argument(s) are useful to


customize the macro to use widely, like a fuction-task. Such macro
argument(s) can be defined with default values so that if an engineer
wont’t pass any specific value, the macro substitutes the default
value.

• The `define compiler directive is used to perform global macro


substitution and remain active for all files read/compiled after the
macro definition.
Prof. Sowmya K B 47
Examples of `define text macros
`define NUMBER1 5
`define STRING1 “RVCE”
`define ADD2PLUS2 2 + 2
`define ADD5(RESULT, SOURCE)\
RESULT = SOURCE + 5; \
$display("Scope is %m");
module m1;
logic [7:0] a, b;
initial begin
$display(`NUMBER1);
$display(`STRING1);
$display(2 + 2);
$display(`ADD2PLUS2);
a=2;
`ADD5(b, a)
$display("a:%0d, b:%0d", a, b);
end Prof. Sowmya K B 48
endmodule
`define WIDTH 8
to avoid redefincation `ifdef can be used,

`ifdef WIDTH
// do nothing (better to use `ifndef)
`else
`define WIDTH 8
`endif

`ifndef WIDTH
`define WIDTH 8
`endif

Prof. Sowmya K B 49
`ifdef can be used as if..else

`ifdef TYPE_1
`define WIDTH 8
`else
`define WIDTH 32
`endif

`ifndef MODULE_1
`define MODULE_1
module mem;
....
....
endmodule
`endif
Prof. Sowmya K B 50
`define MY_NUMBER 5
`define MY_STRING "Hello world!"
`define ADD2PLUS2 2 + 2
`define ADD5(RESULT, SOURCE) \
RESULT = SOURCE + 5; \
$display("Inside ADD5 macro. Scope is %m");

module test;
reg [7:0] a, b;
initial begin 5
$display(`MY_NUMBER); Hello world!
$display(`MY_STRING); 4
$display(2 + 2); 4
$display(`ADD2PLUS2); Inside ADD5 macro. Scope is test
a = 1; a:1, b:6
`ifdef MY_FEATURE
`ADD5(b, a)
$display("a:%0d, b:%0d", a, b);
`else
$display("No feature");
`endif
end
endmodule
Prof. Sowmya K B 51
Example:
module test2;
`define HI Hello
`define LO "`HI, world"
`define H(x) "Hello, x"

initial begin
$display("`HI, world");
$display(`LO);
$display(`H(world));
end
endmodule : test2

Prof. Sowmya K B 52
`" overrides the usual lexical meaning
of "
module TEST3;
`define HI Hello
// macro substitution
`define LO `"`HI, world`"
// argument substitution
`define H(x) "Hello, x"

initial begin
$display(`LO);
$display(`H(world));
end
endmodule : TEST3

Prof. Sowmya K B 53
The above code is an example of a multiline macro. As shown above, for the
multiline macro, the new line is preceded by a backslash “”. If the backslash is
not present for a line, it is considered as the last line of the macro. The
backslash will not be present in actual code where the macro is used and where
the actual macro code is substituted.
Note: There should be no space or character after the backslash “” at the end of
a line –otherwise the compiler shouts an error.
Possible syntaxes used to define a macro based on the usage of the below three
special characters (quotations) along with the arguments, the actual code that it
replaces has a different meaning. All possible macros can be formed using these
Prof. Sowmya K B 54
three quotes:
1. `` (Double tick)
• The ``quotation can be used to form a signal/variable name by
using given argument.
• Example:
Macro definition:
`define master(ARG1)\
VAR1=MST_``ARG1;\
VAR2=MST_``ARG1``_AGAIN;

Macro usage:
`master(3);

Actual code the macro replaces:


;
VAR1=MST_3;\
VAR2=MST_3_AGAIN;
Prof. Sowmya K B 55
2. `”(Tick followed by a double quote)
The `”quotation can be used to interpret the argument as a string.
Example:

Macro Definition:

`define data1(arg1)\
reg_``arg1=data_``arg1;\
$display(“reg name: reg_%0s, value: %0h”, `”arg1`”, reg_``arg1);

Macro usage
`data1(a)

Actual code the macro replaces:


reg_a=data_a;
$display(“reg name: reg_%0s, value: %0h”, ”a”, reg_a);
Prof. Sowmya K B 56
module top();
`define msg(x,y) `"x:y`"
initial begin
$display(`msg(leftside,rightside));
end
endmodule

Prof. Sowmya K B 57
3. `\`” (Tick followed by backslash followed by a
double quote)
• Now what if you want to add double quotes in
string which is constructed using macro.
SystemVerilog provides support for that.
• `\`" indicates that the expansion should include ".

module top();
`define msg(x,y) `”x: `\`”y`\`”`”

initial begin
$display(`msg(leftside,rightside));
end
Prof. Sowmya K B 58
module top();
int unsigned pkt_tx_cnt;
int unsigned pkt_rx_cnt;
bit clock_master;
bit reset_master;
int unsigned count_a;
int unsigned count_b;

`define increment(dir) \
pkt_``dir``_cnt = pkt_``dir``_cnt + 1;

`define set(sig, value) \


sig``_master = value;

`define update_count(sel, value) \


count_``sel = value;

initial begin
$display("pkt_tx_cnt:%0d, pkt_rx_cnt:%0d", pkt_tx_cnt, pkt_rx_cnt);
$display("clock_master:%b, reset_master:%b", clock_master, reset_master);
$display("count_a:%0d, count_b:%0d", count_a, count_b);
Prof. Sowmya K B 59
$display();
`increment(tx)
`set(clock, 1)
`update_count(a, 5)
$display("pkt_tx_cnt:%0d, pkt_rx_cnt:%0d", pkt_tx_cnt, pkt_rx_cnt);
$display("clock_master:%b, reset_master:%b", clock_master,
reset_master);
$display("count_a:%0d, count_b:%0d", count_a, count_b);
$display();

`increment(rx)
`set(reset, 1)
`update_count(b, 7)
$display("pkt_tx_cnt:%0d, pkt_rx_cnt:%0d", pkt_tx_cnt, pkt_rx_cnt);
$display("clock_master:%b, reset_master:%b", clock_master,
reset_master);
$display("count_a:%0d, count_b:%0d", count_a, count_b);
end
endmodule : top
Prof. Sowmya K B 60
Output:
pkt_tx_cnt:0, pkt_rx_cnt:0
clock_master:0, reset_master:0
count_a:0, count_b:0

pkt_tx_cnt:1, pkt_rx_cnt:0
clock_master:1, reset_master:0
count_a:5, count_b:0

pkt_tx_cnt:1, pkt_rx_cnt:1
clock_master:1, reset_master:1
count_a:5, count_b:7

Prof. Sowmya K B 61
`define enhancements
In Verilog, the following example will not work as
intended:
`define print(v)\
$display(“variable v = %h”, v)
`print(data);

In this example, the macro ‘print() will expand to:


$display(“variable v = %h”, data);

Prof. Sowmya K B 62
` “allows macro argument substitution
within strings

`define print(v) \
$display(`“variable v = %h`” , v)
`print(data);
In this example, the macro ‘print() will expand to:
$display(“variable data = %h”, data);

Prof. Sowmya K B 63
`\`" allows an escaped quote in a macro text
string containing argument substitution
To print $display("variable \"data\" = %h", data);

`define print(v) \
$display(`"variable `\`"v` \`" = %h`", v)
`print(data);

Prof. Sowmya K B 64
• Fixed Size Arrays

• Packed and Un-Packed Arrays

• Structure

• Union

• Dynamic Array

• Associative Array

• Queues

Prof. Sowmya K B 65
Fixed size array
In fixed size array, array size will be constant throughout the simulation, Once the
array is declared no need to create it. By default array will be initialized with value ‘0’.

single dimensional array:


Declaration:
int array1 [6]; //Compact declaration :6 ints [0]…[5]
int array2 [5:0]; // Verbose declaration :6 ints [5]…[0]
Initializing an array:
array1 = '{0,1,2,3,4,5};
array2 = '{0,1,2,3,4,5};

Multidimensional array:
You can create multidimensional fixed-size arrays by specifying the dimensions after
the variable name.
The following creates several two-dimensional arrays of integers, 4 entries by 3.
Declaration:
int array3[3][4];
int array3 [2:0][3:0];
array3[0][0]=1; //se t last array element
Initializing an array:
array3 = '{ '{0,1,2,3},'{4,5,6,7},'{8,9,10,11}};
int md[2][3]=’{’{0,1,2}, ’{3,4,5}};// Prof.
declaring
Sowmya Kand
B initializing 66
packed array
bit [7:0] packed_array = 8'hAA;
bit[2:0][3:0] arrays;

unpacked array
reg unpacked_array [7:0] = '{0,0,0,0,0,0,0,1};
bit [7:0] arrays[2:0];

Prof. Sowmya K B 67
integer matrix[7:0][0:31][15:0];//3-dimensional unpacked array of integers
integer matrix[8][32][16]; // 3-dimensional unpacked array of integers

Prof. Sowmya K B 68
EX: Fixed Arrays
module num;
int md[2][3]='{'{0,1,2},'{3,4,5}};
initial
begin

$display("Initial value:");

foreach (md[i,j])
$display("md[%0d][%0d] = %0d", i, j, md[i][j]);
$display("New value:");

md = '{'{9, 8, 7}, '{3{5}}};


foreach (md[i,j])
$display("md[%0d][%0d] = %0d", i, j, md[i][j]);

end endmodule Prof. Sowmya K B 69


Result
Initial value:
md[0][0] = 0
md[0][1] = 1
md[0][2] = 2
md[1][0] = 3
md[1][1] = 4
md[1][2] = 5
New value:
md[0][0] = 9
md[0][1] = 8
md[0][2] = 7
md[1][0] = 5
md[1][1] = 5
md[1][2] = 5

Prof. Sowmya K B 70
module fixedsize_array;
int array1[6]; //single dimension array
int array2[5:0]; //single dimension array
int array3[2:0][3:0]; //multi dimension array
int array4[4:0];
initial
begin
//array initialization
array1 = '{0,1,2,3,4,5};
array2 = '{0,1,2,3,4,5};
array3 = '{'{0,1,2,3},'{4,5,6,7},'{8,9,10,11}};

$display("-------displaying array1-------");
foreach(array1[i])
$display("\t array1[%0d] = %0d", i, array1[i]);

$display("-------displaying array2-------");
for(int i=0;i<6;i++)
Prof. Sowmya K B 71
$display("\t array2[%0d] =%0d“, i, array2[i]);
$display("-------displaying array3-------");
foreach(array3[i,j])
$display("\t array3[%0d][%0d] = %0d",i,j,array3[i][j]);

$display("-------displaying uninitialized array4-------");


for(int i=0;i<5;i++)
$display("\t array4[%0d] = %0d",i,array4[i]);
end
endmodule

Prof. Sowmya K B 72
RESULT
-------displaying array1-------
array1[0] = 0
array1[1] = 1
array1[2] = 2
array1[3] = 3
array1[4] = 4
array1[5] = 5
-------displaying array2-------
array2[0] = 5
array2[1] = 4
array2[2] = 3
array2[3] = 2
array2[4] = 1
array2[5] = 0
-------displaying array3-------
array3[2][3] = 0
array3[2][2] = 1
array3[2][1] = 2
array3[2][0] = 3
array3[1][3] = 4
array3[1][2] = 5
array3[1][1] = 6
array3[1][0] = 7
array3[0][3] = 8
array3[0][2] = 9
array3[0][1] = 10
array3[0][0] = 11
-------displaying uninitialized array4-------
array4[0] = 0
array4[1] = 0
array4[2] = 0
array4[3] = 0 Prof. Sowmya K B 73
array4[4] = 0
Difference between $write and $display
• The only difference is that the $display task
adds a new line character at the end of the
output, while the $write task does not.
• To print something as new lines, use $display.
• $write becomes useful if you want to print a
set of values - all on a single line.
• The only difference between the two is that
$display writes out a newline character at the
end of the text, whereas $write does not.
Prof. Sowmya K B 74
Multidimensional array:
module arr;
initial
begin
byte ss[4][5];
foreach(ss[i,j])
ss[i][j]=i*10+j;
foreach(ss[i])
begin
$display("%2d:", i);
foreach(ss[j])
$display("%4d",ss[i][j]);
end
end
endmodule Prof. Sowmya K B 75
Multidimensional array:
RESULT:
0:
0
1
2
3
4
1:
10
11
12
13
14
2:
20
21
22
23
24
3:
30
31
32
33
Prof. Sowmya K B 76
34
Multidimensional array:
module arr;
initial
begin
byte ss[4][5];
foreach(ss[i,j])
ss[i][j]=i*10+j;
foreach(ss[i])
begin
$write("%2d:", i);
foreach(ss[,j])
$display("%4d",ss[i][j]);
// $display;
end
end
endmodule
Prof. Sowmya K B 77
Multidimensional array:
RESULT:
0: 0
1
2
3
4
1: 10
11
12
13
14
2: 20
21
22
23
24
3: 30
31
32
33
34

Prof. Sowmya K B 78
Multidimensional array:
module arr;
initial
begin
byte ss[4][5];
foreach(ss[i,j])
ss[i][j]=i*10+j;
foreach(ss[i])
begin
$write("%2d:", i);
foreach(ss[,j])
$write("%4d",ss[i][j]);
end
end
endmodule Prof. Sowmya K B 79
RESULT:
0: 0 1 2 3 4 1: 10 11 12 13 14 2: 20 21 22 23 24 3: 30 31 32 33 34

Prof. Sowmya K B 80
Multidimensional array:
module arr;
initial
begin
byte ss[4][5];
foreach(ss[i,j])
ss[i][j]=i*10+j;
foreach(ss[i])
begin
$write("%2d:", i);
foreach(ss[,j])
$write("%4d",ss[i][j]);
$display;
end
end
endmodule
Prof. Sowmya K B 81
Multidimensional array:
RESULT:
0: 0 1 2 3 4
1: 10 11 12 13 14
2: 20 21 22 23 24
3: 30 31 32 33 34

Prof. Sowmya K B 82
Structure (Collection of Data Types)
structure Declaration:
struct{logic[3:0] addr;
int data;
} st;
st.addr=4’b0010;

Prof. Sowmya K B 83
Structure declarations
structures can be variables or nets
// structure variable
var struct {logic [31:0] a, b;
logic [ 7:0] opcode;
logic [23:0] address;
} Instruction_Word_var;

// structure net
wire struct {logic [31:0] a, b;
logic [ 7:0] opcode;
logic [23:0] address;
} Instruction_Word_net;
Prof. Sowmya K B 84
User- defined structure :
typedef struct{
logic[3:0] addr;
int data;
} dt;
dt st;

Prof. Sowmya K B 85
Packed structure :
struct packed{
logic[3:0] addr; *By default structure is unpacked
int data;
} st;
st=36’h1234567B8;

Prof. Sowmya K B 86
Signed Packed structure :
struct packed signed{
logic[3:0] addr;
int data;
} st; // signed
st=36’h1234567B8;

Prof. Sowmya K B 87
Unsigned Packed structure :
struct packed unsigned{
logic[3:0] addr;
int data;
} st;
st=36’h1234567B8;

Prof. Sowmya K B 88
Structure literal ( Assigning Values):
typedef struct {
int a;
shortreal b;
} st;
st sen;
sen=‘{0,0.0};

Prof. Sowmya K B 89
Packed and unpacked structures
• By default, a structure is unpacked.
• The layout of the storage can vary from one
software tool to another.

• A structure can be explicitly declared as a


packed structure, using the packed keyword.
struct packed {
logic valid;
logic [ 7:0] tag;
logic [31:0] data;
} data_word Prof. Sowmya K B 90
Ex:Assigning to structure members
typedef struct { logic [31:0] a, b;
logic [ 7:0] opcode;
logic [23:0] address;
} instr_t;
instr_t IW;
always @(posedge clock, negedge resetN)
if (!resetN)
begin
IW.a = 100; // reference structure member
IW.b = 5;
IW.opcode = 8’hFF;
IW.address = 0;
end
else
begin
...
end
Prof. Sowmya K B 91
Assigning structure expressions to
structures
always @(posedge clock, negedge resetN)
if (!resetN)
IW = ‘{100, 5, 8’hFF, 0};
else
begin
...
end

Prof. Sowmya K B 92
• The values in the structure expression can be listed in the order
in which they are defined in the structure.

• Alternatively, the structure expression can specify the names


of the structure members to which values are being assigned,
where the member name and the value are separated by a
colon.

• When member names are specified, the expression list can be


in any order.
IW = `{address:0, opcode:8’hFF, a:100, b:5};

• It is illegal to mix listing by name and listing by order in the


same structure expression.
IW = `{address:0, 8’hFF, 100, 5}; // ERROR

• set all members of IW to 0


Prof. Sowmya K B 93
IW = `{default:0};
default value precedence
There is a precedence in how structure members are assigned
values. The default keyword has the lowest precedence, and will
be overridden by any type-specific defaults. Type-specific default
values will be overridden by any explicitly named member
values. The following structure expression will assign r0 a value
of 1.0, r1 a value of 3.1415, and all other members of the
structure a value of 0.

typedef struct {
real r0, r1;
int i0, i1;
logic [ 7:0] opcode;
logic [23:0] address;
}strt ;
strt s1;
s1 = ‘{ real:1.0, default:0, r1:3.1415 };
Prof. Sowmya K B 94
Packed structures are stored as vectors

data_word.tag = 8’hf0;
data_word[39:32] = 8’hf0; // same bits as tag

Operations on packed structures


typedef struct packed {
logic valid;
logic [ 7:0] tag;
logic [31:0] data;
} data_word_t;

data_word_t packet_in, packet_out;


packet_in = ‘{1, ‘1, 1024};
always @(posedge clock)
packet_out <= packet_in << 2;
Prof. Sowmya K B 95
Signed packed structures
typedef struct packed signed{
logic valid; logic [ 7:0] tag;
logic signed [31:0] data;
} data_word_t;
data_word_t A, B;
always @(posedge clock)
if ( A < B ) // signed comparison ...

Prof. Sowmya K B 96
Unpacked unions are not synthesizable.
Packed unions
• packed union members all have the same size
Ex:
typedef struct packed {
logic [15:0] source_address;
logic [15:0] destination_address;
logic [23:0] data;
logic [ 7:0] opcode;
} data_packet_t;

union packed {
data_packet_t packet;
logic [7:0][7:0] bytes;
} dreg;

Packed union with two representations of the same storage


Prof. Sowmya K B 97
Unions
A Union Stores A Single Element
It reduces storage and improve performance
union {
int i; Anonymous union
int unsigned u;
} data;
...
data.i = -5;
$display("data is %d", data.i);
data.u = -5;
$display("now data is %d", data.u);
Typed union
typedef union {
int i;
int unsigned u;
} data_t;
data_t a, b;
Prof. Sowmya K B 98
Example : Using structures and unions
package definitions;
typedef enum {ADD, SUB, MULT, DIV, SL, SR} opcode_t;
typedef enum {UNSIGNED, SIGNED} operand_type_t;
typedef union packed { logic [31:0] u_data;
logic signed [31:0] s_data;
} data_t;
typedef struct packed { opcode_t opc; operand_type_t op_type;
data_t op_a; data_t op_b; } instr_t;
endpackage

Prof. Sowmya K B 99
Dynamic Array

• A dynamic array is one dimension of an unpacked array


whose size can be set or changed at run-time.
Dynamic array is Declared using a empty word
subscript[].

• The space for a dynamic array doesn’t exist until the


array is explicitly created at run-time, space is allocated
when new[number] is called. number indicates the
number of space/elements to be allocated.

Prof. Sowmya K B 100


The syntax to declare a dynamic array is:

data_type array_name [ ];

Dynamic array methods are,


new[ ] --> allocates the storage.
size( ) --> returns the current size of a dynamic array.
delete( ) --> empties the array, resulting in a zero-sized array.

Prof. Sowmya K B 101


Example:

//declaration
bit [7:0] d_array1[ ];
int d_array2[ ];

//memory allocation
d_array1 = new[4]; //dynamic array of 4 elements
d_array2 = new[6]; //dynamic array of 6 elements

//array initialization
d_array1 = `{0,1,2,3};

foreach(d_array2[j])
d_array2[j] = j;

Prof. Sowmya K B 102


// change the length of the array after declaration/initialization
d_array1 = new[10]; //dynamic array of 10 elements

In the above syntax d_array1 will get allotted with 10 new memory
locations and old values of d_array1 will get deleted. old values of
d_array1 elements can be retained by extending the current array by
using below syntax.

//allocate 6 new elements and retain values of 4 elements.


d_array1 = new[10](d_array1);

//delete array
d_array1.delete( );

Prof. Sowmya K B 103


Example-1: Dynamic Array Decalaration, Allocation and Initialization .
module dynamic_array;
bit [7:0] d_array1[]; //dynamic array declaration
int d_array2[];
initial begin
$display("Before Memory Allocation");
$display("\tSize of d_array1",d_array1.size());
$display("\tSize of d_array2",d_array2.size());
d_array1 = new[4]; //memory allocation
d_array2 = new[6];
$display("After Memory Allocation");
$display("\tSize of d_array1 ",d_array1.size());
$display("\tSize of d_array2 ",d_array2.size());

Prof. Sowmya K B 104


d_array1 = ‘{0,1,2,3}; //array initialization
foreach(d_array2[j])
d_array2[j] = j;
$display("--- d_array1 Values are ---");
foreach(d_array1[i])
$display("\td_aaray1[%0d] = %0d",i, d_array1[i]);
$display("---------------------------------");
$display("--- d_array2 Values are ---");
foreach(d_array2[i])
$display("\td_aaray2[%0d] = %0d",i, d_array2[i]);
$display("---------------------------------");
end
endmodule
Prof. Sowmya K B 105
Simulator Output
Before Memory Allocation
Size of d_array1 0
Size of d_array2 0

After Memory Allocation


Size of d_array1 4
Size of d_array2 6

--- d_array1 Values are ---


d_aaray1[0] = 0
d_aaray1[1] = 1
d_aaray1[2] = 2
d_aaray1[3] = 3
---------------------------------
--- d_array2 Values are ---
d_aaray2[0] = 0
d_aaray2[1] = 1
d_aaray2[2] = 2
d_aaray2[3] = 3
d_aaray2[4] = 4
d_aaray2[5] = 5 Prof. Sowmya K B 106
queue
• A queue is a variable-size ordered collection of
homogeneous elements.

• queues can grow and shrink, queue supports


adding and removing elements anywhere.

• Queues are declared using the same syntax as


unpacked arrays, but specifying $ as the array
size. In queue 0 represents the first, and $
representing the last entree.
Prof. Sowmya K B 107
2
Prof. Sowmya K B 108
Prof. Sowmya K B 109
Queue operations
int j = 1,
b[$] = {3,4},
c[$] = {0,2,5};
initial
begin
c.insert(1, j);
c.insert(3, b);
c.delete(1);
// The rest of these are fast
c.push_front(6);
j = c.pop_back
q.push_back(8);
j = c.pop_front
foreach (c[i])
$display(c[i]);
c.delete();
Prof. Sowmya K B 110
end
{0,1,2,5}
{0,1,2,3,4,5}
{0,2,3,4,5}

{6,0,2,3,4,5}
{6,0,2,3,4} j=5
{6,0,2,3,4,8}
{0,2,3,4,8} j=6

Print entire queue


{} Prof. Sowmya K B 111
module queues_array;
bit [31:0] queue_1[$];
string queue_2[$];
initial begin
queue_1 = {0,1,2,3};
queue_2 = {"Red","Blue","Green"};

$display("----- Queue_1 size is %0d -----",queue_1.size());


foreach(queue_1[i]) $display("\tqueue_1[%0d] = %0d",i,queue_1[i]);
$display("----- Queue_2 size is %0d -----",queue_2.size());
foreach(queue_2[i]) $display("\tqueue_2[%0d] = %0s",i,queue_2[i]);

queue_2.insert(1,"Orange");
$display(“--Queue_2 size after inserting Orange is %0d --",queue_2.size());
foreach(queue_2[i]) $display("\tqueue_2[%0d] = %0s",i,queue_2[i]);

queue_2.delete(3);
$display(“--Queue_2 size after Delete is %0d-- ", queue_2.size());
foreach(queue_2[i])
$display("\tqueue_2[%0d] = %0s",i,queue_2[i]);
Prof. Sowmya K B 112
Simulator Output
----- Queue_1 size is 4 -----
queue_1[0] = 0
queue_1[1] = 1
queue_1[2] = 2
queue_1[3] = 3
----- Queue_2 size is 3 -----
queue_2[0] = Red
queue_2[1] = Blue
queue_2[2] = Green
--Queue_2 size after inserting Orange is 4 --
queue_2[0] = Red
queue_2[1] = Orange
queue_2[2] = Blue
queue_2[3] = Green
-- Queue_2 size after Delete is 3 --
queue_2[0] = Red
queue_2[1] = Orange
queue_2[2] = Blue Prof. Sowmya K B 113
module queues_array;
//declaration
bit [31:0] queue_1[$];
int lvar;

initial begin
//Queue Initialization:
queue_1 = {0,1,2,3};

//Size-Method
$display("\tQueue_1 size is %0d",queue_1.size());
//Push_front Method
queue_1.push_front(22);
$display("\tQueue_1 size after push_front is %0d",queue_1.size());

//Push_back Method
queue_1.push_back(44);
$display("\tQueue_1 size after push_back is %0d",queue_1.size());
//Pop_front Method
lvar = queue_1.pop_front();
$display("\tQueue_1 pop_front value is %0d",lvar);

//Pop_back Method
lvar = queue_1.pop_back();
$display("\tQueue_1 pop_back value is %0d",lvar);
Prof. Sowmya K B 114
end endmodule
Simulator Output
Queue_1 size is 4
Queue_1 size after push_front is 5
Queue_1 size after push_back is 6
Queue_1 pop_front value is 22
Queue_1 pop_back value is 44

Prof. Sowmya K B 115


Associative Arrays
• Associative array stores entries in a sparse matrix.
• When the size of the collection is unknown or the
data space is sparse, an associative array is a better
option.
• Associative array allocate the storage only when it is
used, unless like in the dynamic array we need to
allocate memory before using it
• In associative array index expression is not restricted
to integral expressions, but can be of any type.

Prof. Sowmya K B 116


Declaration of Associative Array

data_type array_name [index_type];

Where
data_type- data type of the array element
array_name- name of the associative array
index_type- datatype to be used as an index

Prof. Sowmya K B 117


Associative Array Methods:
num() -->returns the number of entries in the associative array.

delete(index) --> removes the entry at the specified index.

exists(index) --> returns 1 if an element exists at the specified index


else returns 0.

first(var) --> assigns the value of first index to the variable var.

last(var) --> assigns the value of last index to the variable var.

next(var) --> assigns the value of next index to the variable var.

prev(var) --> assigns the value of previous index to the variable var.
Prof. Sowmya K B 118
write a SystemVerilog code to create two
associative arrays. Perform operations on the
arrays to find
• size,
• first element,
• last element,
• previous element,
• next element in the array set
• and display the array.

Prof. Sowmya K B 119


module tb;
int fruits_l0 [string];
string fruits_l1 [int];
initial begin fruits_l0 = '{ "apple" : 4, "orange" : 10, "plum" : 9, "guava" : 1 };
fruits_l1 = '{ 34 : "Grapes", 22 : "Melon" };
// size()
$display ("[l0] size = %0d", fruits_l0.size());
$display ("[l1] size = %0d", fruits_l1.size());
// num()
$display ("[l0] num = %0d", fruits_l0.num());
$display ("[l1] num = %0d", fruits_l1.num());
// exists()
if (fruits_l0.exists ("orange"))
$display ("Found %0d orange !", fruits_l0["orange"]);
if (fruits_l1.exists (22))
$display ("Found 22 %s !", fruits_l1[22]);
if (!fruits_l0.exists ("apricots"))
$display ("Sorry, season for apricots isSowmya
Prof. overK...");
B 120
// first()
begin
string f;
if (fruits_l0.first (f))
$display ("fruits_l0.first [%s] = %0d", f, fruits_l0[f]);
end

// last() : string indices are taken in alphabetical order


begin string f;
if (fruits_l0.last (f))
$display ("fruits_l0.last [%s] = %0d", f, fruits_l0[f]);
end
Prof. Sowmya K B 121
// prev()
begin string f = "orange";
if (fruits_l0.prev (f))
$display ("fruits_l0.prev [%s] = %0d", f, fruits_l0[f]);
end

// next()
Begin
string f = "orange";
if (fruits_l0.next (f))
$display ("fruits_l0.next [%s] = %0d", f, fruits_l0[f]);
end
end
endmodule
Prof. Sowmya K B 122
Output:

Prof. Sowmya K B 123


State machine
RESETN

WAIT

INSTRUCTION==FETCH
/
WRITE

STORE LOAD
INSTRUCTION==FETCH
/
READ

Prof. Sowmya K B 124


State machine modeled with Verilog ‘define and parameter
constants
`define FETCH 3'h0
`define ADD 3'h2
`define SUB 3'h3
`define MULT 3'h4
`define DIV 3'h5
`define SHIFT 3'h6
`define NOP 3'h7
module controller (output reg read, write,
input wire [2:0]instruction, input wire
clock, resetN);

parameter WAITE = 0, LOAD = 1, STORE = 2;


reg [1:0] State, NextState;
Prof. Sowmya K B 125
always @(posedge clock, negedge resetN)
if (!resetN) State <= WAITE;
else State <= NextState;
always @(State)
begin
case (State)
WAITE: NextState = LOAD;
LOAD: NextState = STORE;
STORE: NextState = WAITE;
endcase
end
always @(State, instruction)
begin read = 0; write = 0;
if (State == LOAD && instruction == `FETCH)
read = 1;
else if (State == STORE && instruction == `FETCH)
write = 1;
end
Prof. Sowmya K B 126
endmodule
PACKAGE
package chip_types;
typedef enum {FETCH, WRITE, ADD, SUB, MULT, DIV, SHIFT, NOP } instr_t;
endpackage

import chip_types::*;

Prof. Sowmya K B 127


State machine
RESETN

WAIT

INSTRUCTION==
FETCH/WRITE

STORE LOAD

INSTRUCTION==
FETCH/READ

Prof. Sowmya K B 128


State machine modeled with enumerated types
package chip_types;
typedef enum {FETCH, ADD, SUB, MULT, DIV,
SHIFT, NOP }
instr_t;
endpackage

import chip_types::*;
module controller (output logic read, write, input
instr_t instruction, input wire clock, resetN);

enum {WAITE, LOAD, STORE} State, NextState;

Prof. Sowmya K B 129


always_ff @(posedge clock, negedge resetN)
if (!resetN)
State <= WAITE;
else
State <= NextState;
always_comb
begin
case (State) WAITE: NextState = LOAD;
LOAD: NextState = STORE;
STORE: NextState = WAITE;
endcase
end
always_comb
begin
read = 0; write = 0;
if (State == LOAD && instruction == FETCH)
read = 1;
else if (State == STORE && instruction == FETCH)
write = 1;
end
endmodule
Prof. Sowmya K B 130
Function

• A function cannot contain any time-controlled statements


like #, @, wait, posedge, negedge.

• A function cannot start a task because it may consume


simulation time, but can call other functions.

• A function should have atleast one input.

• A function cannot have non-blocking assignments or force-


release or assign-deassign.

• A function cannot have any triggers.

• A function cannot have an output or inout.


Prof. Sowmya K B 131
Ex:
function [7:0] sum;
input [7:0] a, b;
begin sum = a + b;
end
endfunction

// or
function [7:0] sum (input [7:0] a, b);
begin
sum = a + b;
end
endfunction

reg [7:0] result;


reg [7:0] a, b;
initial
begin a = 4; b = 5;
#10 result = sum (a, b);
end Prof. Sowmya K B 132
Difference between function and task
Function Task
Cannot have time-controlling Can contain time-controlling
statements/delay, and hence executes statements/delay and may only
in the same simulation time unit complete at some other time

Cannot enable a task Can enable other tasks and


functions
Should have atleast one input Can have zero or more arguments
argument and cannot have output or of any type
inout arguments

Can return only a single value Cannot return a value, but can
achieve the same effect using
output arguments
Prof. Sowmya K B 133
TASK
task sum (input [7:0] a, b, output [7:0] c);
begin c = a + b;
end
endtask

// or
task sum;
input [7:0] a, b;
output [7:0] c;
begin c = a + b;
end
endtask

initial
begin
reg [7:0] x, y , z;
sum (x, y, z);
end Prof. Sowmya K B 134
TASK & FUNCTIONS
Write a SystemVerilog code for writing task.

module main;
task t1();
$display("Inside Task : Before return statement");
return;
$display("Inside Task : After return statement");
endtask

initial
t1();

endmodule Prof. Sowmya K B 135


Write a SystemVerilog code for sum of
two integer using functions.
module fun();
int x; //function to add two integer numbers.
function int sum;
input int a,b;
return a+b;
endfunction

initial
begin x = 10 + sum(10,5);
$display("\tValue of x = %0d",x);
end
endmodule Prof. Sowmya K B 136

You might also like