Vous êtes sur la page 1sur 120

Verilog

-Introduction
Lecture 3

Amit Degada

Asst Prof, EC
IT-NU
Amit.degada@nirmauni.ac.in
www.adsignals.wordpress.com
DSD

Presentation Outline
Detailed Verilog Program structure
Verilog Lexical Convention
Verilog Behavioral Modeling

DSD

Verilog Program Structure


module <module_name> (<port_list>);
Port Declaration
Data type Declaration
Circuit Functionality
Timing Specification

Begins
Beginswith
withkeyword
keywordmodule
module
and
andends
endswith
withendmodule
endmodule
The<module
The<modulename>is
name>isan
an
identifier
identifierthat
thatuniquely
uniquelynames
names
the
themodule.
module.All
Allthe
therules
rulesof
ofCC
identifier
identifierare
areapplicable.
applicable.i.e.
i.e.itit
Must
Muststart
startwith
withalphabets,
alphabets,
should
shouldnot
notstart
startwith
withnumb
numbor
or
special
specialcharacter.
character.ItItshould
shouldnot
not
End
Endwith
withspecial
specialcharacter
character

endmodule

2016

Three Ways to Specify the Module


1.Behavioral
2.Data-flow
3.Structural
DSD

Verilog Program Structure


module <module_name> (<port_list>);
Port Declaration
Data type Declaration

The<port
The<portlist>is
list>isaalist
listof
ofinput,
input,
inout
inoutand
andoutput
outputports
portswhich
which
are
areused
usedto
toconnect
connectto
toother
other
modules.
modules.
e.g.
e.g.a,b,c
a,b,c

Circuit Functionality
Timing Specification
endmodule

2016

DSD

Verilog Program Structure


module <module_name> (<port_list>);
Port Declaration
Data type Declaration
Circuit Functionality

In
Inport
portdeclaration
declarationregion,
region,the
the
Ports
Portsspecified
specifiedin
in<port_list>
<port_list>are
are
Specifically
Specificallymention
mentionas
asinput,
input,
output
outputand
andinout
inout
e.g
e.g input
inputa;
a;
output
outputb;
b;
input
inputc;
c;

Timing Specification
endmodule

2016

DSD

Port Declaration
module <module_name> (<port_list>);
Port Declaration
endmodule
Syntax:

<port direction> [port size] port name, port name,;


input
output
inout

2016

Port size range from [msb:lsb]


Either little endian or big endian
Max port size is 256

DSD

Port Declaration
Examples:
Examples

Notes

input a,b,sel;

3 scalar ports

output [7:0] result;

little endian convention

inout [0:15] data_bus;

big endian convention

input [15:12] addr;

msb:lsb may be any integer

parameter word = 32;

constant expressions may be


used

input [word-1:0] addr;

Verilog Program Structure


module <module_name> (<port_list>);
Since
Sincethe
thepurpose
purposeof
ofthe
thepurpose
purpose
of
ofVerilog
VerilogHDL
HDLisisto
tomodel
modeldigital
digital
hardware,
hardware,the
theprimary
primarydata
datatypes
types
are
arefor
formodeling
modelingregisters
registers(reg)
(reg)and
and
net.
net.Typical
Typicallogic
logicvalues
values
are
are0,1,
0,1,x/X
x/Xand
andz/Z
z/Z

Port Declaration
Data type Declaration
Circuit Functionality
Timing Specification
endmodule

2016

DSD

Verilog Program Structure


module <module_name> (<port_list>);
Data type Declaration

Data types are classified as:


1.register
2.net

endmodule
Syntax:

<register/net> [size] #(delay) name, name,;


delay (optional) may only be specified on net data types
size is a range from [msb : lsb] (most-significant-bit to leastsignificant-bit)
The msb and lsb must be integers
Either little-endian convention (the lsb is the smallest bit
number) or big-endian convention (the lsb is the largest bit
number) may be used.
The maximum vector size is at least 65,536 bits (216).

2016

DSD

Rule to Remember
General Rules For Choosing The Correct Data
Type Class
when a signal is driven by a module output, a
primitive output, or a continuous assignment
use a net type
when a signal is assigned a value in a Verilog
procedure use a variable type

