0% found this document useful (0 votes)
37 views

Verilog 2internals

Mtech VLSI

Uploaded by

jerim57595
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Verilog 2internals

Mtech VLSI

Uploaded by

jerim57595
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Procedural Statements and Routines

3.1 Introduction
As you verify your design, you need to write a great deal of code, most of
which is in tasks and functions. System Verilog introduces many incremental
improvements to make this easier by making the language look more like C,
especially around argument passing. If you have a background in software
engineering, these additions should be very familiar.
3.2 Procedural Statements
System Verilog adopts many operators and statements from C and C+t.
You can declare a loop variable inside a £or loop that then restricts the scope
of the loop variable and can prevent some coding bugs. The increment ++ and
decrement -- operators are available in both pre- and post- form. If you have
a label on a begin or fork statement, you can put the same label on the
matching end or join statement. This makes it easier to match the start and
finish of a block. You can also put label on other System Verilog end
statements such as endmodule, endtask, endfunction, and others that
you will learn in this book. Example 3-1 demonstrates some of the new
constructs.

Example 3-1 New procedural statements and operators


initial
begin : example
integer array[ 10] , sun, j
Decl are i in for statement
tor (int i=0; i<10; i++) 1/ Increment 1
array[ i] = i;
// Add up values in the array
Sum array[9];

I/o.. .while loop


Sum + array(3]# 1/ Accumulate
while (3--); I Test it j=0
$display( " Sumt4d, sum) ; I/ 4d - specify width
end : example /End label

56 SystemVerilog for Verification

Two new statements help with loops. First, if you are in a loop, but want to
skip over rest of the statements and do the next ileration, use cont inue. If
you want to leave the loop immediately, use break.
The following loop reads commands from a file using the amazing file VO
code that is part of Verilog-2001. If the command is just a blank line, the code
just doesa continue and skips any further processing of thecommand. If the
command is "done," the code does a break to terminate the loop.
Example 3-2 Using break and continue while readinga file
initial begin
logic [127 :0] cmd;
integer £ile, C;

£ile = $£open( "comands.txt, "r);


while (1$£eo£(file)) begin
c= $fscanf (£ile, $s, cmd) ;
case (cnd)
continue I/ Blank line akip to loop end
"done ": break; I Done - leave loop
1/ Process other comnands here

endcase // case ( cmd)


end
$£close (file) ;
end

3.3 Tasks, Functions, and Void Functions

Verilog makes a very clear differentiation between tasks and functions.


The most important difference is that a task can consume time while a
function cannot. A function cannot have a delay, #100, a blocking statement
such as e(posedge clock) or wait (ready), or call a task. Additionally, a
Verilog function must return a value, and the value must be used, as in an
60 System Verilog for Verification

Example 3-11 Using ref across threads


task bus_read(input logic (31: 0] addr,
ref logic [31:0) data) ;

1/ Request bus and drive address


bus.request = 1'bl;
e(posedge bus.grant) bus . addr = addr;
/ Wait for data from memory
(posedge bus. enable) data bus.datas

i/ Release bus and wait for grant


bus.request = 1'b0
e(negeddge bus.grant) :
endtask

logic [31:0] addr, data;


initial
fork
bus_read ( addr, data):
begin
data ; | Trigger on data change
$display("Read th from bus", data):
end
join

In Example 3-11, the initial block can access the data from memory as
soon as bus.enable is asserted, even though the bus_read task does not
return until the bus transaction completes, which could be several cycles later.
Since the data argument is passed as ref, the edata statement triggers as
soon as data changes in the task. If you had declared data as output, the
edata statement would not trigger until the end of the bus transaction.

3.5.4 Default Argument Values


As your testbench grows in sophistication, you may want to add additional
controls to your code but not break existing code. For the function in Example
3-10, you might want to print a sum of just the middle values of the array.
However, you don't want to go back and rewrite every call to add extra
arguments. In SystemVerilog you can specify a default value that is used if
you leave out an argument in the call.
8:54 9 i 53 O86%

< System verilog...


6.15.1 Pseudorandom number generators
erilos uses a simple PRNG that you could uccess with the $random
eenerator has an internal stale that you can set by providing a
function.
seed to $random. AII IEEE-1364-compliant Verilog simulators use the sarme
algorithm to caleulate values.

178 System Verilog for Verification

Example 6-57 shows a simple PRNG, not the one used by SystemVerilog.
The PRNG has a 32-bit state. To caleulate the next random value, Kquare the
stale to produce a 64-bit value, take the middle 32 bits, then add the original
value.
Exumple6-57 Smple pseudarandon number generator
reg (3l:0) state 32"hl2345678;
Eunction reg [31:0) y_ randomp
reg [63 10) 641
tate:
te te64 >> 16) Btate
my _random state;
endfunction