2016

DSD

10

net Vs. reg


net

Variable

Variable data types are used as


temporary
storage
of
programming data
Variables can only be assigned a
value from within an initial
procedure, an always procedure,
a task or a function.
Variables can only store logic
values; they cannot store logic
strength.
Variables are un-initialized at
the start of simulation, and will
contain a logic X until a value is
assigned.

Net data types are used to


make
connections
between
parts of a design
Nets reflect the value and
strength level of the drivers of
the net or the capacitance of
the net, and do not have a
value of their own.
Nets
have
a
resolution
function, which resolves a final
value when there are multiple
drivers on the net.

2016

DSD

11

1. register data type


Keyword
reg
integer
time
real or realtime

Functionality
unsigned variable of any bit size
signed 32-bit variable
unsigned 64-bit variable
double-precision
variable

floating

point

Register retains last value (not logic strength) assigned


to it
A variable data type must be used when the signal is
on the left-hand side of a procedural assignment
In verilog2001, its referred as variable
12

2. net data type


Keyword
wire or tri

Functionality
Simple interconnecting wire

wor or trior Wired outputs OR together


wand or
triand
tri0
tri1

Pulls down when tri-stated


Pulls up when tri-stated

supply0

Constant logic 0 (supply strength)

supply1

Constant logic 1 (supply strength)

trireg

Wired outputs AND together

Stores last value when tri-stated (capacitance strength)

Net data types connect structural components together.


Nets transfer both logic values and logic strengths.
A net data type must be used when:

A signal is driven by the output of some device.


A signal is also declared as an input port or inout port.
A signal is on the left-hand side of a continuous assignment.

13

Examples
Data Type Examples

Notes

wire a, b, c;

3 scalar nets

tri1 [7:0] data_bus;

8-bit net, pulls-up when tri-stated

reg [1:8] result;

an 8-bit unsigned variable

a memory array; 8-bits wide, with


1K of addresses (1D Array)
a 2-dimensional array of 8-bit
wire [7:0] Q [0:15][0:256];
wires
reg [7:0] RAM [0:1023];

14

other data type


Other
Types

Functionality

Run-time constant for storing integers, real


parameter numbers, time, delays, or ASCII strings. Parameters
may be redefined for each instance of a module.
specparam

Specify block constant for storing integers, real


numbers, time, delays or ASCII strings

event

A momentary flag with no logic value or data


storage. Often used for synchronizing concurrent
activities within a module.

15

Examples
Data Type Examples
parameter [2:0] s1 = 3b001,
s2 = 3b010,
s3 = 3b100;
parameter integer period = 10;

Notes
three 3-bit constants
an integer constant

localparam signed offset = -5;

an 8-bit unsigned variable

event data_ready, data_sent;

two event data types

16

Verilog Program Structure


module <module_name> (<port_list>);
Continuous
Continuousassignments
assignmentsuse
usethe
the
keyword
keywordassign
assignwhereas
whereas
procedural
proceduralassignments
assignmentshave
have
the
theform
form
<reg
<regvariable>
variable>==<expression>
<expression>
where
wherethe
the<reg
<regvariable>
variable>must
mustbe
be
aaregister
registeror
ormemory.
memory.
Procedural
Proceduralassignment
assignmentmay
mayonly
only
appear
appearin
ininitial
initialand
andalways
always
constructs.
constructs.

Port Declaration
Data type Declaration
Circuit Functionality
Timing Specification
endmodule

2016

DSD

17

Verilog Program Structure


module <module_name> (<port_list>);
Port Declaration
Data type Declaration
Circuit Functionality

This
Thisisisbeyond
beyondthe
thescope
scopeof
ofthe
the
syllabus,
syllabus,will
willbe
beexplored
exploredififtime
time
permits
permitsat
atlater
laterpart
partof
ofthe
the
semester
semester

Timing Specification
endmodule

2016

DSD

18

Verilog Program Structure


module <module_name> (<port_list>);
module_port_declarations
data_type_declarations
module_instances
primitive_instances
procedural_blocks
continuous_assignments
task_definitions
function_definitions
specify_blocks

We will see each of them in detail

endmodule

2016

DSD

19

Verilog Program Structure


module <module_name> (<port_list>);
module_instances
primitive_instances
procedural_blocks
endmodule

Explicit

Implicit

module module_name (.port_name


(signal_name ), .port_name
(signal_name ), ... );

module module_name
(port_name,
port_name, ... );

module_items

module_items

endmodule

endmodule
2016

Port list can be specified in


two way
1.Implicit
2.Explicit
Useful while using module
instances,
primitive
instances

DSD

20

Verilog reserved keywords


Dont
use any
Keyword
as
identifie
r name

always
and
assign
attribute
begin
buf
bufif0
bufif1
case
casex
casez
cmos
deassign
default
defparam
disable
edge
else
end
endattribute
endcase
endfunction

endmodule
endprimitive
endspecify
endtable
endtask
event
for
force
forever
fork
function
highz0
highz1
if
ifnone
initial
inout
input
integer
join
medium
module

large
macromodul
e
nand
negedge
nmos
nor
not
notif0
notif1
or
output
parameter
pmos
posedge
primitive
pull0
pull1
pulldown
pullup
rcmos
real
realtime

reg
release
repeat
rnmos
rpmos
rtran
rtranif0
rtranif1
scalared
signed
small
specify
specparam
strength
strong0
strong1
supply0
supply1
table
task
time
tran

tranif0
tranif1
tri
tri0
tri1
triand
trior
trireg
unsigned
vectored
wait
wand
weak0
weak1
while
wire
wor
xnor
xor

21

Verilog Lexical Convention


1.White Space Keywords
2.Comments
3.Case Sensitivity
4.Identifiers(names)
5.Logic Values
6.Logic Strength
7.Literal Integer numbers
8.Literal real numbers

DSD

22

1. White Space

blanks, tabs,
newlines (carriage return),
formfeeds
EOF (end-of-file).

23

2. Comments
// begins a single line
terminated by a newline.

comment,

/* begins a multi-line
terminated by a */

comment,

24

3. Case sensitivity
Verilog is case sensitive.
Lower case letters are unique from
upper case letters
All keywords we write in small letters

25

4. Identifiers (names)
Must begin with alphabetic or underscore
characters a-z, A-Z, _
May contain the characters a-z, A-Z, 0-9, _ and $
Examples
adder

Notes
legal identifier name

XOR

uppercase identifier
from xor keyword

is

unique

\reset*

an escaped identifier (must be


followed by a white space)

26

Escaped Identifier
Verilog HDL allows any character to be used in an identifier by
escaping the identifier. Escaped identifiers provide a means of
including any of the printable ASCII characters in an
identifier (the decimal values 33 through 126, or 21 through 7E
in hexadecimal).
Escaped identifiers begin with the back slash ( \ )
Entire identifier is escaped by the back slash.
Escaped identifier is terminated by white space (Characters such
as commas, parentheses, and semicolons become part of the
escaped identifier unless preceded by a white space)
Terminate escaped identifiers with white space, otherwise
characters that should follow the identifier are considered as part
of it.

27

Escaped Identifier
// There must be white space after the
// string which uses escape character
module \1dff (
q,
\q~ ,
d,
cl$k,
\reset*
);

//
//
//
//
//

Q output
Q_out output Escaped Identifier
D input
CLOCK input
Reset input Escaped identifier

input d, cl$k, \reset* ;


output q, \q~ ;

endmodule
28

5. Logic Values
The Verilog HDL has 4 logic values.
Logic Value

Description

zero, low, or false

one, high, or true

z or Z

high impedance (tri-stated or


floating)

x or X

unknown or uninitialized

29

6. Logic Strengths
The Verilog HDL has 8 logic strengths: 4 driving, 3 capacitive, and high impedance (no
strength).

Strength
Level

Strength Name

Specification
Keyword

Display
Mnemonic

Supply Drive

supply0

supply1

Su0

Su1

Strong Drive