You can see how this simple code produces a stream of values thal seem
random, but can be repeated by using the same seed value. SystemVerilog
calls its PRNG for a new values for randoad se and randcase.

6.15.2 Random Stability -multiple generators

Verilog has a single PRNG that is used for the er W


would happen if SystemVerilog kept this approach? 204/326 h
several stimulus generators running in parallel. creat1. esi,
under test. If two streams shure the same PRNG, they cach get a subset of the
rundom values.
Flgure 6-3 Shuring a single randam genetatot
PRNG
b,c
d
h,
class danl class den2
Transaction tr) Transaction trl, tr2;

forever (intl,cb) Eorever (int2. cb)


tr.randamige ) trl.randoaie()#
endelass tr2.randomige()
endclass

In Figure 6-3, there Iwo stimulus generators and a single


ducing values a, b, c, etc. Gen2 has two random object
cycle, it uses twice as muny random values as Ganl probl
Chapter 3: Procedural Statements and Routines 59

3.5.3 Advanced Argument Types


Verilog had a simple way to handle arguments: an input or inout was
copied to a local variable at the start of the routine, while an output or
inout was copied when the routine exited. No memories could be passed into
a Verilog routine, only scalars.
In SystemVerilog. you can specify that an argument is passed by
reference. rather than copying its value. This argument type, ret, has several
benefits over input, output, and inout. First. you can now pass an array
Into a rOutine.

Example-10 Passing arrays using ref and const