strong0

strong1

St0

St1

Pull Drive

pull0

pull1

Pu0

Pu1

Large Capacitive

La0

La1

Weak Drive

We0

We1

Med. Capacitive

medium

Me0

Me1

Small Capacitive

small

Sm0

Sm1

High Impedance

HiZ0

HiZ1

large
weak0

highz0

weak1

highz1

The cap_strength is for trireg nets only.

30

7. Literal Integer Number


Syntax:
<size><base><value>
size (optional) is the number of bits in the
number. Unsized integers default to at least
32-bits.
'base (optional) represents the radix. The
default base is decimal.

31

7. Literal Integer Number


Base

Symbol

Legal Values

binary

or

0, 1, x, X, z, Z, ?, _

octal

or

0-7, x, X, z, Z, ?, _

decimal

or

0-9, _

hexadecimal

or

0-9, a-f, A-F, x, X, z, Z, ?,

The ? is another way of representing the Z logic value.


An _ (underscore) is ignored (used to enhance readability).
Values are expanded from right to left (lsb to msb).
When size is less than value, the upper bits are truncated.
When size is larger than value, and the left-most bit of value is 0 or
1, zeros are left-extended to fill the size.
When size is larger than value, and the left-most bit of value is Z or
X, the Z or X is left-extended to fill the size.

32

7. Literal Integer Number


Examples:
Examples
10

Size
unsized

Base
decimal

Binary Equivalent
0...01010 (32-bits)

'o7

unsized

octal

1'b1

1 bit

binary

8'Hc5

8 bits

hex

11000101

6'hF0

6 bits

hex

110000

(truncated)

6'hF

6 bits

hex

001111

(zero filled)

6'hZ

6 bits

hex

ZZZZZZ

(Z filled)

0...00111

(32-bits)

33

8. Literal Real Number


Syntax:
<value>.<value>
<base>E<exponent>
Real numbers are limited to the values 0-9
and underscore.
There must be a value on either side of the
decimal point.

34

8. Literal Real Number


Examples:
Examples Notes
Value 0.5
0.5
must have value on both sides of
decimal point
3 times 104 (30000)
3e4
5.8 times 10-3 (0.0058)
5.8E-3

35

Verilog

-Behavioral Modeling

DSD

36

Behavioral Modeling
In complex digital design, some decision
(e.g. trade-offs of various architecture
and algorithms) need to be made earlier
Verilog has the feature to specify the
design functionality (or may be called
behavior) in algorithmic manner
Behavioral constructs are similar to any
HLL like C, and Verilog has reach
behavioral construct

DSD

37

Learning Objective
Significance of structured procedures: always and
initial
Define blocking and non-blocking procedural assignment
Use of
level-sensitive Timing control
Conditional statements like if and else
Multiway branching, using case, casex and casez
Looping statements, such as while, for, repeat and
forever
Understand the delay based timing control mechanism
(regular delays, intra-assignment delay, zero delay)
Define sequential and parallel blocks
Naming of blocks and disabling of named blocks
38

Structured Procedures
Two basic structured procedure statements
always
initial
All behavioral statements appear only inside these
blocks
Each always or initial block has a separate activity
flow (multithreading, concurrency)
Start from simulation time 0
No nesting

Structured Procedures:
initial statement
Starts at time 0
Executes only once during a simulation
Multiple initial blocks, execute in parallel
All start at time 0
Each finishes independently

Syntax:
initial
begin
// behavioral statements
end

Structured Procedures:
initial statement (contd)
Example:
module stimulus;
reg x, y, a, b, m;

initial
#50 $finish;
endmodule

initial
m= 1b0;
initial
begin
#5 a=1b1;
#25 b=1b0;
end
initial
begin
#10 x=1b0;
#25 y=1b1;
end
2016

DSD

41

Initializing variables
Ordinary style, using initial block
reg clock;
//the clock variable is defined first
initial clock = 0; //the value of clock is set to 0

Combined declaration and initialization


reg clock = 0; //Equaillent of above two statements
module adder (
output reg [7:0] sum = 0,
output reg
co = 0,
input
[7:0] a, b,
input
ci);
...
endmodule

Structured Procedures:
always statement
Start at time 0
Execute the statements in a looping
fashion (Digital Hardware engineer
consider as repeated activity in digital
circuit)
Example

Example 7.5

44

Procedural Assignments
Assignments inside initial and
always
To update values of register data
types
The value remains unchanged until
another procedural assignment updates it
Compare
to
continuous
assignment
(Dataflow Modeling)

Procedural Assignments
(contd)
Syntax
<lvalue> = <expression>
<lvalue> can be

reg, integer, real, time


A bit-select of the above (e.g., addr[0])
A part-select of the above (e.g., addr[31:16])
A concatenation of any of the above

<expression> is the same as dataflow modeling


What happens if the widths do not match?

LHS wider than RHS => RHS is zero-extended


RHS wider than LHS => RHS is truncated (Least significant
part is kept)

Blocking Procedural
Assignments
The two types of procedural assignments
Blocking assignments
Non-blocking assignments

Blocking assignments

are executed in order (sequentially)


Example:
reg x, y, z;
reg [15:0] reg_a, reg_b;
integer count;
initial begin
x=0; y=1; z=1;

All executed at time 0

count=0;
reg_a= 16b0; reg_b = reg_a;
executed at time 15
#15 reg_a[2] = 1b1;
#10 reg_b[15:13] = {x, y, z};
count = count + 1;
All executed at time 25
end

Non-Blocking Procedural
Assignments
Non-blocking assignments

Processing of the next statements is not blocked for this one


Transactions created sequentially (in order), but executed
after all blocking assignments in the corresponding
simulation cycle
Syntax:
<lvalue> <= <expression>

Example:

reg x, y, z;
reg [15:0] reg_a, reg_b;
integer count;
initial begin
x=0; y=1; z=1;

All executed at time 0

count=0;

reg_a= 16b0; reg_b = reg_a;


reg_a[2] <= #15 1b1;
reg_b[15:13] <= #10 {x, y, z};
count <= count + 1;
end

Scheduled to run at time 15


Scheduled to run at time 10
48

Non-Blocking Assignments
(contd)
Application of non-blocking assignments
Used to model concurrent data transfers
Example: Write behavioral statements to swap
values of two variables
always
begin
reg1
reg2
reg3
end

@(posedge clock)
<= #1 in1;
<= @(negedge clock) in2 ^ in3;
<= #1 reg1;
The old value of reg1 is used

Race Condition
When the final result of simulating two (or more)
concurrent processes depends on their order of
execution
Example:
always
b =
always
a =

@(posedge clock)
a;
@(posedge clock)
b;

Solution:

always @(posedge clock)


b <= a;
always @(posedge clock)
a <= b;

always @(posedge clock)


begin
temp_b = b;
temp_a = a;
b = temp_a;
a = temp_b;
end

Race Condition (contd)


Recommendation
Concurrent data transfers => race
condition
Use
non-blocking
assignments
for
concurrent data transfers
Example: pipeline modelling
Disadvantage:
Lower simulation performance
Higher memory usage in the simulator

Behavioral Modeling Statements:


Conditional Statements

Just the same as if-else in C


Syntax:
if (<expression>) true_statement;
if (<expression>) true_statement;
else false_statement;
if (<expression>) true_statement1;
else if (<expression>) true_statement2;
else if (<expression>) true_statement3;
else default_statement;

True is 1 or non-zero
False is 0 or ambiguous (x or z)
More than one statement: begin end

Example 7-18

53

Behavioral Modeling Statements:


Multiway Branching
Similar to switch-case statement in C
Syntax:
case (<expression>)
alternative1: statement1;
alternative2: statement2;
...
default: default_statement; // optional
endcase

Notes:

<expression> is compared to the alternatives in the


order specified.
Default statement is optional

Multiway Branching (contd)

Examples:
To be provided in the class

Now, you write a 4-to-1 multiplexer.

Multiway Branching (contd)

The case statements compare <expression> and alternatives


bit-for-bit
x and z values should match
See Example 7-20