function void print_ sum (const ref int a[I);
Ant gum
£or (int i=0; ica.size; i++) begin
sum += alil;
$display ("The sum of the arrays i s . sum) }
endfunction

SystemVerilog allows you to pass array arguments without the ref


direction, but the array is copied onto the stack, an expensive operation for all
but the smallest arrays.
Example 3-10 also shows the const modifier. As a result, the array a is
initialized when print_sum is called, but cannot be modified in the routine.
Always use ret when passing arrays to a routine. If you don't
want the routine to change the array values, use the const
ref type. With this, the compiler checks that ye
not modify the array. 87/326
The second benefit of ref arguments is that a task can modify a variable
and is instantly seen by the calling function. This is useful when you have
several threads executing concurently and want a simple way to pass
information. See Chapter 7 for more details on using tork-join.

60 SystemVerilog for Verification

Example 3-11 Using ref acrOss threads


task bus _read(input logic (31:0] addr,
ref logic [31:0] data) ;

1/ Request bus and rive address


bus.request 1'bl:
e(posedge bus.grant) bus.addr = addr;
II Wait for ata fram memory
e(posedge bus. enable) data = bus.data;

// Release bus and wait for grant


bus.request = 1'b0;
(negedge bus.grant) :
endtask

logic (31:0] addr, data;


initial
fork
bus read (addr, data):
begin
data; I/ Trigger on data change
$display("Read th from bus", ata);
end
join
constant. Use a separate assignment statement to give you
better control over when initialization is done.

64 SystemVerilog for Verification

The following task looks at the bus after five cycles and then creates a
local variable and attempts to initialize it to the current value of the address
bus,

Example 3-20 Static initialization bug


program initialization; I| Buggy version
task aheck bus:
repeat (5) (posedge clock)
i£ (bus_cmd m 'READ) begin
I/ When is local_addr initialized?
reg (7:0] local_addr addr<e2} // Bug
$display( "Local Addr th, local_addr ):
end
endtask
endprogram

The bug is that the variable local_addr is statically allocated, so it is


actually initialized at the start of simulation, not when the begi
is entered. Once again. the solution is to declare the program a! 92/326
Example 3-21 Static initialization fix: use automatic
program automatic initialization; /I Bug solved
endmodule

3.8 Time Values


SystemVerilog has several new constructs to allow you to unambiguously
specify time values in your system.

3.8.1 Time units and precision


When you rely on the timescale compiler directive, you must compile
the files in the proper order to be sure all the delays use the proper scale and
precision. The timeunit and timeprecision declarations eliminate this
ambiguity by precisely specifying the values for every module. Example 3-22
shows these declarations. Note that if you use these instead of timescale,
you must put them in every module that has a delay.
3,8.2 Time literals
SystemVerilog allows you to unambiguously specify a time value plus
units. Your code can use delays such as 0.1ns or 20ps. Just remember to use
timeunit and timeprecision or tines cale. You can make your code

Chapter 3: Procedural Statements and Routines 65

even more time aware by using the classic Verilog $timeformat and
$realtime routines.
Example 3-22 Time literals and Stime format
module tining:
timeunit lns
timeprecision lps
initial begin
$timefornat (-9, 3, "ns", 8);
$display( "@tt", $realtime) I/ 1.00Ons
W2ns $display( "@%t", $realtine) ; I7 3.000ns
#0.lns $display ("@tt", $realtine ) 17 3.100ns
W41ps $display("tt, $realtina ) 17 3.14lns
end
endmodule
Chapter 6.: Randomization 157

function does not return a value, but, because il is not a task, does not con
sume time. If you wunt to call a debug routine from pre_randoize or
Post randomize, it must be a function.

6.9.1 Building a bathtub distribution

For some applications, you want a nonlinear rundom distribution. For


instance, small and large packets are more likely to find a design bug such as
buffer overflow than medium-sized packets. So you want a bathtub shaped
distribution; high on both ends, and low in the middle. You could build an
elaborate dist constraint, but it might require lots of tweaking to get the
shape you want. Veilog has several functions for nonlinear distribution such
as $dist._exponential but none for a bathtub. However. you can build one
by using the exponential function twice.
Figure 6- Bulding abathtub distribution

Sum isa
Left bathtub Right
Exponentlal Exponential

Values WLDIT
Example 6-24 Building a bathtuh distribution
class Bathtub
int value; /I Random variable with bathtub dist
int WIDTH 50, DEPTH=4, seedel

tunction void pre_randomize()i


1/ Calculate the left curve of the tub
value $dist_exponential(seed, DEPTH) ;
1t (value > WIDTH) value WIDTH)

7 Randomly put this point on the left or right curve


L£ ($urandom_range(1))
WIDTH- value
endfunction
endelass

183/326

158 SystemVerilog for Verification

Every time this object is randomized. the variable value gets updated.
Across many rundomizations. you will see the desired nonlinear distribution.
You can use all the Verilog-1995 distribution functions this way. plus sev
eral that are new for SystemVerilog. Some of the useful functions include the
following.

$dist_exponential -Exponential decay, as shown in Figure 6-I


$dist_nornal - Bell-shaped distribution
$dist poisson Bell-shaped distribution
$dist_uni£orm Flat distribution
$random -Flat distribution, returning signed 32-bil random
^urandan-Flat distribution, retuning unsigned 32-bit random
^urandom_range - Flat distribution over arange
Consult a statistics book for more details on these functions.

6.9.2 Note on void functions


I57
Chapter6: Randomization
not con
value, but, because it is not a task, does
e on
function does not return a call a debug routine from pre_randoni
to
sume time. If you want function.
post_randoaize, it must be
distribution
Building a bathtub
6.9.1
random distribution. For
For some applica you want a nonlinear bug such as
instance, small and cation ets-sizedare
more likely to find a design shaped
packets. So you wanta bathtubbuild an
buffer overflow han meaium You could
distribution: high on b ends, and low in the middle.
but it might require lots of tweaking to get the
elabarate ist constraint, several functions for nonlinear distribution such
shupe you want. Ver ghas build one
$dist_exponent but none for a bathtub. However, you can
as
function twice.
by using the exponential
Fgure 6- Buikding a hathtub distribution

Sum isa
bathtub Right
&Exponential
Left Exponential

WPLDNH
lo Values
Example 6-24 Huilding a bathtub distr1bution
class Bathtub dist
Lnt value ; I| Randam variable writh bathtub
seedul
int WIDTH = 50, DEPTH=4,
tunction void pre_randomize()p
culate the left curve of the tub
value $dist exponential(seed,, DEPTH)
WIDTH) value WIDTH)
if (value
left or right curve
17 RaDdomly put this point on the
if ($urandom range (1))
value WIDTH - value;
endfunction

ondclass
People also ask

What is strobe control method of


asynchronous data transfer with neat
diagrams?

The strobe controltechnique of asynchronous


data transfer operates a single control line to
time each transfer. The strobe can be activated
unit. The
by either the source or the destination
diagram shows a source-initiated transfer. The
data bus gives the binary data from the sOurce
unit to the destination unit. 24 Jul 2021

https://www.tutorialspoint.com » wh...
What is Strobe Control? - Tutorialspoint

MORE RESULTS

What is the strobe method?

What is strobe in microprocessor?


8:50 t Bl 69%

UPSC Fever X

Data bus
Source Destination
unit Strobe unit

(a) Block diagram

Data -Valid data

Strobe

(b) Timing diagram


Figure 3 Source-initiated strobe for data transfer.

Computer Organization and Visit >


Architecture (Asynchronous Dat...
Images may be subject to copyright. Learn more

Share Save

Data
Dnta Bus
Strobe

Buck Dagta
(Beck dagrun

Des ha

Computer Organisation A.
Computer Organisation ..

te us

Data Vald

* Q
Discover Search Saved
8:45 49" l 70%

< 50

166 System Verilog for Verification

with thousands or millions of elements, which can cause the random solver to
take an excessive amount of time.

6.12.2 Sum of elements

You can send a random array of data into a design, but you can also use it
to control the flow. Perhaps you have an interface that has to transfer four data
words. The words can be sent consecutively or over many cycles. A strobe
signal tells when the data is valid. Here are some legitimate strobe pattems.
sending four values over ten cycles.
62 Randam strube wavelams

You can create these putterns using a random urray. Constrain it to have
four bils enabled out of the entire range using the sun function.
Example 6-36 Random strobe pattem class
paraneter NAX_TRANSPER_LEN = 10;
class StrobePati
rand bit utrobe [AX TRANSP
traint C se {Btrobe.f
endglasg

Edit Annotate Fill &Sign Convert All


3.5 Routine Arguments
Many of the SystemVerilog improvements for routine make it easier to
declare arguments and expand the ways you can pass values to and from a
routine.

3.5.1 C-style Routine Arguments


SystemVerilog and Verilog-2001 allow you to declare task and function
arguments more cleanly and with less repetition. The following Verilog task

In general, a routine definition or call with no arguments does not need the empty parentheses (). This
book leaves them out except as heeded for clarity

58 SystemVerilog for Verification

requires you to declare some arguments twice, once for the direction, and
once for the type.
Example 3-6 Verilog-1995 routine arguments
task mytask2;
output [31:0) x
reg (31:0) x;
input Y;

endtask

With System Verilog. you can use the less verbose C-style. Note that you
should use the universal input type of logic.
Example 3-7 C-style routine arguments
task mytaskl (output logic [3l:0) x,
input logic y):

endtask

3.5.2 Argument Direction


You can take even more shortcuts with declaring routine arguments. The
direction and type default to "input logic" and are sticky, so you don't have to
repeat these for similar arguments. Here is a routine header written using the
Verilog-1995 style.
Example 3-8 Verbose Verilog-style routine arguments
task T31
input a, bË
logic a, bË
output [15:0] u, vË
bit (15:0] u, Vi

endtask

You could rewrite this as follows.


Example 3-9 Routine urguments with sticky types
task T3(a, b, output bit [15:0] u, v)i

The arguments a and b are input logic, Ibit wide. The arguments u and v
are 16-bit output bit types.

Chapter 3: Procedural Statements and Routines 59

3.5.3 Advanced Argument Types


when one of the classes changes. Genl gets an additional random variable,
and so consurnes two randor values every time it is called.

Figure 64 Firt generator uses additional values


PRNG
c.d

k.

class Genl; class Gen21


Transaction tra, trbj Transaetion trl, tr2;
Lorever e(intl. cb) torever e(int2.cb)
a.rndoai e() Crl.randoni e()
andaaie()a andomize( )
endclass ndclaBs

This approuch changes the values used not only by Genl, but also by
Gen2.
In SystemVerilog, there is a separate PRNG for every object and thread.
Changes to one object don't affect the random values seen by others.
Figure 6-5 Separate random generaton pet object
PRNG 1 PRNG 2
a,b
O.p
e,
class denl; class Gen2
Transaction tra, trb Transaetion trl, tr2,

Lorever (intl.cb) Lorever e(int2.cb)

trb.randonise()
endclass
tr2.rAndomise()
andclas

6.15.3 Rundom Slability -hierarchical seeding

Every object und thread huve its own PRNG and unique seed. When a new
object or thread is started, its PRNG is seeded frum its purent's PRNG. Thus a

205/326

I80 System Verilog for Verification

single seed specified ut the start of simulation can create many streans of ran
dom stimulus, euch distinct.

6.16 Random Device Configuration


An important part of your DUT to test is the configuration of
both the internal DUT settings and the system that surrounds i
As described in section 6.2.1, your tests should randomize the
environment so that you can be confident it has been tested in
as many modes as possible.
Example 6-58 shows how to create a random testbench configuration and
modify its results as needed at the test level. The eth_cfg class describes the
configuration for a 4port Ethernet switch. It is instantiated in an environment
class, which in turn is used in the test. The test overrides one of the configura
tion values, enabling all 4 ports.
Example 6-58 Ethernet switch configuration ciass
class eth_cfgi
rand bit [ 3:0J in_use; Ports usedd in test
rand bit (47:0] nac_addr (4]; I/ MAc addresses
rand bit ( 3:0) is_100; I/ 100mb mode

You might also like