module demultiplexer1_to_4(out0, out1, out2, out3, in, s1, s0);


output out0, out1, out2, out3;
input in, s1, s0;
always @(s1 or s0 or in)
case( {s1, s0} )
2b00: begin ... end
2b01: begin ... end
2b10: begin ... end
2b11: begin ... end
2bx0, 2bx1, 2bxz, 2bxx, 2b0x, 2b1x, 2bzx:
begin ... end
2bz0, 2bz1, 2bzz, 2b0z, 2b1z:
begin ... end
default: $display(Unspecified control signals);
endcase
endmodule

Multiway Branching (contd)


casex and casez keywords

casez treats all z values as dont care


casex treats all x and z values as dont care

Example: 7-21

Behavioral Modeling Statements:


Loops
Loops in Verilog
while, for, repeat, forever

The while loop syntax:


while (<expression>)
statement;

while Loop Example


To be provided in the class

Loops (contd)
The for loop
Similar to C
Syntax:
for( init_expr; cond_expr; change_expr)
statement;

Example:
Provided in the class

Loops (contd)
The repeat loop
Syntax:

repeat(

number_of_iterations )
statement;

The number_of_iterations is evaluated only when


the loop is first encountered
integer count;
initial
begin
count = 0;
repeat(128)
begin
$display("Count = %d", count);
count = count + 1;
end
end

Loops (contd)
The forever loop
Syntax:
forever
statement;

Equivalent to while(1)

Timing Control

63

Objectives of This Topic


Internal operations of Event-Driven
simulators
Behavioral Modeling (contd)
Blocking vs. non-blocking assignments
Race condition
Timing control by delays, events, and
level
Other features

Two Types of Simulators


Oblivious Simulators
Evaluate
outputs
repetitively
predefined time intervals

at

Event Driven Simulators


Evaluate outputs only when an event
occurs on the inputs

Internal Operations of EventDriven Simulators


Event
Transaction
The simulation cycle

Timing Controls in
Behavioral Modeling

Introduction
No timing controls No advance in
simulation time
Three methods of timing control
1. delay-based
2. event-based
3. level-sensitive

1. Delay-based Timing Controls


Delay Duration between encountering
and executing a statement
Delay symbol: #
Delay specification syntax:
#5
#(1:2:3)

//Delay specified by number


//(min:typ:max) delay model

Delay-based Timing Controls


(contd)
Types of delay-based timing controls
Regular delay control
Intra-assignment delay control
Zero-delay control

Delay control can be specified by a


number, identifier or
mintypmax_expression.

Regular Delay Control


Symbol: non-zero delay before a procedural
assignment
Delay is specified at Left of procedural assignment
Example: 7-10.
The execution of procedural statement is delayed
by the number specified by the delay control

2016

DSD

72

Regular Delay Control

2016

DSD

73

Regular Delay Control

2016

DSD

74

Intra-assignment Delay
Control
Symbol: non-zero delay to the right of
the assignment operator
Example: 7-11
Operation sequence:
1. Compute the RHS expression at current
time.
2. Defer the assignment of the above
computed value to the LHS by the
specified delay.

Intra-assignment Delay
Control

Intra-assignment Delay
Control

Zero-Delay Control
Symbol: #0
Different initial/always blocks in the same
simulation time
Execution order non-deterministic

#0 ensures execution after all other


statements
Eliminates race conditions (only in simulation)

Multiple zero-delay statements


Non-deterministic execution order

2. Event-based Timing Control


Event
Change in the value of a register or net
Used to trigger execution of a statement
or block (reactive behavior/reactivity)

Types of Event-based timing control


Regular event control
Named event control
Event OR control

Regular Event Control


Symbol:

@(<event>)

Events to specify:
posedge sig

Execute the statement when the sig chnges with


positive transitions (0 to 1, x or z, x to 1, z to 1)

negedge sig

Execute the statement when the sig chnges with


positive transitions (1 to 0, x or z, x to 0, z to 0)

sig

Execute the statement when, Any change in sig


value occurs

Named Event Control


You can declare (name) an event, and then
trigger and recognize it.
Keyword:

event

event calc_finished;

Verilog symbol for triggering:

->

->calc_finished

Verilog symbol for recognizing:


@(calc_finished)

@()

Named Event Control


event received_data; //Declare an event
always @ (posedge clock)
Begin
if (last_packet)
->received_data

//check at each pos edge


//if last_packet is 1 then
//triggers the event named as
//received_data

end
always@(received_data)
begin
/*---Do Something---*/
end

Event OR control
Used when need to trigger a block upon
occurrence of any of a set of events.
The list of the events: sensitivity list
Keyword:
or

2016

DSD

83

Event OR control
Simpler syntax
always @( reset or clock or d)
always @( reset, clock, d)
@* and @(*)

Level-sensitive Timing
Control
Level-sensitive vs. event-based
event-based: wait for triggering of an
event (change in signal value)
level-sensitive: wait for a certain
condition (on values/levels of signals)

Keyword:

wait()

always
wait(count_enable)

#20 count=count+1;

Objectives of This Topic


Some more constructs on Behavioral
Modeling
Parallel blocks
Nested blocks
disable keyword

Verilog Scheduling Semantics

Blocks, Sequential blocks


Used to group multiple statements
Sequential blocks

Keywords: begin end


Statements are processed in order.
A statement is executed only after its
preceding one completes.
Exceptions: non-blocking assignments and
intra-assignment delays

A delay or event is relative to the


simulation time when the previous
statement completed execution

Parallel Blocks
Parallel Blocks
Keywords: fork, join
Statements
in
the
blocks
are
executed
concurrently
Timing controls specify the order of execution of
the statements
All delays are relative to the time the block was
entered
The written order of statements is not important
The join is done when all the parallel statements
are finished

Sequential vs. Parallel Blocks


initial
begin
x=1b0;
#5
y=1b1;
#10 z={x,y};
#20 w={y,x};
end

initial
fork
x=1b0;
#5
y=1b1;
#10 z={x,y};
#20 w={y,x};
join

2016

DSD

90

Parallel Blocks and Race


Parallel execution Race conditions may
arise
initial
fork
x=1b0;
y=1b1;
z={x,y};
w={y,x};
join

z,w can take either 2b01, 2b10


or 2bxx, 2bxx or other
combinations depending on simulator

Special Features of Blocks


Contents
Nested blocks
Named blocks
Disabling named blocks

Nested Blocks
Sequential and parallel blocks can be mixed
initial
begin
x=1b0;
fork
#5 y=1b1;
#10 z={x,y};
join
#20 w={y,x};
end

Named blocks
Syntax:
begin: <the_name>fork: <the_name>

end
join

Advantages:
Can have local variables (local variables are static)
Are part of the design hierarchy.
Their local variables can be accessed using
hierarchical names
Can be disabled

Disabling Named Blocks


Keyword: disable
Action:
Similar to break in C/C++, but can
disable any named block not just the
inner-most block.

Loops

A loop is synthesizable if it is static: The


number of iterations is fixed and independent of
the data
Example:

reg
[2:0]
i;
reg
[3:0]
out;
wire [3:0] a,b;
always @ (a or b)
begin
for (i=0; i<=3; i=i+1)
out[i] = a[i] & b[i];
end
endmodule

Example Unrolled:
out[0]
out[1]
out[2]
out[3]

=
=
=
=

a[0]
a[1]
a[2]
a[3]

&
&
&
&

b[0];
b[1];
b[2];
b[3];

Generate Statements
Generate Loop
Generate loops can be used to create multiple instances of
instances within a for loop.
The for loop in a generate statement is similar to the regular for
loop except for the following conditions:

The loop index variable must be a genvar variable, a special integer


variable used in for loops.
The assignments in the loop control must assign to the same
genvar.
The contents of the loop must be within a named beginend block.
The genvar variable is a special integer variable used in generate

loops, which can be assigned only 0 or positive numbers. A


genvar can only be assigned a value as part of a generate loop
statement. A genvar variable can be defined outside of the
generate block or within a generate block. If declared outside,
the genvar variable can be used by any number of generate
blocks.

Conditional Generates

Conditional generates can be created in two ways:

if else statements
case statements

Both of these statements can be used within the generate block.


Here is an example of using a generate statement to control the type
of adder used:
// if-else
generate
if (adder_width < 8)
ripple_carry # (adder_width) u1 (a, b, sum);
else
carry_look_ahead # (adder_width) u1 (a, b, sum);
endgenerate

Note: The expression inside the if statement must evaluate to a static value.

Conditional Generates
The following example uses the case statement
to determine which adder is used, based on the
parameter WIDTH:
// case
parameter WIDTH=1;
generate
case (WIDTH)
1: adder1 x1 (c0, sum, a, b, ci);
2: adder2 x1 (c0, sum, a, b, ci);
default: adder # WIDTH x3 (c0, sum, a, b, ci);
endcase
endgenerate

Behavioral Modeling
Some Examples

4-to-1 Multiplexer

4-bit Counter

Have you learned this topic?


Sequential and Parallel Blocks
Special Features of Blocks
Nested blocks
Named blocks
Disabling named blocks

Objectives of This Topic


Use Tasks and Functions for better
structured code

Introduction
Procedures/Subroutines/Functions in
SW programming languages
The same functionality, in different
places

Verilog equivalence:
Tasks and Functions
Used in behavioral modeling
Part of design hierarchy Hierarchical
name

Functions
Keyword: function, endfunction
Can be used if the procedure
does not have any timing control constructs
returns exactly one single value
has at least one input argument

Function Declaration Syntax


function <range_or_type> <func_name>;
input <input argument(s)> // at least
<variable_declaration(s)> // optional
begin // if more than one statement needed
<statements>
end // if begin used
endfunction

one input

Function Invocation Syntax


<func_name> ( <argument(s)> );

Example:
function my_not;
input in;
my_not= ~in;
endfunction
reg ni;
initial
ni = my_not(i);

Function Semantics
much like function in Pascal or C
An internal implicit reg is declared
inside the function with the same name
The return value is specified by setting
that implicit reg
<range_or_type> defines width and
type of the implicit reg
<type> can be integer or real
default bit width is 1

Two Function Examples:


Parity Generator, and Controllable
Shifter

2016

DSD

111

Tasks
Keywords: task, endtask
Must be used if the procedure has
any timing control constructs
zero or more than one output arguments
no input arguments

Task Declaration Syntax


task <task_name>;
<I/O declarations> // optional
<variable and event declarations>
begin // if more than one statement needed
<statement(s)>
end
// if begin used!
endtask

Task Invocation Syntax


<task_name>;
<task_name> (<arguments>);

input and inout arguments are passed


into the task
output and inout arguments are
passed back to the invoking statement
when task is completed

I/O declaration in modules


vs. tasks
Both use keywords: input, output,
inout
In modules, represent ports
connect to external signals

In tasks, represent arguments


pass values to and from the task

Task Examples
Use of input and output arguments
Use of module local variables

Automatic Tasks and


Functions
Used for re-entrant code
Task called from multiple locations
Recursive function calls

Keyword
automatic

Example
function automatic integer factorial;
task automatic bitwise_xor;

Automatic Function Example


Factorial

Tasks and Functions


Differences between
Tasks and Functions

Differences between...
Functions

Tasks

Can enable (call) just


another function (not
task)
Execute in 0 simulation
time
No timing control
statements allowed
At least one input

Return only a single value


2016

DSD

Can enable other tasks


and functions
May execute in nonzero simulation time
May contain any timing
control statements
May have arbitrary
input, output, or
inout
Do not return any
value
120

Have you learned this topic?


How to define tasks and functions
Where to use each of them
The same purpose as subroutines in SW
Provide more readability, easier code
management
Are part of design hierarchy
Tasks are more general than functions
Can represent almost any common Verilog
code

Functions can only model purely


combinational calculations

Structured Procedure

122

Thanks

Give Your Feedbacks at:


www.amitdegada.weebly.com/Guest-book.html
2016

DSD

123

Vous aimerez peut-être aussi