You are on page 1of 354

Sandeepani

www.sandeepani-vlsi.com

Verilog HDL
Coding for Simulation &
Synthesis
Sandeepani
www.sandeepani-vlsi.com

What’s Coming
• Objectives
– Introduce Verilog language concepts
– Use of language features to capture hardware design
specification and Verify
– Explore gate level modeling capabilities
– Understand PLI capability

• Format
– Morning – Presentations
– Afternoon – Lab Exercises

• Timing
– Coffee…..10.30 to 10.45 & 3.30 to 3..45
– Lunch……1.00 to 2.00
Sandeepani
www.sandeepani-vlsi.com

Part-I
Designing using Verilog ( RTL Coding )
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Introduction to Verilog-HDL, Data Types, Operators.
• Verilog Language Concept, Hierarchy, Concurrency,
Timing
• Continuos and Procedural Assignments

- Session II
• Lab 1- Use of Simulation and synthesis Tools
• Multiplexer, Comparator ,Decoder
• Using Hierarchy
• Assignments
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Verilog Coding styles – RTL , Behavioural.
• Sequential statements - if else, case, for loop, while loop,
statements
• Blocking and Non-blocking statements,Simulation cycle

- Session II
• Lab 2
• Sequential Logic exercises- Registered logic, timing
logic, Counting logic..
• Assignments
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Synthesis Process
• Structural RTL coding

- Session II
• Lab 3
• Coding for Finite State Machines
• Assignments
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I

• Sample complete design


• RTL coding Guidelines

- Session II
• Lab 4
• Use of External IP in design
• Structural coding
• Assignments
Sandeepani
www.sandeepani-vlsi.com

Part-II
Verification using Verilog ( Behavioral Coding )
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Verification Overview, Writing Simple Test benches
• System Tasks & Compiler directives
• Use of input and output files
• Creating self checking test benches

- Session II
• Lab 1- Use of Simulation and synthesis Tools
• Writing Simple Test benches for Multiplexer,
comparator,Decoder..
• Writing Test bench for Clocked logic
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Tasks & Functions
• PLI Overview
• Creating PLI applications

- Session II
• Lab 2
• Writing test benches using Tasks
• Writing test benches for FSM’s
Sandeepani
www.sandeepani-vlsi.com

SCHEDULE
- Session I
• Sum up
- Session II
Lab 3
• Writing structured test benches using I/O files
• Complete verification of structured model
• Design Debugging
Sandeepani
www.sandeepani-vlsi.com

Verilog Application
Sandeepani
www.sandeepani-vlsi.com

Verilog Application
Objectives
 Identify the advantages of designing with an HDL.
 Applications of Verilog
 Define what is meant by “levels of abstraction” with
respect to:
 Verilog modeling
Sandeepani
www.sandeepani-vlsi.com

What is Verilog
• Verilog is not a software
language
• Verilog is a Hardware
Description Language (HDL)
– Programming language with
special constructs for modeling
hardware Structure
Verilog Supports:-
• Structure a q
– Physical (netlist & hierarchy)
– Software (subprogram) b s
• Hardware behavior
– Serial (sequential)
c r Behavior
– Concurrent (parallel)
Tpd Tsetup
• Timing D Q Thold
• Abstraction levels Tclk-q
Tnet
clk
Timing
Sandeepani
www.sandeepani-vlsi.com

Levels of Abstraction
Behavioral
algorithmic
f

Register
Transfer Level
Verilog Logic synthesis
Gate level
-structural
-netlist

Physical
-silicon
Layout / place
-Switch
& Route
Sandeepani
www.sandeepani-vlsi.com

Abstraction Level Example:Divide by 2


Behavioral
data op
always @ (data) 2
op <= data/2;
4 4
RTL data op
SLI D Q
always @ (posedge clk) 4 4
op <= data >> 1;
clk
Gate Level Netlist
FD1 opreg2 ( .D(data[3]), .CP(clk), .Q(op[2] ) );
FD1 opreg1 (.D(data[2]), .CP(clk), .Q(op[1] ) );
FD1 opreg0 (.D(data[1]), .CP(clk), .Q(op[0] ) );
FD1 opreg3 ( .D(1’b0), .CP(clk), .Q(op[3] ) );
Sandeepani
www.sandeepani-vlsi.com

Benefits of Using an HDL


 Design at a higher level.
 Find problems earlier in the design cycle
 Explore design alternatives
 Description is implementation independent.
 Functional and technology changes are easier to make
 Decisions on implementation can be delayed longer
 Flexibility
 Re-use of design
 Choice of tools,vendors
 Text language based
 Faster design capture
 Easier to manage
Sandeepani
www.sandeepani-vlsi.com

Applications
Verilog language is used by:

 ASIC and FPGA designers writing RTL code for synthesis


 System architects doing high level system simulations
 Verification engineers writing advanced tests for all level of
simulation
 Model developers describing ASIC or FPGA cells, or higher level
components
Sandeepani
www.sandeepani-vlsi.com

Verilog Based Simulation


• High level testbench in
waveforms Verilog
• Interacts with design
• Portable
• Possibility of automatic
Testbench Design checking of function
behavioral RTL
• Testbench written in
behavioral style
• Design written in RTL
Compare style

Results Expected results


Sandeepani
www.sandeepani-vlsi.com
Sandeepani
www.sandeepani-vlsi.com

Verilog Language Introduction


Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


• Objective
– Examine fundamental language objects
– Introduce the main language concepts

• Contents
– Verilog objects
– Verilog connection model
– Hierarchy
– Rules and regulations
Sandeepani
www.sandeepani-vlsi.com

module
• Describes interface and module halfadd (a, b, sum, carry);
behavior
output sum, carry;
• Module’s communicate input a, b;
through ports
– Port names listed in assign sum = a^b
parentheses after the
assign carry = a&b
module name.
• Ports can be defined as
endmodule
input, or inout (bidirectional)
• ^is the exclusive or operator
• & is an logical and operator halfadd
a sum
Important to Remember :
Verilog is case sensitive for +
identifiers keywords must be b
in lowercase
carry
Sandeepani
www.sandeepani-vlsi.com

Representing Hierarchy
Create hierarchy by
 Instantiating module fulladd
 Connecting module ports to a n_sum
local ports or nets sum
U1 U2
 Local nets need to be
b n_carry2
declared
halfadd halfadd
 The or construct is a “built cin
in” gate primitive carry
n_carry1
module fulladd (a, b, cin, sum, carry);
input a, b, cin; Local nets of type
output sum, carry; wire
wire n_sum, n_carry1, n_carry2;
halfadd U1 (.a(a), .b(b), .sum(n_sum), .carry(n_carry1) );
halfadd U2 (.a(n_sum), .b(cin), .sum(sum), .carry(in_carry2) );
or U3 (carry1, n_carry2, n_carry1) ;
endmodule
Sandeepani
www.sandeepani-vlsi.com

Connecting Hierarchy-Named Port


Connection instantiation module
 Explicitly specifies which n_sum
a
module port is mapped to a sum
which local port/wire b n_carry1 b carry
U1
module fulladd (a, b, cin, sum, carry); halfadd
input a, b, cin; …mapped to
output sum, carry ; wire n_carry1
wire n_sum, n_carry1, n_carry2 ; of fulladd module
…..
halfadd U1 (.a(a), .b(b), .sum(n_sum), .carry(n_carry1) );
…..
module halfadd (a, b, sum, carry);
output sum, carry; Tip
input a, b; Output carry of Use named port connection

halfadd module For linking hierarchy
endmodule
Sandeepani
www.sandeepani-vlsi.com

Connecting Hierarchy-Ordered Port


Connection
 Port mapping in order:- instantiation module
•1st instantiation port a n_sum
st
mapped to 1 module port a sum
• 2nd instantiation port mapped b n_carry1 b carry
to 2nd module port
• etc U1 halfadd
module fulladd (a, b, cin, sum, carry) ;
input a, b, cin; input a of fulladd mapped to
output sum, carry; input a of halfadd
wire n_sum, n_carry1, n_carry2;
…..
input b of fulladd mapped to
halfadd U1 (a, b, n_sum, n_carry1) ;
….. input b of halfadd
module halfadd (a, b, sum, carry) ;
output sum, carry ;
input a, b ; Caution
…… Less readable and more error-prone
endmodule than named port connection
Sandeepani
www.sandeepani-vlsi.com

Procedural Blocks (Procedures)


• Section containing always @ (a or b or sel)
procedural statements if (sel = = 1)
• Multiple procedures interact y=a; event list
concurrently else
• always procedure y=b;
– Executes when any
variable in event list
changes value a 1
– Runs throughout y
simulation b 0
• initial procedure
– Executes once at start of sel initial
simulation
begin
– Used for initialisation, a = 1;
testbenches…
b = 0;
Synthesis
end
initial blocks are not synthesisable
Sandeepani
www.sandeepani-vlsi.com

Event List
“or” is a keyword used in event
• always procedure lists
executes when one or
more variables in the always @ (a or b or sel)
begin
event list change if (sel = = 1)
value y=a; event list
else
• An event is a change y=b;
in logic value end
Sandeepani
www.sandeepani-vlsi.com

The Verilog Connectivity Model


• Multiple procedures
interacting concurrently
– Executing statements in
sequence, like Procedure
conventional “software”
– Communicating
concurrently through
variables Procedure
• Procedures contained in
Procedure
a module
– Or separated into several
modules for a hierarchical
design
Procedure
Sandeepani
www.sandeepani-vlsi.com

Compilation Library
Some Verilog tools use
compilation libraries:-
 A collection of compiled
modules or primitives
 Physical exists as a directory
a_clk.v
 Referred to by library name
 Simulator startup file
WORK specifies mapping
 Library name ->directory
name
PRIMS MY_WORK PROJ Compile into “WORK”
 WORK mapped to specific
library name
Sandeepani
www.sandeepani-vlsi.com

Design Compilation
• Design compiled from a list
of Verilog files
tb_one • Normally compile the
testbench testbench first
– Usually contains compiler
directives
design – Provides additional
structural information for the
compiler/simulator
• Order of other files generally
cpu pnet_read pnet_write not important
behavioral RTL/structural behavioral • Hierarchical connections are
automatically made
• Verilog allows different levels
read_frame write_frame of abstraction anywhere in
netlist primitives the hierarchy
Sandeepani
Comments and Spacing www.sandeepani-vlsi.com

// This is a ‘line’ comment. Each line must begin with //


// Comments end with a new line
module halfadd (a, b, sum, carry) ;
output sum, carry ;
input a, b ; // End of line comment

/* This is a ‘block’ comment. Text in a block comment
can span many lines.*/
// Verilog is a free-format language
// Additional spaces can be used to enhance readability
assign sum =a ^ b;
assign carry = a & b;
// use indentation to aid readability and debugging
always @ (a or b or sel)
if (sel = =1)
y = a;
else
y = b;
Sandeepani
www.sandeepani-vlsi.com

Identifier Naming Rules


• Names may consist of any
alphnumeric character,
including dollar sign ($) and unit_32
underscore(_)
• Names must start with a
structural
letter or an underscore bus_16_bite
• Verilog identifiers are case a$b
sensitive
– Keywords must be
lowercase unit@32
• These names do not refer to unit - 32
the same object
16_bit_bus
– ABC,Abc,abc
• Names can be of any length
– Tool or methodology may
restrict name lengths.
Sandeepani
www.sandeepani-vlsi.com
Sandeepani
www.sandeepani-vlsi.com

Verilog Logic System and


Data
Types
Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


• Aims
– To introduce the Verilog logic value system and to
understand the different data types and the rules
covering their use.
• Topics
– Logic value system
– Data type classes
– Vectors and literal values
– Net data types and their use
– Choosing the correct data type
– Parameters
– Memory arrays
Sandeepani
www.sandeepani-vlsi.com

4-Value Logic System in Verilog


buf
Zero, Low,False, Logic Low,
0 Ground, VSS, Negative
Assertion
buf
1 One,High,True,Logic High,
Power, VDD, VCC, Positive
buf Assertion

X X,Unknown (bus contention),


Uninitialized

bufifI
Z Hiz, High Impedance, Tri-State,
Undriven, Unconnected,
Disabled Driver (Unknown)

Important
The “unknown” logic value x is not the same as “don’t care.”
Sandeepani
www.sandeepani-vlsi.com

Data Types
• Verilog objects communicate using variables
• All variables have a type
• There are three different classes of data type
– Nets
• Represent physical connection between structures and
objects e.g. wire
– Registers
• Represent abstract storage elements e.g.reg
– Parameters
• Run-time constants
Sandeepani
www.sandeepani-vlsi.com

Net Types
• A Net type behaves like a wire driven by a logic gate
• Various net types are available
– Wire is the most commonly used
– Nets not explicitly declared default to type wire
• Net values changed with assign in continuous assignments and
by modules or primitives in the design

wire sel; // Scalar wire


wire [31:0] w1, w2 ; // Two 32-bit wires with msb = bit 31
wand c; // Scalar wired-AND net
tri [15:0] busa ; // A 16-bit tri-state bus, msb = bit 15

Net types:- module halfadd (a, b, sum, carry) ;


wire, tri input a, b; // default to wire
output sum, carry ; // default to wire
supply1, supply0
// change with assign
wor, trior assign sum = a ^ b;
wand, triand assign carry= a & b;
trireg, tri0, tri1 endmodule
Sandeepani
www.sandeepani-vlsi.com

Wire and assign


a nsela  wire declaration and
assignment can be
sel out merged.
nsel  Remember – ports default
b to wire types
 Note:~ is an inversion
selb
operator

Nets
module mux (a, sel, b, out); module mux (a, sel, b, out );
input sel, b, a; input sel, b, a ;
output out ; output out ;
wire nsela, selb, nsel ; wire nsel = ~sel;
assign nsel = ~sel; wire selb = sel & b;
assign selb = sel & b ; wire nsela = nsel & a ;
assign nsela = nsel & a;
assign out = nsela | selb ; assign out = nsela | selb;
endmodule endmodule
Sandeepani
www.sandeepani-vlsi.com

Logic Conflict Resolution with Nets


 If the same net is driven a
from multiple sources a y assign y = a ;
conflict occurs ?
assign y = b ;
 Net types have a resolution
function to determine final
value of target b

y declared as y declared as y declared as


wire y ; wand y ; wor y ;
tri y ; triand y ; trior y ;
b b 0 1 x z b
a 0 1 x z
a 0 1 x z a
0 0 x x 0 0 0 0 0 0 0 0 1 x 0
1 x 1 x 1 1 0 1 x 1 1 1 1 1 1
x x x x x x 0 xx x x x 1 x x
z 0 1 x z z 0 1 x z z 01 x x
Synthesis wire and tri are synthesisable, some synthesis tools support wor and wand
Sandeepani
www.sandeepani-vlsi.com

Register Types module mux (a, b, c, sel, op) ;


input a, b, c, ;
 Register types stores value until a
input sel ;
new value is assigned
output op ;
 Various register types are available
reg op ;
 reg is the most commonly used
 Register values changes with
always @ (a or b or sel)
procedural assignment
begin
if (sel = = 1)
op = a;
Synthesis
else
reg and integer are synthesisable, but do not
op = b;
have to synthesis to a flip-flop in hardware
end
endmodule
Register types:-
reg reg [3:0] vect ; // 4-bit unsigned vector
integer reg [2:0] p, q ; // two 3-bit unsigned vector
real integer i ; // 32-bit signed integer
time reg s ; // unsized reg defaults to 1-bit
time delay ; // time value
Sandeepani
www.sandeepani-vlsi.com

Register Assignment
module mux ( a, b, c, sel, mux ) ;
input a, b, c ;
 Register types can only be input sel ;
updated from within a procedure output mux ;
 Procedures can only update wire aandb, nmux ;
register types reg mux, nota ;
 Registers and nets can be mixed
always @ (a or b or sel)
on the right-hand-side of an
if (sel = = 1)
assignment begin
mux = a ;
nmux = b ;
Error
end
Net type assigned
else
in procedure begin
mux = a ;
Error nmux = b ;
Register type end
assigned outside assign nota = ~a;
procedure assign aandb = a & b ;

Sandeepani
www.sandeepani-vlsi.com

Choosing the Correct Data Type


Input Port Output Port
net/register net net/register net
atop a ytop
b net y
btop Inout Port

net
module top;
wire ytop;
reg atop, btop; module dut (y, a, b) ;
initial output y;
begin input a, b;
atop = 1’b0;
btop = 1’b0; assign y = a&b;
end endmodule
dut U1 (.a(atop), .y(ytop), . b(btop));
endmodule
Sandeepani
www.sandeepani-vlsi.com

Parameters
• Parameters are used to declare // parameter list
run-time constants. parameter pl = 8,
• Can be used anywhere that you REAL_p = 2.039,
can use a literal. X_WORD = 16’bx ;
•Make code more
readable module mux (a, b, sel, out) ;
• Parameters are local to the
parameter WIDTH = 2;
module in which they are
defined. input [WIDTH –1:0] a;
• Can be used to size local input [WIDTH – 1:0] b;
variable declarations input sel ;
• Including module ports output [WIDTH – 1:0] out ;
• Must be declared before used reg [WIDTH –1:0] out ;
always @ (a or b or sel)
if (sel)
out = a;
else
out = b;
endmodule
Sandeepani
Overriding the Values of www.sandeepani-vlsi.com

Parameters
• Constant values can be changed for each
instantiation of module
module muxs (abus, bbus, anib, bnib, opbus, opnib, opnib1, sel );

parameter NIB = 4:
input [NIB-1:0] anib, bnib; module mux (a, b, sel, out);
input [7:0] abus, bbus;
input sel; parameter WIDTH = 2;
….
output [NIB-1:0] opnib, opnib1;
output [7:0] opbus ;
// module instantiations for different sized muxes
mux # (8) mux8 (.a(abus), .b(bbus), . Sel(sel), .out”(opbus) );
mux # (NIB) mux4 (.a(anib), .b(bnib), .sel(sel), .out(opnib) );

mux mux4a (.a(anib), .b(bnib), .sel(sel), .out(opnib1) );


defparam mux4a.width=4;
endmodule
Example follows…..
Sandeepani
www.sandeepani-vlsi.com

Generic Decoder
module gen_dec (en,a,y); module gen_dec_call (ena,enab,adda,addb,decadda,decaddb);

parameter sizein=3, input ena;


sizeout=8;
input enb;
input en;
input [sizein-1:0]a; input [1:0]adda;
output [sizeout-1:0]y; input [1:0]addb;
reg [sizeout-1:0]y;
integer i; output [3:0]decadda;
always @(en or a) output [3:0]decaddb;
begin
if(!en) gen_dec#(2,4) dec2_4(ena,adda,decadda);
y=0; gen_dec #(3,8) dec3_8(enb,addb,decaddb);
else
if(a > sizeout-1 ) endmodule
for (i=0;i<= sizeout-1;i=i+1)
y[i]=1'bx;
else
for (i=0;i<= sizeout-1;i=i+1)
if(a==i)
y[i]=1;
else
y[i]=0;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Two Dimensional Arrays


• Verilog supports two-dimensional array of registers
reg [15:0 ] mem [0 : 1023] ; // 1K x 16-bit 2-d array
integer int_arr [99 :0] ; // Array of integers 100 deep

• A array element is addressed by an index to the 2-d


array
-You can only reference one element of memory at a time
– Multiple words accesses require multiple statements
– Single bit accesses require an intermediate variable
reg [7:0] mem_array [0:255]; // memory array
reg [7:0] mem_word;
reg membit;

mem_word = mem_array [5]; // access address 5


mem_word = mem_array [10]; // access address 10
membit = mem_word [7] ; // access bit 7 of address 10
Synthesis: Two-dimensional arrays generally not synthesisable
Sandeepani
www.sandeepani-vlsi.com

Summary
• A net type behaves like a real wire driven by a logic gate
– Nets not explicitly declared default to type wire
– Net values changed with assign statement or when driven by
a module/primitive
• Register types stores value until a new value is assigned
– Register types do not have to synthesise to a register
hardware element
– Procedural assignment can only be updated with a
procedural assignment
– When assigning integer to reg, sign information is
disregarded
• Registers and nets can be mixed on the right-hand-side of an
assignment
• Module ports are defined as wire by default
– Inputs must be net types, but can be driven by nets or registers
– Inouts must be net types and can only be driven by a net
– Outputs can be net or a register types, but can only drive a net
Sandeepani
www.sandeepani-vlsi.com

Verilog Operators
Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


 Aims
-Introduce the operators available in the Verilog language
 Topics
Operator Type Symbol

arithmetic +-*/ %
bit-wise ~& ^~^
logical !&&
reduction & ^ ~ & ~ ~ ^
shift << >>
relational < > <= >=
equality == != === !==
conditional ?:
concatenation {}
replication {{ }}
Sandeepani
www.sandeepani-vlsi.com

Arithmetic Operators
module arithops ( ) ;
+ add integer ans, int ;
- substract parameter FIVE = 5 ;
* multiply reg [3:0] rega, regb, regc, num ;
/ divide initial
% modulus begin
rega = 3 ; // 0011
regb = 4’b1010 ;
• Binary arithmetic is regc = 2; // 00010
unsigned int = -3 ;
• Integer arithmetic is
ans = FIVE * int; // ans = -15
signed ans = (int + 5) /2; // ans = 1
ans = FIVE / int ; // ans = -1
Synthesis num = rega + regb; // num= 1101
num = regc + regb; // num= 1100
% not synthesisable num = int; // num = 1101
/ only synthesisable if dividend num = regc % rega; // num = 0010
is a power of 2 end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Bit-Wise Operators
module bitwise ( ) ;
~ not reg [3:0] rega, regb, regc ;
& and reg [3:0] num ;
or
initial
^ xor begin
~ ^ xnor rega = 4’ b1001 ;
^ ~ xnor regb = 4’ b1010 ;
regc = 4’ b11x0 ;

• Bit-wise operators num = ~rega; // num = 0110


operate on vectors. num = rega & 0 ; // num = 0000
num = rega &regb; // num = 1000
• Operations are num = rega | regb; // num = 1011
performed bit by bit num = regb & regc; // num = 10x0
on individual bits. num = regb | regc; // num = 1110
end
endmodule

Note: Unknown bits in an operand do not necessarily lead to unknown bits in the result
Sandeepani
www.sandeepani-vlsi.com

Logical Operators module logical ( );


parameter FIVE = 5;
! not reg ans ;
reg [3:0] rega, regb, regc ;
&& and
or initial
begin
rega = 4’b0011; // reduces to 1
• Logical operators are an
regb = 4’b10xz; // reduces to 1
operand reduction, followed regc = 4’b0z0x; // reduces to x
by single bit operation
ans = ! rega; // ans = 0
- Vectors containing any 1
ans = rega && 0; // ans = 0
reduce to 1’b1 ans = rega | | 0; // ans = 1
- Vectors containing all 0 ans = rega && FIVE; // ans = 1
reduce to 1’b0 ans = regb && rega ; // ans = 1
ans = regc | | 0; // ans = x
- Vectors containing any x or z end
with only 0 reduce to 1’bx endmodule
Sandeepani
Unary Reduction Operators www.sandeepani-vlsi.com

module reduction ( ) ;
& and reg val ;
or reg [3:0] rega, regb;
^ xor initial
~& nand begin
~ nor rega = 4’b0100;
regb = 4’b1111;
~ ^ xnor
^ ~ xnor val = & rega ; // val = 0
val = | rega ; // val = 1
val = & regb ; // val = 1
val = | regb ; // val = 1
• Reduction operators val = ^ rega ; // val = 1
perform a bit-wise val = ^ regb ; // val = 0
val = ~ | rega ; // val = 0
operation on all the bits val = ~ &rega; // val = 1
of a single operand. val = ^rega && regb; // val = 1
• The result is always end
endmodule
1’b1, 1’b0 or 1bx.
Sandeepani
www.sandeepani-vlsi.com

Shift Operators
module shift ( ) ;
> > shift right reg [9:0] num ;
< < shift left reg [7:0] rega ;

initial
• Shift operators perform begin
rega = 8’b00001100;
left or right bit shifts on
the operand. num =rega >> 1; // num = 0000000110
• Shift is logical num = rega >> 3; // num = 0000000001
•0 is used for extra bits num = rega << 5; // num = 0110000000
• Shifts can be used to
end
implement division or
multiplication by powers endmodule zeros added first,
of two then shift by 5 to the
left
Sandeepani
www.sandeepani-vlsi.com

Relational Operators
> greater than module relationals;
reg [3:0] rega, regb, regc;
< less than reg val ;
>= greater than or equal
<= less than or equal initial
begin
• The result is:- rega = 4’b0011;
regb = 4’b1010;
• 1’b1 if the condition is true regc = 4’b0x10;
• 1’b0 if the condition is false
• 1’bx if the condition cannot val = regc > rega ; // val = x
be resolved val = regb < rega ; // val = 0
val = regb >= rega ; // val = 1
val = regb > regc ; // val = x
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Conditional Operator
module tribuf (in, enable, out);
? : conditional input in, enable;
output out;
reg out;
in out
always @ (enable or in)
out = enable ? In : 1’bz;
endmodule
enable

wire out3;
reg out1, out2;
always @ (a or b or sel)
a out1 = sel ? a : b ;
out
b always @ (a or b or sel)
if (sel)
out2 = a;
sel else
Note: sometimes the if else construct out2 = b;
may be more readable assign out3 = sel ? a : b;

Sandeepani
www.sandeepani-vlsi.com

Concatenation
module concatenation;
{ } concatenation reg [7:0] rega, regb, regc, regd, new;
• Allows you to select reg [3:0] nib1, nib2;
bits from different initial
vectors and join them begin
rega = 8’ b00000011;
into a new vector. regb = 8’ b00000100;
• Used for bit regc = 8’ b00011000;
regd = 8’ b11100000;
reorganization and new = { regd [6:5], regc [4:3], regb[3:0];
vector construction // new = 8’ b11_11_0100
new = {2’ b11, regb[7:5], rega[4:3], 1’ b1};
•e.g.rotates // new = 8’ b11_000_00_1
• Can used on either new = {regd [4:0], regd[7:5]};
// rotate regd right 3 places
side of assignment // new = 8’b00000_111

{nib1, nib2} = rega;


Important // nib1 = 4’ 0000, nib2 = 4’ 0011
Literals used in concatenation end
must be sized endmodule
Sandeepani
Replication www.sandeepani-vlsi.com

module replicate ( ) ;
{ { } } replication reg rega;
Replication allows you to reg [1:0] regb;
reproduce a sized variable a reg [3:0] regc;
set number of times reg [7:0] bus;
•Can be nested and used initial single bit rega
begin replicated 8 times
with concatenation
rega = 1’ b1;
• Syntax is:-
regb = 2’b11;
{ <repetitions> {<variable>} } regc = 4’ b1001;
bus = {8{rega}};
Important // bus = 11111111
Literals used in replication must be sized bus = { {4{rega}}, {2{regc[1:0] }} };
// bus = 1111_01_01
4x rega concatenated bus = { regc, {2{regb}} };
with 2x regc [1:0] // bus = 1001_11_11
bus = {2 {regc[2:1], {2{1’b1}}} };
regc concatenated
// bus = 00_1_1_00_1_1
with 2x regb
end
regc concatenated with 2x endmodule
1’b1 and replicated 2 times
Sandeepani
www.sandeepani-vlsi.com

Operator Precedence
• Do not rely on Operator Precedence – use parentheses

Type of Operators Symbols Highest


Concatenation / Replication {} {{ }}
Inversion (Logical / Bitwise) ! ~
Arithmetic * / %
+ -
Logical Shift << >>
Relational < <= > >= Precedence
Equality == != === !==
Bit-wise / Reduction & ~&
^ ^~
~
Logical &&

Conditional ?: Lowest
Sandeepani
www.sandeepani-vlsi.com

Procedural Statements
Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


• Aim
– To introduce some of the most commonly
used procedural statements
• Topics
– Procedures
– Procedural statements
• if then else
• case
• loops
Sandeepani
initial versus always www.sandeepani-vlsi.com

Procedures …
reg a, b, zor, zand;
• There are 2 types of procedural block
• always procedure executes initial
repeatedly throughout the simulation begin
a = 1’b1;
• it is triggered by a change of value b = 1’b0;
for any variable in the event list end
• initial procedure executes once at
always @ (a or b)
start of simulation begin
if (a | b) event list
• begin …end must be used for zor = 1’b1;
else
multiple statements within a block zor = 1’b0;
if (a & b)
Synthesis zand = 1’b1;
else
Initial procedures cannot be synthesized zand = 1’b0;
end

Sandeepani
www.sandeepani-vlsi.com

Procedural Assignments
module fulladder (out, a, b, cin);
• Assignments made inside input a, b, cin;
procedural blocks are called output [1:0] out;
procedural assignments
reg sum;
• All variables on the reg [1:0] out;
left-hand side must be
always @ (a or b or cin)
register data-types, e.g. reg begin
• Here carry is not declared, sum = a ^ b ^ cin;
and defaults to a 1-bit wire. carry = ((a & b) | ( cin & (a ^ b)));
out = {carry, sum};

Error end
carry is a net type-should be endmodule
declared reg carry;
Sandeepani
www.sandeepani-vlsi.com

Event Control
• always procedure executes when always @ (a or b or sel)
one or more variables in the begin
event list change value if (sel = = 1)
y = a; event list
Synthesis else
y = b;
Include all signals read by the block end
in the event list for the generation
of combinational logic
always @ (posedge clk)
• Can also use negedge or posedge // procedural statements
•Execute procedure on a specific edge always @ (negedge clk)
of a variable // procedural statements
• Used for modeling synchronous logic
Synthesis: always @ (negedge clk or rst)
cannot mix edge and level triggers in // not synthesisable

event list
Sandeepani
www.sandeepani-vlsi.com

Procedural Blocks within Verilog


module design;
wire nsela;

wire nsel = !sel;


wire selb = sel & b; Procedure

always @ (nsel or selb)


out = nsel | selb; Procedure

assign nsela = nsel & a;


always @ (a or b or sel)
begin
// procedural statements
end
Procedure
// continuous statements
Procedure

endmodule
Sandeepani
www.sandeepani-vlsi.com

if Statement Example
• if is a conditional module if_example (a, b, c, d, y);
input [3:0] a, b, c, d;
statement output [3:0] y;
• Each if condition is reg [3:0] y;
tested in sequence
always @ (a or b or c or d)
-Condition is boolean if (d = = 4’ b0000)
expression y = a;
•The first valid test else if (d <= 4’b0101)
y = b;
executes that branch else
•Conditions can overlap y = c;
endmodule
d 0101 d 0000
<=
Synthesis =
if synthesis to mux structures c 0 0
b 1 1 y
a mux
mux
Sandeepani
www.sandeepani-vlsi.com

if Statement Syntax
if (CONDITION) begin
/ / procedural statements • Signal if statement execute
end procedural statements only if
if (CONDITION) begin
the condition is true..
/ / procedural statements • .. add an unconditional else
end to execute procedural statements
else begin
when the if condition is false..
/ / procedural statements
end • …add else if to test further
conditions if the first is false
if (CONDITION) begin -Final else is optional and
/ / procedural statements can be used to indicate
end
else if (CONDITION) begin default operation
/ / procedural statements • Use begin and end to bound
end multiple procedural statements
else begin
/ / procedural statements
end
Sandeepani
www.sandeepani-vlsi.com

case Statement Example


• case is a multiway module case_example (a, b, c, d, y);
conditional statement input [3:0] a, b, c, d;
• case expression is output[3:0] y;
evaluated and compared reg [3:0] y;
against each item in turn
always @ (a or b or c or d)
-Branch items can overlap case (d)
-The first item match 0 : y = a;
executes that branch 1,2,3,4,5 : y = b;
• The optional default captures 6 : y = c;
7 : y = c:
unspecified values
default : y = 4’ b0000;
•In this example, values endcase
containing x or z endmodule
Sandeepani
www.sandeepani-vlsi.com

for Loop module parity (a, odd);


• Iterates around loop for a input [3:0] a;
output odd;
specified number of times
reg odd, tmp;
• Loop variable must be declared
• When loop executed: integer i;
-Loop variable initialized
-Loop statement(s) executed always @ (a)
begin
-Loop operation performed
tmp = 0;
-When condition false, loop exits for (i = 0; i <= 3; i = i + 1)
// for loop expansion tmp = tmp ^ a[i];
tmp = 0 ^ a[0]; // =a[0] odd = tmp;
tmp = tmp ^ a[1]; end
tmp = tmp ^ a[2]; endmodule
tmp = tmp ^ a[3]; a[0]
a[1] tmp
a[2]
Synthesis a[3]
for loop with fixed limits is synthesisable
Sandeepani
www.sandeepani-vlsi.com

repeat and while Loops


module multiplier (result, op_a, op_b); • repeat loops iterate
input [3:0] op_a, op_b;
by the number specified
output [7:0] results;
reg [7:0] results; -Number can be literal,
reg [7:0] shift_opa; variable or expression
reg [3:0] shift_opb;
• while loop iterates while
always @ (op_a or op_b) the expression is true, or
begin non-zero
result = 0; …
shift_opa = op_a; // zero extend left while (count < 10)
shift_opb = op_b; begin
repeat (4) // statements
begin count = count + 1;
if (shift_opb[0] ) end
result = result + shift_opa; …
shift_opa = shift_opa << 1; // shift left
shift_opb = shift_opb >> 1; // shift right
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Loop Statement Syntax


• for loop requires a loop // loop variable must be declared
variable declaration for (initial, condition, inc_dec)
• while loop continues begin
// statements
while the condition is true end
• repeat iterates the number
of times defined by the while (condition)
begin
expression // statements
• forever loops forever end
repeat (expression)
Synthesis begin
-for loop synthesizable for fixed range. / / statements
- repeat synthesizable for fixed repetitions end
- while generally not synthesizable forever
- forever generally not synthesisable begin
Unsynthesizable loops used in testbenches // statements
and simulation models end
Sandeepani
www.sandeepani-vlsi.com

Continuous and procedural statements

Objective: To explain difference between continuous


and procedural statements
Sandeepani
www.sandeepani-vlsi.com

Continuous Assignments
They are:
continuously driven
order independent
They:
operate on net data type only & reside outside
procedures

Example: wire a; x
wire out; a
y +
……….. out
assign a=x+y; +
z
assign out=a+z;
Sandeepani
Multiple Continuous
www.sandeepani-vlsi.com

Assignments

Example:
wire z;
…. a
….. b + z
assign z=a+b; c ?
assign z=c+d; +
d

What would be value on signal z ?
Sandeepani
Multiple Continuous
www.sandeepani-vlsi.com

Assignments
• Multiple assignments to single variable are “wired together”
• If z is wire type ,then following table resolves value

wire/tri | 0 1 x z
-----------------------
0 | 0 x x 0
1 | x 1 x 1
x | x x x x
z | 0 1 x z
• As per need one can use wand or wor types for resolution|
Sandeepani
www.sandeepani-vlsi.com

Procedural Assignments

•Procedure statements execute in sequence or triggered by event


occurring on variable in event list

• Variables are updated immediately

•Procedures execute concurrently


Sandeepani
www.sandeepani-vlsi.com

Procedural Assignments
Example:
module andor(a,b,z_or,z_and);
input a,b;
output z_or,z_and;
reg z_or,z_and;
always @(a or b)
begin
if(a | b)
z_or=1;
else procedural assignments
z_and=0;
if(a & b)
z_and=1;
else
z_and=0;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Multiple Assignments in Procedure

What happens when same variable is assigned in procedure?


Ex: …….
reg z;
…..
always @(a or b or c or d)
begin c
z=a+b; z
z=c+d; d
end

Last statement overrides previous assignment.


Sandeepani
www.sandeepani-vlsi.com

Example..

Code the following block:

a z
b

sel
Sandeepani
www.sandeepani-vlsi.com

Example..

1) always@ (a or b or sel) 2) always@ (a or b or sel)


begin begin
z=b;//default assig.
if(sel) if(sel)
z=a; z=a;
else end
z=b;
end

• Last statement takes effect


Sandeepani
www.sandeepani-vlsi.com

Conditional Assignments
•This can be used in either procedural or continuous assignments
•Procedure containing single if can be replaced by continuous
assignments
Example:
always @(a or b or c or sel)
if (sel==0)
z=a;
else if(sel<= 4’b1010)
z=b;
else
z=c;
endmodule
alternate to above procedure is to use conditional operator
Sandeepani
www.sandeepani-vlsi.com

Conditional Assignment..

always @(a or b or c or sel)


z=(sel==0) ? a:((sel<=4’b1010) ?b:c);
…………

Using continuous assignment:


…..
assign z=(sel==0) ? a:((sel<=4’b1010) ?b:c);
Sandeepani
www.sandeepani-vlsi.com

Avoid feedback loops

What would happen if you use following code ?

assign z=z+x;
Or
always @(z or x)
z=z+x;
Sandeepani
www.sandeepani-vlsi.com

Avoid feedback loops

x
z

•Creates feedback loop with zero-delay.


•Program shall go in infinite loop in simulation and
simulation will lock.
Sandeepani
www.sandeepani-vlsi.com

Review
1.What happens if multiple procedural assignment are
made to the same variable?
2. Is a conditional assignment statement continuous,
procedural or both ?
3. Why should you not create combinational feedback loops?
4. Code the following hardware using
i) a continuous assignment and
ii) using a procedure
a[3:0]

+ 1 d[4:0]

b[3:0] 0
c[4:0]

add
Sandeepani
www.sandeepani-vlsi.com
Sandeepani
www.sandeepani-vlsi.com

Procedural Statements and the


Simulation Cycle

Objective: To explain capabilities of procedures


and blocking non-blocking assignments

Simulation cycle
Sandeepani
www.sandeepani-vlsi.com

Contents

Blocking Procedural Assignment


Non-blocking procedural assignment
Simulation cycle
Timing control
Review
Sandeepani
www.sandeepani-vlsi.com

Procedure and Event Control


Example: 1. …… 2. ……
always @(a or b or c) always @(posedge clk)
begin:adding if(clr)
y=a+b; q <= 0;
z=a+c; else
end q <= d;

•Procedures executes whenever any event occurs on variable


•Procedures can be named
Sandeepani
www.sandeepani-vlsi.com

Blocking Procedural Assignment

Blocking assignment:=

Variable assignment is immediate


-before the next statement is executed

Can create problems with some code structures

Example..
Sandeepani
Example
www.sandeepani-vlsi.com

Will this segment of code Swap the


upper and lower byte contents?

……..
initial
begin
byte=8’b00001111;
#20;
byte[3:0]=byte[7:4];
byte[7:4]=byte[3:0];
#20;
……
Sandeepani
www.sandeepani-vlsi.com

Contents

Blocking Procedural Assignment


Non-blocking procedural assignment
Simulation cycle
Timing control
Review
Sandeepani
www.sandeepani-vlsi.com

Non-Blocking Assignment

Non-blocking assignment:<=

Variable update is scheduled


-value is calculated and stored
-Variable is updated at the end of time slice
Sandeepani
www.sandeepani-vlsi.com

Example
Will this segment of code Swap the
upper and lower byte contents?
……..
initial
begin
byte<=8’b00001111;
#20;
byte[3:0]<=byte[7:4];//byte[3:0] scheduled to receive 4’b0000
byte[7:4]<=byte[3:0];// byte[7:4] scheduled to receive 4’b1111
#20; // procedure suspends, scheduled assignments updated
and nibbles successfully swapped
……
Yes !!!
Sandeepani
www.sandeepani-vlsi.com

Contents

Blocking Procedural Assignment


Non-blocking procedural assignment
Simulation cycle
Timing control
Review
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle(1)
module sim_ex(a,m,y,w);
Input a;
___ ___ Output m,y,w;
___ ___ Reg m,y,w;

Always@ (a or m)
Variable procedure begin:p1
Event list schedule m<=a;
a<=1 y<=m;
End variable at
start
• Assume a,w,m,y all zero
Always@ ( m) a:m:y:w=0
• a changes from zero to one
begin:p2
w<=m;
End
endmodule
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle(2)
module sim_ex(a,m,y,w);
Input a;
Output m,y,w;
___ ____ Reg m,y,w;

___ always@ (a or m)
____ begin:p1
m<=a;
y<=m;
Variable procedure End variable at start
a:1,m:y:w:0
Event list schedule Always@ ( m)
m<=1 p1 begin:p2
a updated from 1’b0 to 1’b1 w<=m;
End
Procedure p1 executes endmodule
Update to m scheduled
No change in the value of y
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle(3)
module sim_ex(a,m,y,w);
Input a;
Output m,y,w;
Reg m,y,w;

____ always@ (a or m)
_____ begin:p1
m<=a;
____ y<=m;
End variable at start
_____ a:1,m:1y:w:0
Variable procedure always@ ( m)
begin:p2
Event list schedule w<=m;
m<=1 p1 End
endmodule
m changes value to 1’b1 p2
Procedure p1 placed on scheduler list
Procedure p2 placed on scheduler list
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle(4)
module sim_ex(a,m,y,w);
input a;
____ ____ output m,y,w;
____ ____ Reg m,y,w;

always@ (a or m)
begin:p1
m<=a;
y<=m;
Variable procedure end
Event list schedule
y<=1 always@ ( m) variable values
W<=1 after one delta
Procedure p1 and p2 execute(random) a:1,m:1y:w:0
Update to y and w scheduled begin:p2
No change in value for m w<=m;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle(5)
module sim_ex(a,m,y,w);
Input a;
Output m,y,w;

____ ____ Reg m,y,w;

always@ (a or m)
____ begin:p1
m<=a;
____ End
y<=m;

always@ ( m) variable
values after
Variable procedure two deltas

Event list schedule a:1,m:1y:1w:1

begin:p2

y and w are updated to 1’b1; End


w<=m;

no more procedures to be endmodule

executed
Sandeepani
www.sandeepani-vlsi.com

Simulation cycle:summary
Variable procedure variable
Event list schedule values
a<=1 p1 a:1,m:0 module sim_ex(a,m,y,w);
y:0,w:0 Input a;
Output m,y,w;
Reg m,y,w;
m<=1 p1 a:1,m:1
p2 y:0,w:0 always@ (a or m)
begin:p1
m<=a;
Y<=1 a:1,m:1 y<=m;
W<=1 End
y:1,w:1 always@ ( m)
begin:p2
w<=m;
End
endmodule
Sandeepani
Delta cycle and simulation
www.sandeepani-vlsi.com

Time
Multiple delta cycles at each point of simulation time

One can specify timing inside procedural blocks


Following are three types of timing controls
Edge-sensitive timing control:@
regular delay: #
level sensitive :wait

Simulation time
Sandeepani
www.sandeepani-vlsi.com
Sandeepani
www.sandeepani-vlsi.com

More on blocking and non-blocking


assignments

Objectives: Guidelines on usage of blocking and


non-blocking assignments
Sandeepani
www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review


Usage in clocked procedures
Usage in combinational procedures
Mix usage
Sandeepani
www.sandeepani-vlsi.com

Blocking assignment review


Blocking assignment:=

Variable update is immediate


-before other statements are executed

always @(posedge clk)


if(sel)
z=a;
else
z=b;
Sandeepani
Non-blocking assignment
www.sandeepani-vlsi.com

review
Non-blocking assignment:<=
Variable update is scheduled
-after the procedure suspends

…..
reg q;
always @(posedge clk)
q<=d;
..
Sandeepani
www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review


Usage in clocked procedures
Usage in combinational procedures
Mix usage
Sandeepani
www.sandeepani-vlsi.com

Blocking assignment in clocked


procedures

What is value of cvar in following segment of code?

initial
begin
avar=1’b1;
bvar=1’b1;
end
always @(posedge clk)
bvar=avar+1’b1;

always @(posedge clk)


cvar=bvar;
Sandeepani
www.sandeepani-vlsi.com

Blocking assignment in clocked


procedures

Blocking assignment can lead to “race conditions”


Specifically when:-
-variable written in one procedure and read in another
-both procedures have same event list

In example shown above:


-both procedures execute on positive edge of clock
-assignments to bvar and cvar are immediate
-final value of cvar depends on which procedure is
executed first
Sandeepani
www.sandeepani-vlsi.com

Non-Blocking assignment in clocked


procedures
• Non=blocking
assignment avoids initial
race conditions begin
avar=1’b1;
• Example:- bvar=1’b1;
both procedures execute on end
positive on positive edge of always @(posedge clk)
clock bvar<=avar+1’b1;
assignments to bvar and cvar always @(posedge clk)
are scheduled cvar<=bvar;
Use non-blocking
assignment for
synchronous logic
Sandeepani
www.sandeepani-vlsi.com

Position dependent code

always @(posedge clk) always @(posedge clk)


begin
begin
b=a;
d=c;
c=b;
d=c; c=b;
end b=a;
Using blocking signal assignment
in clocked procedures can also
end
result in position dependent
code
Sandeepani
www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review


Usage in clocked procedures
Usage in combinational procedures
Mix usage
Sandeepani
www.sandeepani-vlsi.com

Combinational logic

always @ (a or b)
begin
m=a;
n=b;
p=m+n;
end

Use blocking assignment for combinational


procedures
Sandeepani
www.sandeepani-vlsi.com

Combinational logic
always @(a or b or m or n) • Non-blocking assignment can
begin:p1 be inefficient for combinational
m<=a; logic
n<=b; • Specifically when logic
p<=m+n; contains serial serial behavior
end or intermediate variables
Variable event procedure -intermediate variables must
event list scheduler be added to event list
a<=1 p1
-procedure will take several
b<=2
delta cycles to reach “steady
m<=1 p1
state”
n<=2
p<=3
Sandeepani
www.sandeepani-vlsi.com

Multiple assignments
always @(a or b or c) always @(a or b or c or m or n)
begin begin
m<=a;
m=a; n<=b;
n=b; p<=m+n;
p=m+n; m<=c;
m=c; q<=m+n;
q=m+n; end
Multiple assignments can be made to
end a variable within one procedure
Multiple assignments should be either -last assignment wins for non-
blocking or non-blocking blocking
Sandeepani
www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review


Usage in clocked procedures
Usage in combinational procedures
Mix usage
Sandeepani
www.sandeepani-vlsi.com

Mixed assignments
always @(posedge clk) always @(posedge clk)
begin begin
tempa=ip1;
…… temp=a+b;
tempb=f(tempa); q<=temp+c;
……
op1<= tempb;
end
……
end
Sandeepani
www.sandeepani-vlsi.com

Mixed assignments

•Blocking assignments can be used within clocked


procedures for temporary variables
• usage:
- assign inputs to temporary variables with blocking
assignment
-perform algorithm with temporary variables and
blocking assignment
-assign temporary variables to outputs with non-
blocking assignment
Sandeepani
www.sandeepani-vlsi.com

Definition of RTL Code


Sandeepani
www.sandeepani-vlsi.com

AIMS and Topics

• AIM

-To define that rule and coding guidelines for


RTL code, and to give an overview of portability
issues

Topics
-Combinational Procedures
-Clocked procedures
Sandeepani
www.sandeepani-vlsi.com

RTL Style
Combinational Procedure Clocked Procedure
always @ (a or b or c)
always @ (posedge clock)
begin
Begin
...

...

...
end
end

Tip Tip

blocking assignment Non-blocking assignment


(<=) should be used
(=) should be used
Sandeepani
www.sandeepani-vlsi.com

Complete Event List

always @ (a or b or sel)
• Even List for
begin
combinational logic must
if (sel = = 1)
contain all variables read
y = a;
within procedure
else
y = b;
What would the behavior end
be if sel was missing ?
Sandeepani
www.sandeepani-vlsi.com

Incomplete Event List


always @ (a or b or sel)
begin
Synthesis if (sel = = 1)
For combinational logic, include y = a;
all variables read in event list, else
y = b;
end
always @ (a or b or sel)
always @ (a or b) …

a
a

b
b
sel sel
y
y
Sandeepani
Incomplete Assignments in Combinational www.sandeepani-vlsi.com

Logic

• What is the value of b if module incomplete (ctrl, a, b);


input a, ctrl;
ctrl = 0 ?
output b;
reg b;
• What hardware would be
built it this is synthesized ? always @ (ctrl or a)
if (ctrl)
b = a;
• How can you avoid this
type of hardware ? endmodule
Sandeepani
www.sandeepani-vlsi.com

Avoiding Latches
module completel (ctrl, a, b);
input a, ctrl;
• Two ways to output b;
avoid latches:- reg b;
•Use default
always @ (ctrl or a)
statement begin
•Add else b = 0; // default
if (ctrl) module complete2 (ctrl, a, b);
clause input a, ctrl;
b = a;
end output b;
endmodule reg b;
always @ (ctrl or a)
begin
if (ctrl)
Question
b = a;
which do you think would be best for else
a procedure with complex nested if b = 0; / / default
statements? end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Continuous Assignments
• Continuous assignments drive values onto nets
-Outputs update simultaneously with any input change
-Combinational logic is implied
module orand (out, a, b, c, d, e);
input a, b, c, d, e;
output out;

assign out = e & (a b) & (c d) ;


endmodule

a
b
e out

c
d
Sandeepani
Rules for the Synthesis of www.sandeepani-vlsi.com

Combinational Logic
• Complete event list
• Default assignments to prevent latches
• Use blocking assignments
• Continuous assignment synthesizes to
combinational logic
• Avoid combinational feedback loops
• (Functions synthesize to combinational logic)
– Functions will be described later
Sandeepani
Register Inference in Clocked www.sandeepani-vlsi.com

Procedures
module counter (count, clk);
output [3:0] count;
• Clocked procedures triggered on
input clk; clock edge
reg [3:0] count; •Use only posedge/negedge in
event list
always @ (posedge clk)
if (count > = 9)
• Registers are inferred on all
count < = 0 ; non-blocking assignments in
else synchronous procedures
count < = count + 1;
endmodule

0 count Question
1 0
+ 1 4
4 What is the issue with
4

4
sel this counter description?
<
9 clk
Sandeepani
www.sandeepani-vlsi.com

Resetting Clocked Logic


Synchronous Reset Asynchronous Reset
module counter (count, clk, rst); module counter (count, clk, rst);
output [3:0] count ; output [3:0] count;
input clk, rst; input clk, rst;
reg [3:0] count ; rst [3:0] count;
always @ (posedge clk) always @ (posedge clk or posedge rst)
if (rst) / / active high reset if (rst) // active high reset
else if (count > = 9) count < = 4 ‘ b0;
count < = 4’ b0 ; else if (count < 9)
else count < = 4 ‘ b0;
count < = + 4’ b1 ; else
count < = count + 4 ‘ b1;
endmodule endmodule

• if-else used to add reset to clocked


procedure
• if defines reset behavior
• First else defines clocked behavior
• For asynchronous resets, active edge
of reset added to event list
Sandeepani
www.sandeepani-vlsi.com

Clocked Procedure Templates


always @ (posedge clk or negedge rst)
if (!rst) • always procedure
begin
// asynchronous reset behavior
• Event list only contains:-
end • posedge/negedge reset
else
begin
• posedge/negedge reset
// all synchronous actions for asynchronous reset
end
• Code must follow these
always @ (posedge clk)
if (!rst)
templates
begin
// synchronous reset behavior
end
else
begin TIP
// all synchronous actions
end Keep procedures with asynchronous resets
always @ (posedge clk) separate from procedures with
begin synchronous resets.
// all synchronous actions
end
Sandeepani
www.sandeepani-vlsi.com

Synchronous Feedback Inferrence


• Incomplete assignment in clocked procedure implies
synchronous feedback

module dffn (q, d, clk, en);


input d, clk, en;
output q; 0
reg q; d 1 q
en mux
always @ (posedge clk)
if (en)
q < = d; clk

endmodule
Sandeepani
www.sandeepani-vlsi.com

Clocked Procedure Assignment

a b c

clk

Question
How would you code this design in Verilog?
Sandeepani
Blocking and Non-blocking
www.sandeepani-vlsi.com

Assignment
1 always @ (posedge clk) 2 always @ (posedge clk)
begin begin
c < = b; b < = a;
b < = a; a < = b;
end end

3 always @ (posedge clk) 4 always @ (posedge clk)


begin begin
c = b; b = a;
b = a; c = b;
end end

• Easier to use non-blocking assignment to infer registers in


synchronous procedures
• Order independent
• Register inferred for each assignment
Sandeepani
www.sandeepani-vlsi.com

The Synthesis Process


Sandeepani
www.sandeepani-vlsi.com

AIMS ANDS TOPICS

* AIMS
- To introduce synthesis process and look at its strenths
and weaknesses

* TOPICS
- How a synthesis tool works
- Synthesis based methodology
- Synthesis strengths and weakness
- Programmable Logic device synthesis issues
- Language subsets
Sandeepani
www.sandeepani-vlsi.com

clk

WHAT DOES SYNTHESIS DO?


* Infers registers from cloked procedures
* Builds optimized combinational logic
* A new engineer task:
- How much of it?
- How well?
- Do you trust it?
Sandeepani
Verilog code Synthesis flow www.sandeepani-vlsi.com

* Verilog code is the


important input - the
quality of results
depends
mainly on the code
Technology * Technology Library
Constraints library is used to build the
File circuit from the verilog
Synthesis
Engine description
* Constraints File
drives the synthesis
engine

area/Speed Curve
Schematic

Gate Level Netlist Area


How Synthesis works Sandeepani
www.sandeepani-vlsi.com

Verilog code
Constrains file

Boolean Parsing

Mapping

Technology Gates
Library

Optimization
Gate Level Netlist

Schematic
Sandeepani
www.sandeepani-vlsi.com

clk

Coding Styles Affect Results


* Number of registers
- Combinational logic optimised only, not register numbers
or placement
* Amount of combinational logic inbetween registers
- Pipelining and logic timing mut be considered when
code written
* structure of .logic
Sandeepani
Translation Can Be Literal! www.sandeepani-vlsi.com

* Synthesis tools generate logic directly from the structure of


your code
-Here == operator is redundant but may still appear in the
synthesized netlist 011
d
always @ (posedge clk) d 011
d 011
if (d < 3) =
y <= a; >
? <
else if (d > 3) 0
0
y <=b; c 1 mux 0
else if (d == 3) y
1mux
y <= c; b 1 mux

? Question a
What would be the input at “?“
clk
Inferred hardware structure
What Synthesis Sometimes Can’t Do Well.. Sandeepani
www.sandeepani-vlsi.com

* Clock trees
- Usually require detailed, accurate net delay information
* Complex clocking schemes
- Synthesis tools prefer simple single clock
synchronous designs
* Memmory, IO pads, technology -specific cells
- You will probably need to instantiate these by hand
* Specific macro -cells
* Always as well as you can
- Although it can analyze hundreds of implementations
in the time taken for designer to analyze one
Sandeepani
www.sandeepani-vlsi.com

Programmable Logic Device Specific Issues


* Different architectures for
different technologies
* Fixed architecture within a
specific technology
* Architecture specific ‘tricks‘
for good utilization and
speed
* Code becomes technology
specific
* How your synthesis tool
handles your technology
Sandeepani
change code A Synthesis Methodology www.sandeepani-vlsi.com

Change constraints file


netlist

constraints tech library


n

synthesis y
meets area/speed?
verilog
functional?
y gate
rtl
simulation
simulation n
testbench
change code
compare
golden results results
Language Support Sandeepani
www.sandeepani-vlsi.com

* Synthesizeable Verilog is a subset of the full language


* There is no standard for synthesizeable code
* Diferent tool vendors have slightly different
interpretations of what is synthesizeable

Synthesis Subset
Full Verilog Language
Tool1

Tool2
Tool3
Tool4
Tool5
Sandeepani
Summary
www.sandeepani-vlsi.com

* RTL for synthesis


* Logic and gate optimization
* Coding style affects results
* Synthesis tools support subsets of
language style
Sandeepani
www.sandeepani-vlsi.com

Verilog Coding Guidelines


Sandeepani
www.sandeepani-vlsi.com

Blocking and nonblocking statements


Coding guidelines
Coding for Performanance(Examples)
Sandeepani
Blocking and non-blocking
www.sandeepani-vlsi.com

assignments
• Guidelines
– Use blocking assignments in always blocks that are
written to generate combinational logic
– Use nonblocking assignments in always blocks that
are written to generate sequential logic
• Ignoring these guidelines can result in a
mismatch between behavior of synthesized
circuit and the pre-synthesis simulation results
Sandeepani
www.sandeepani-vlsi.com

Comparison
• Evaluation of blocking statements requires
less simulator memory
• Evaluation of Non blocking statements
requires more simulator time
Sandeepani
www.sandeepani-vlsi.com

Coding Guidelines
Sandeepani
www.sandeepani-vlsi.com

Guideline 1
• To model combinational logic within an
always block, use blocking statements

a always
temp @(a or b or c)
out temp = a & b;
b out = c & temp;
endmodule
c
Sandeepani
www.sandeepani-vlsi.com

Guideline 2
• In order to model sequential logic, use
non-blocking assignment statements
Sandeepani
www.sandeepani-vlsi.com

Guideline 3
• In order to model latches, use non-
blocking statements
Sandeepani
www.sandeepani-vlsi.com

What’s wrong with this block?


always @(test or PC or AluOut)
begin if (select) begin
output = PC;
end else begin
output = AluOut;
end
end

Hint: Look at the sensitivity list.


Sandeepani
www.sandeepani-vlsi.com

Sensitivity List
• A signal that appears on the right-hand side of a
combinational always block must appear in the sensitivity
list of the always block.
• The only exceptions here are signals that are also
generated in the always block (are on the left-hand side).
– Verilog only evaluates always blocks only when a signal in the
sensitivity list changes.

always
@(a or b or c)
temp = a & b;
out = c & temp;
endmodule
Sandeepani
www.sandeepani-vlsi.com

What’s wrong with this block?


always @(select or PC or AluOut or IR1 or add3)
begin if (select == 2'h0) begin
output1 = PC; PC IR1 add3 AluOut
output2 = add3
end else if (select == 2'h3) begin
output1 = AluOut;
output2= IR1;
end 2 Selector
end select

output1 output2
Sandeepani
If/Case construct in
www.sandeepani-vlsi.com

Combinational always block


• Each left-hand side signal must be assigned in
every possible case.
• If it is not assigned to in one of the cases, then
you have "implied a latch" -- there is some set of
inputs for which this gate does not take on a new
value and therefore "holds" its old value.
• No longer a combinational logic element!
Sandeepani
www.sandeepani-vlsi.com

Correct implementation
always @ (select or PC or AluOut or IR1 or add3 or output1 or output2)
begin
if (select == 2'h0) begin
output1 = PC;
output2 = add3
end else if (select == 2'h3) begin
output1 = AluOut;
output2= IR1;
end else begin
output1 = output1;
output2 = output2;
end
end
Sandeepani
www.sandeepani-vlsi.com

What’s not good here?


always @(posedge CLK) begin
Q <= `TICK D;
Z <= `TICK (a ^ b) & (sig1 | sig2);
end

D Q

a
b Z
sig1
sig2
Sandeepani
www.sandeepani-vlsi.com

More readable code


wire nextZ;
assign nextZ = (a ^ b) & (sig1 | sig2);
always @(posedge CLK)
begin Q <= `TICK D;
Z <= `TICK nextZ;
end

Q
a D
b
sig1 Z
sig2 nextz
Sandeepani
www.sandeepani-vlsi.com

Add comments in your code


• Others can read and understand your design
• You can understand your design after 3 months
when you may have to debug the design!
• Make sure that you modify the comments if you
are modifying the design!
• If you are modifying someone else’s code, add
comments regarding what modification you
made and the date of modification.
• Do not delete old code; comment it.
• Learn to write simple and helpful comments.
Sandeepani
www.sandeepani-vlsi.com

Indentation
• Indent your code.
• Proper indentation makes your code
easier to read and debug.
• Indentation also forces you to write better
code: levels of nesting will be in kept in
check!
Sandeepani
www.sandeepani-vlsi.com

`define statements
• Do not use hardwired constants all over the place;
instead, use meaningful names.

if (opcode == 6b`000010) `define ADD 6b`000010


then begin `define SUB 6b`000011
end else if (opcode == `ADD)
if (opcode = 6b`000011) then begin
then begin end else
end if (opcode = `SUB) then
begin
end
Sandeepani
www.sandeepani-vlsi.com

Examples of coding style


Sandeepani
www.sandeepani-vlsi.com

Priority Encoder
module my_if (c, d, e, f, s, pout);
input c, d, e, f; input [1:0] s;
output pout; reg pout;
always @ (s or c or d or e or f)
begin : myif_pro
if (s == 2'b 00) begin
pout <= c;
end else if (s == 2'b 01 ) begin
pout <= d;
end else if (s == 2'b 10 ) begin
pout <= e;
end else begin
pout <= f;
end
end
endmodule // module my_if
Sandeepani
www.sandeepani-vlsi.com

Multiplexer

module mux (c, d, e, f, s, muxout);


c input c, d, e, f;
input [1:0] s;
d output muxout; reg muxout;
e always @ (s or c or d or e or f)
begin : mux1
f case (s)
2'b 00: begin muxout <= c; end
s 2'b 01: begin muxout <=d; end
2'b 10: begin muxout <= e; end
default: begin muxout <= f;
end endcase
end endmodule // module mux
Sandeepani
www.sandeepani-vlsi.com

Multiplexer vs Latch
a
if (select)
y
y = a;
b else
y = b;

a y
if (select)
y = a;
select
Sandeepani
Register with Asynchronous
www.sandeepani-vlsi.com

Reset
module dff_async_reset (data, clk, reset, q);
input data, clk, reset;
output q; reg q;
always @ (posedge clk or negedge reset)
data q if (~reset)
q = 1’ b0
else
q = data;
endmodule

clk
reset
Sandeepani
Clock-triggered Flip-flop with
www.sandeepani-vlsi.com

Enable control

module ff_clk (d, en, clk, clr, q);


input d, en, clk, clr;
output q; reg q;
d always @ (clk or clr) begin
q
if (clr == 1'b 0) begin
q <= 1'b 0;
end else
if (clr & clk == 1'b 1 ) begin
if (en == 1'b 1) begin
clk q <= d;
end
en clr end
end
endmodule / / module ff_clk
Sandeepani
www.sandeepani-vlsi.com

Resource Sharing:I

if (select)
+
sum <= A + B;
B else
Mux sum <= C + D;
sum

C
+

D select
We are sharing the multiplexer.
Sandeepani
www.sandeepani-vlsi.com

Resource Sharing:II

A
if (select) begin
temp1 <= A;
mux
temp2 <= B;
B end
select + else begin
sum
temp1 <= C;
C temp2 <= D;
mux end
sum <= temp1 + temp2;

D select

We are sharing the adder.


Sandeepani
www.sandeepani-vlsi.com

Resource Sharing:III
vsum

+
0 vsum = sum;
mux
for (i=0;i<3;i++)
Offset[0]
begin
if (req[i]=1‘b1) begin
0
vsum <= vsum + offset[i];
mux + end;
Offset[1] end loop;

0
mux +
Offset[2]
Sandeepani
www.sandeepani-vlsi.com

Resource Sharing:IV

mux
vsum R

0 +

Offset[0]
mux
Offset[1]

Offset[2]

Can we rewrite to code to generate


hardware that looks like this?
Sandeepani
www.sandeepani-vlsi.com

Code that forgets performance

sum := start;
for (i=0;i<2;i++)
start
begin
sum <= sum + inc[i];
inc[0] + end;

+
inc[1]
+
sum
inc[2]
Sandeepani
www.sandeepani-vlsi.com

Performance-oriented coding

start sum = ((inc[2] + inc[1]) + ((inc[0] + start));


inc[0] +

+
inc[1] sum
+
inc[2] Loop Unrolling performed by designer!
Sandeepani
www.sandeepani-vlsi.com

Overchecking for conditions can


increase hardware

data_in data_out

always @ (posedge clk) begin


if (req == 4'b1000)
data_out <= data_in;
end
clk end
en

req
Sandeepani
www.sandeepani-vlsi.com

Simplifying the code

data_in data_out

always @ (posedge clk) begin


if (req(3) == 1'b1)
data_out <= data_in;
clk end
en end

req[3]
Sandeepani
www.sandeepani-vlsi.com

Optimization in case statements

always @ (posedge clk) begin


if (req) begin
case (r)
5'b00001: c <= a(0);
5'b00011: c <= a(1);
5'b00101: c <= a(2);
5'b00111: c <= a(3);
5'b01001: c <= b(0);
5'b01011: c <= b(1);
5'b01101: c <= b(2);
5'b01111: c <= b(3);
default: c <= 1'bx;
end case
end
Sandeepani
How can we obtain this
www.sandeepani-vlsi.com

hardware instead?

a[3:0]

c
8-to-1 mux
DFF
r[4]
b[3:0]
r[0]
clk
r [3:1]
Sandeepani
www.sandeepani-vlsi.com

Summary
• Synthesis is still an evolving art
– Unless you describe exactly what you want,
the synthesizer will misunderstand you!
• Following a set of guidelines will help
• Good coding styles will help you and the
synthesis tool
Sandeepani
www.sandeepani-vlsi.com

Finite State Machines


Sandeepani
www.sandeepani-vlsi.com

Topics
• FSM Basics
• Steps for FSM design
• Example design
• HDL code for FSM
Sandeepani
www.sandeepani-vlsi.com

Any Sequential Logic Circuit is


a State Machine
• Single flip-flop has two states - `0`, `1`
• A circuit with 2 flip-flops can have a
maximum of 4 states.
• n flip-flops can have 2n states.
Sandeepani
www.sandeepani-vlsi.com

Flip Flip as an FSM

D Q

CLK
Sandeepani
www.sandeepani-vlsi.com

Simple Transition Sequence


• Sequential circuits like counters and shift
registers have a fixed transition sequence
• Counters - 00000, 00001, 00010, 00011…
each count is a state, total 25
• Shift Registers - 00001, 00010, 00100,
each shift position is a state, total 5
Sandeepani
www.sandeepani-vlsi.com

Complex trasitions
Coin collection FSM
TO
00p
25p Possible
50p Possible Possible
75p Possible Possible
100p Possible Possible Possible Possible
00p 25p 50p 75p 100p
FROM
Sandeepani
www.sandeepani-vlsi.com

What is an FSM?
Design Specification Point of View
• State machines are a means of specifying
sequential circuits which are generally
– complex in their transition sequence
– and depend on several control inputs.
Sandeepani
www.sandeepani-vlsi.com

What is an FSM?
Digital Circuit Point of View
• State machines are a group of flip-flops,
whose group-state transition pattern (from
one set of values to another ) is
– generally unconventional
– and depends on several control inputs
Sandeepani
www.sandeepani-vlsi.com

FSM Structure

ACTION PORTS
COMBINATORIAL
CURRENT
STATE CURRENT
COMB. STATE
LOGIC NEXT
for STATE
CONTROL
NEXT
INPUTS
STATE STATE
REGISTER
FLIP-FLOPS

ACTION PORTS
REGISTERED
CLOCK

ASYNC
CONTROL

PORTS
Sandeepani
www.sandeepani-vlsi.com

FSM Design Steps


• Define the ports
• Define the states
• Define transitions and conditions
• Define the actions
• Write code for synthesis
Sandeepani
www.sandeepani-vlsi.com

State Machine: State Diagram


01 = 1’bo
01 =1 ’bo
State Names
A (A,B,C,D,E,)
3’b000 01 =1’b0
02 =1’b0 State encoding:
b=1 ’ b 1 a= 1’b1
A=3’ b000,
C B=3’b001…
3’b011
B Transition
3’b001 b= 1’b o {a, b} = 2’b11 Conditions:
01 = 1’b1 {a ,b}=2’b01
02 = 1’b1 {a ,b}=2’b01 a= 1’b0
Output values:
D a =1’b1 01=1’b0
3’b010

01 = 1’b0 E
3’b110
02 = 1’b0

01= 1’b0
02= 1’b1
Sandeepani
www.sandeepani-vlsi.com

State Machine: Declarations and Clocked


Procedure
• Use parameters for state encoding module fsm (a, b, clock, reset, 01, 02);
• Reset strategy for state register input a, b, clock, reset;
• Partition into clocked procedure output 01, 02 ;
and combinational procedures // parameter declarations (state encoding)
parameter A = 3’b000, B = 3’b001,
C = 3’b011, D = 3’b010,
E = 3’b110;
// wire and reg declarations
Output Logic reg [2:0] state, next_state ;
reg 01, 02 ;
State register 01
// clocked procedure
a always @(posedge clock or posedge reset)
02 begin: STATEREGISTER
b if (reset)
Next State Logic
state < = A;
state else
state < = next_state ;
end
Next_state …
Sandeepani
www.sandeepani-vlsi.com

State Machine: Declarations and Clocked


Procedure
• Use parameters for state encoding module fsm (a, b, clock, reset, 01, 02);
• Reset strategy for state register input a, b, clock, reset;
• Partition into clocked procedure output 01, 02 ;
and combinational procedures // parameter declarations (state encoding)
parameter A = 3’b000, B = 3’b001,
C = 3’b011, D = 3’b010,
E = 3’b110;
// wire and reg declarations
Output Logic reg [2:0] state, next_state ;
reg 01, 02 ;
State register 01
// clocked procedure
a always @(posedge clock or posedge reset)
02 begin: STATEREGISTER
b if (reset)
Next State Logic
state < = A;
state else
state < = next_state ;
end
Next_state …
Sandeepani
State Machine: Combinational www.sandeepani-vlsi.com

Procedures
always @ (a or b or state) always @ (state)
begin: NEXTSTATE begin: OUTPUTDECODE
next_state = state ; // DEFAULT ASSIGNMENTS
case (state)
01 = 1’b0 ;
A : begin 02 = 1’b0 ;
if (a) next_state = C; case (state)
else if (b) next_state = B; B: begin
end 01 = 1’b1;
B: begin 02 = 1’b1;
if (~b) next_state = A; end
else if ( { a,b} = = 2’b01) next_state = D; E: 02 = 1’b1;
end end
C: begin end // end output decode logic
if (a) next_state = E;
else if ( {a,b} = = 2’b11) next_state = D;
 Next state and output decode
end
D:next_state = A;
combinational procedures
E: if (~a) next_state = C; could be merged
end // end next state logic  Next state and state register
procedures could be merged
Sandeepani
www.sandeepani-vlsi.com

If Synthesis
module if_example (a, b, c, ctrl, op);
input a, b, c;
input [3:0] ctrl ;
output op;
reg op;

always @ (a or b or c or ctrl)
if (ctrl) = = 4’b0000)
op = a; Question
else if (ctrl < = 4’b0100) Draw the architecture of
op = b ; hardware that this
else represents.
op = c ;

endmodule
Sandeepani
www.sandeepani-vlsi.com

If and Case Architectures


if (ctrl = = 4’b0)
case (ctrl)
op = a ;
0: op = a;
else if (ctrl < = 4’d4 )
0,1,2,3,4 : op = b;
op = b ;
default: op = c;
else
endcase
op = c ;
if synthesis c b a

ctrl Question
o 1
<= What hardware structure is created
4 for a case statement?
ctrl
0 1 Depends if case statement is
=
parallel or not!
0 op
Sandeepani
www.sandeepani-vlsi.com

Case Synthesis
• Case statement allowed to have overlapping choices
– Choices prioritized in order of appearance
• Some synthesis tools infer priority encoder structure
– Even for cases with no choice overlap
• Case with mutually exclusive choices can be built
with non-prioritized logic
case (ctrl)
0; op = a ;
Prioritized case synthesis
0, 1, 2, 3, 4 : op = b ; ctrl c b a
default op = c ;
endmodule <= 0 1
case (ctrl) 4
0: op = a ; ctrl
1, 2, 3, 4 : op = b ;
default : op = c ; = 0 1
endcase
op
0
Sandeepani
Parallel Case Statement www.sandeepani-vlsi.com

• Case with mutually exclusive


choices known as parallel case case (ctrl)
– Can be implemented with 0: op = a ;
non-prioritized logic 1, 2, 3, 4 : op = b ;
• Most synthesis tools can default : op = c ;
recognize parallel case endcase
– Others may need to be told case (ctrl)
case is parallel // rtl_synthesis parallel_case
• Directives can be used to 0: op = a ;
control synthesis 1, 2, 3, 4 : op = b ;
– Embedded comments which default op = c ;
are recognized by synthesis endcase
Important
Never apply directive to a non- ctrl
c b a
parallel case
<
Tip: If your synthesis tool supports 5
it, create parallel case by design
not by directive ctrl
> op
5
parallel case synthesis
Sandeepani
Synthesis Directives www.sandeepani-vlsi.com

• Most synthesis tools handle directives or programs


• Directives are verilog comments, ignored by
simulation but meaningful to synthesis
– Aim is to control synthesis optimization from within the RTL
code.
case (test) $display
// rtl_synthesis parallel_case writes a message
2’b00: op = 1 ; to the simulator
2’b01, transcript window
2’b10: op = 2 ;
2’b11: op = 3 ; Caution
default : // rtl_synthesis off Can lead to different
$ display (“unknown test!”); RTL/Gate level
// rtl_synthesis on functionality from
endcase Same design – use
With caution!
Sandeepani
Casez Synthesis
• casez is treated similar to
www.sandeepani-vlsi.com

always @ (pri_in) case by the synthesis tool


begin
casez (pri_in) • casez can be parallel or
4’ b1??? : op = 3 ; non-parallel
4’ b01?? : op = 2 ; – Parallel casez will synthesis
4’ b001? : op = 1 ; to parallel logic
4’ b0001 : op = 0 ; – Non-parallel casez will
default : op = 0 ; synthesize to prioritized logic
endcase
end • Synthesis tool may need to
be told casez is parallel
always @ (ctrl)
Important
begin
{int0, int1, int2 } = 3’ b000 Make sure casez actually is parallel
casez (ctrl) before using directives
3’ b?/1 : int0 = 1’ b1 ;
3’ b?1?: int1 = 1’ b1 ; Question
3’b1?? : int2 = 1’ b1 ;
endcase Are these casez statements parallel
end or not?
Sandeepani
www.sandeepani-vlsi.com

Full Case • Case branches do not need


to cover all values for case
// declarations for examples expression
module case_1 (b, c, ctrl, op) ;
– Can cause incomplete
input [3:0] b, c ; assignments in
input [1:0] ctrl ; combinational code.
output [3:0] op ; -Will synthesze latches
reg [3:0] op
• Full case (for synthesis)
covers all binary values of
always @ (ctrl or b or c) case expression.
case (ctrl) – Ignoring x and z value
0, 1 : op = b ; case not full- combinations
2 : op = c ; latches inferred
endcase always @ (ctrl or b or c)
case (ctrl)
default makes
always @ c(ctrl or b or c) 0, 1: op = b ;
full case for
case (ctrl) 2: op = c ;
synthesis and
0, 1 : op = b ; default : op = 0 ;
simulation
2 : op = c ; endcase
3 : op = 0 ; Full case for
endcase synthesis
Sandeepani
www.sandeepani-vlsi.com

Full Case Directive


• Most synthesis tools can
always @ (ctrl or b or c) recognize full case
//rtl_synthesis full_case – Others may need to be told
case (ctrl) case is full
0, 1 : op = b ; • Can use synthesis directive to
2, 3 : op = c ; force full case
endcase • What happens if directive
applied to case description
which is not full?
Caution – Assumes missing case
Make sure case actually is full values can be implemented
before using directives as “don’t care”
– Can cause RTL to gate level
always @ (ctrl or b or c) simulation mismatches
begin • Full case issue avoided if
op = c ; default assignments used
case (ctrl)
0, 1 : op = b ;
2 : op = c ;
endcase
end
Sandeepani
www.sandeepani-vlsi.com

Case Directive Exceptions


• A full case statement can still synthesize latches
– Even if the full_case directive and default option are used
• Incomplete assignments can occur for any variable
assigned to in a combinational procedure.
– Default statements can prevent problems
module select (a, b, sl ) ;
input [1:0] sl ;
output a, b ;
req a, b ; Question
always @ (sl)
There is latch inferred from
case (sl) // rtl_synthesis full_case
2’ b00 : begin a = 0 ; b = 0 ; end this code. What is the name
2’ b01 : begin a = 1 ; b = 1 ; end of the latches variable and
2’ b10 : begin a = 0 ; b = 1 ; end
how can it be prevented?
2’ b11 : b = 1 ;
default : begin a = ‘bx; b = ‘bx; end
endcase
endmodule
Sandeepani
www.sandeepani-vlsi.com

Initial Statements
module counter (clk, rst, q ) ;
module counter (clk, q ) ;
input clk ; input clk, rat ;
output [ 3 : 0 ] q ; output [3 : 0] q ;
reg [3:0] q: reg [3 :0] q ;

initial q = 0 ; always @ (posedge clk)


if (rst)
always @ (posedge clk) q < = 4’ b0; // synchronous reset
if (q > = 9)
else if (q >= 9)
q < = 4 ‘ b0 ;
q < = 4’ b0;
else
q <= q+1; else
q<=q+1;
endmodule endmodule

Question Synthesis
What does this initial statement mean: Synthesizable equivalent-add
1.For simulation? reset
2.For synthesis?
Sandeepani
www.sandeepani-vlsi.com

Summary
• FSM is a systematic way of specifying any
sequential logic
• Ideally suited for complex sequential logic
• Translating the problem in terms of
discrete states is the “difficult” part
• Define the FSM and generate the code
Sandeepani
www.sandeepani-vlsi.com

Structural Modeling
Sandeepani
Aims and Topics www.sandeepani-vlsi.com

* Aims
- Learn about the full capabilities of verilog for structural
,gate level modeling and modeling memories
* Topics
- Built in primitives
- Modeling memories
Sandeepani
Structural Modeling
www.sandeepani-vlsi.com

* Pure structural model only contains instantiated modules,


primitives and wire connections
* Used for block diagrams, schematics, post synthesis netlist
and ASIC/FPGA
a nsela

sel out
nsel
module mux (a, sel, b, out);
selb input a, sel, b;
b output out;
wire nsela, selb, nsel;
OR2 U32(.A(nsela), .B(selb), .Z(out) );
IV U33 (.A(sel), Z(nsel) );
AN2 U34 (.A(a), .B(nsel), .Z(nsela) );
AN2 U35 (.A(b), .B(sel), .z(selb) );
Sandeepani
Conditional Primitives www.sandeepani-vlsi.com

* Four different types of conditional primitives


* Conditional primitives only have three pins: output, input and enable
* Enabled and disabled by the enable pin
- When disabled outputs are at high impedance

Primitive Name Functionality


bufif1 Conditional buffer with logic 1 as enabling input
bufif0 Conditional buffer with logic 0 as enabling input
notif1 Conditional inverter with logic 1 as enabling input
notif0 Conditional inverter with logic 0 as enabling input
Sandeepani
Conditional Buffers www.sandeepani-vlsi.com

bufif1
bufif1
data out
data out

enable enable

bufif1(out, data, enable) bufif1(out, data, enable)


enable enable
bufif1 0 1 x z bufif0 0 1 x z
0 z 0 L L 0 0 z L L
data 1 z 1 H H 1 1 z H H
x z x x x x x z x x
z z x x x z x z x x

note : Verilog uses the symbols L and H to represent partially unknown


logic values
Sandeepani
Modeling a Memory Device www.sandeepani-vlsi.com

A memory device must do two things :


* Declare a memory of appropriate size
* Provide some level of access to its contents, such as :
- Read only
- Read and Write
- Write and Simultaneous read
- Multiple reads , simultaneous to a single write
- Multiple simultaneous reads and writes, with
some method of ensuring consistency
Sandeepani
Simple ROM Model www.sandeepani-vlsi.com

my_rom_data
‘timescale 1ns / 10ps 0000
module myrom (read_data, addr, read_en_); 0101
input read_en_; 1100
input [3:0] addr; 0011
output [3:0] read_data; 1101
reg [3:0] read_data; 0010
reg [3:0] mem [0:15]; 0011
1111
initial 1000
$readmemb (“my_rom_data“, mem); 1001
always @ (addr or read_en_) 1000
if (! read_en_) 0001
read_data = mem[addr]; 1101
endmodule 1010
0001
ROM data is stored in a separate file 1101
Sandeepani
Simple RAM Model www.sandeepani-vlsi.com

module mymem (data, addr, read, write);


inout [3:0] data;
input [3:0] addr;
input read , write;
reg [3:0] memory [0:15]; 4 bit , 16 word array for
// read memory contents
assign data = (read ? memory [addr] : 4’bz);
// write
always @ (posedge write)
memory[addr] = data; tr i- state controller
endmodule enabled by read

rising edge triggered


RAM write
Note :Simultaneous models for internal RAM/ROM usually
supplied by technology vendor
Sandeepani
Scalable Memory device www.sandeepani-vlsi.com

* Parameters can be used to scale memory models


module scalable _ROM (mem_word, address);
parameter addr_bits = 8; size of address bus
parameter wordsize = 8; width of memory word
parameter words = (1 << addr_bits); size of memory

output [wordsize : 1] mem_word; output word


input [addr_bits : 1] address; address bus
memory
reg [wordsize : 1] mem [0 : words - 1];
declaration
// output one word of memory
wire [wordsize : 1] mem_word = mem[address]; continuous
assignment
endmodule to output
Sandeepani
Loading a Memory www.sandeepani-vlsi.com

* ROM will need to be loaded with data


* RAM may need to be initialzed
* Memory can be pre - loaded via loops or from an external file
// initialize memory via loop
for (i = 0 ; i< memsize ; i = i+1)
mema [i] = {wodsize {1 ‘b0}};

// load memory from a file


$ readmemb (“mem_file . txt“, mema);
Sandeepani
Using inout Ports www.sandeepani-vlsi.com

module mymem (data , addr , read , write);


inout [3 : 0] data;
input [3 : 0] addr;
input read, write;
.............

assign data = (read ? memory[addr] : 4’ bz);


...................

* Bi - directional ports are declared with the inout keyword


* You can not directly connect an inout port to a register
* Your design should drive an inout port from only one direction at
a time
- To avoid bus contention
- You must design logic around the inout port to ensure
proper operation
Sandeepani
Bidirectional Ports Using Primitives www.sandeepani-vlsi.com

en_a_b
b1

bus_a bus_b

b2 en_b_a
module bus_xcvr(bus_a , bus_b, en_a_b, en_b_a);
input bus_a, bus_b;
When en_a_b = 1,
input en_a_b , en_b_a;
primitive b1 is enabled
bufif1 b1 (bus_b , bus_a , en_a_b);
and the value on bus_a
bufif1 b2 (bus_a , bus_b , en_b_a);
is transferred to bus_b
//structural module logic
endmodule When en_b_a = 1,
primitive b2 is enabled
and the value on bus_b
is transferred to bus_a
Sandeepani
Bidirectional Ports Using Continuos Assignment www.sandeepani-vlsi.com

en_a_b
b1

bus_a bus_b

b2 en_b_a
module bus_xcvr(bus_a , bus_b, en_a_b, en_b_a);
input bus_a, bus_b;
When en_b_a = 1,
input en_a_b , en_b_a;
this assignment drives
assign bus_b = en_a_b ? bus_a : ’bz;
the value of bus_b
assign bus_a = en_b_a ? bus_b : ’bz;
on to bus_a
//structural module logic
endmodule When en_a_b = 1,
this assignment drives
the value of bus_a
on to bus_b
Sandeepani
Modeling Memory Ports www.sandeepani-vlsi.com

Test Bench RAM cell


rd

data
bus data
reg
wr
module ram_cell (databus, rd, wr); when rd = 1 the value
input databus; of datareg is assigned
input rd, wr; to databus
reg datareg;

assign databus = rd ? datareg : ‘bz; When wr deasserts


always @ (negedge wr); the value of databus
datareg <= databus; is writteb to datareg
endmodule
Sandeepani
www.sandeepani-vlsi.com

Gate level Modeling


Sandeepani
Aims and Topics www.sandeepani-vlsi.com

* Aims
- Understand how to model simple delays for
simulations and gate level models
* Topics
- Lumped delays
- Distributed delays
- Path delays
- Specify timing blocks
Sandeepani
Delay Modeling Types www.sandeepani-vlsi.com

noror ASIC cell 1


a Lump the entire delay
net1
b n1 at the last gate

c o1 out

3 Use a specify block


2 to specify pin-to-pin
distribute the delays for each path
delay across each
gate
Typical delay specification Delays can be modeled in three ways :
delay from a to out =2
delay from b to out = 3
delay from c to out = 1
Sandeepani
Lumped Delay www.sandeepani-vlsi.com

* Lumped delays place entire delay on the last gate


-Simple to implement
a - Does not allow for different path delays
b
path delay as modeled
a -> out is 3
c #3 out b -> out is 3
c -> out is 3

‘timescale 1ns / 1ns


module noror (out, a, b, c);
output out;
input a, b, c;
nor n1 (net1, a, b);
or #3 o1 (out, c, net1);
endmodule
Distributed Delays Sandeepani
www.sandeepani-vlsi.com

* distributed delays divide delay over more than one gate


- Allows different delays for different paths
a - Delays accumulate along the path
b #2
path delay as modeled
a -> out is 3
c #1 out b -> out is 3
c -> out is 1

‘timescale 1ns / 1ns


module noror (out, a, b, c);
output out;
input a, b, c;
nor #2 n1 (net1, a, b);
or #1 o1 (out, c, net1);
endmodule
Module Path Delays Sandeepani
www.sandeepani-vlsi.com

* Specify block allows individual path delay to be defined


- Paths from the inputs to outputs of a module
a
net1
b n1
path delays
a -> out is 2
c o1 out b -> out is 3
c -> out is 1
Sandeepani
The Specify Block www.sandeepani-vlsi.com

module noror (out, a, b, c); * Specify block defines module


output out; timing data
input a, b, c; - Separates timing information
nor n1 (net1, a, b); from functionality
or o1 (out, c, net1); * Typical tasks for specify block:
- Define module timing paths
specify - Assign delays to those paths
(a => out) = 2; - Perform timing checks
(b => out) = 3; * Module parameters can not be
(c => out) = 1; used in a specify block
endspecify - Specify blocks use a special
“specify parameter“ (specparam)
endmodule - See later .............
Sandeepani
Specify Block Parameters www.sandeepani-vlsi.com

Module noror (op. a, b, c); * Specparam declares


output op; parameters for specify block
input a, b, c; * Must be declared inside
nor n1 (net1, a, b); specify block
or o1 (op, c, net1); - Only visible inside block
* Cannot be over-ridden like
specify parameters
specparam aop = 2; * Parameters cannot be used
bop = 3; inside a specify block
cop = 1; - Must use specparam
(a => op) = aop;
(b => op) = bop;
(c => op) = cop;
endspecify
endmodule
Sandeepani
Accurate Delay Control www.sandeepani-vlsi.com

*Rise, fall and turn-off delays can be specified for gates and module paths
- Rise is transition to 1
- Fall is transition to 0
- Turn-off is transition to z
and # (2, 3) (out, in1, in2, in3); // rise, fall
bufif0 #(3, 3, 7) (out, in, ctrl); // rise, fall. turn-off
spacify
(in => out) = (1, 2); // rise, fall
(a = > b) = (5, 4, 7); // rise, fall, turn-offs
endspecify
* Minimum , typical and maximum values can be specified for each delay
- Syntax - (minimum : typical : maximum)
or # (3 . 2 : 4 . 0 : 6 . 3) o1 (out, in1, in2); // min : typ : max
not # (1 : 2 : 3, 2 : 3 : 5) (o, in); // min : typ : max for rise, fall
specify
// min:typ:max for rise, fall and turn-off
(b => y) = (2 : 3 : 4, 3 : 4 : 6, 4 : 5 : 8);
endspecify
Parallel and Full Connection Module PathsSandeepani www.sandeepani-vlsi.com

* => represents parallel connection


- Must be between ports must be of the same size
* * > represents full connection
- All listed inputs connect to all listed outputs
Parallel module path Full module path
q output
input a q output input a
bits b qb bits bits b bits
qb
2 paths 4 paths
Bit - to - bit connections Bit - to - vector connections
Use => to define path Use *> to define path
(a, b *> q, qb) = 15;
(a, b => q, qb) =15; is equivalent to
is equivalent to (a => q ) = 15;
(a => q ) = 15; (b => q ) = 15;
(b => qb ) =15; (a => qb ) = 15;
(b => qb ) = 15;
Sandeepani
State Dependent Path Delays www.sandeepani-vlsi.com

* State dependent path delay are assigned to module path only


if a specific condition is true
- Note : not an if statement - no else is allowed....

module jexor (op, a, b);


input a, b;
output op;
a
xor (op, a, b); op
b
specify
if (a) (b => op) = (5 : 6 : 7);
if (!a) (b => op) = (5 : 7 : 8);
if (b) (a => op) = (4 : 5 : 7);
if (!b) (a => op) = (5 : 7 : 9);
endspecify
endmodule
Sandeepani
www.sandeepani-vlsi.com

User Defined Primitives


Sandeepani
www.sandeepani-vlsi.com

AIMS AND TOPICS


Aims
* Learn how to build logic using user defined primitives

Topics
* Understand verilog composite libraries
* Understand functional modeling of ASIC libraries
* Learn about the use of UDPs in ASIC library models
Sandeepani
WHAT IS A UDP ? www.sandeepani-vlsi.com

Verilog has over two dozen gate level primitives for modeling
structural logic . In addition to these primitives Verilog has
user defined primitives (UDPs) that extend the built in
primitives by allowing you to define logic in tabular format.

UDPs are useful for ASIC library cell design as well as small
scale chip and medium scale chip design
* You can use UDPs to augment the set of predefined
primitive element s
* UDPs are self contained , they do not instantiate other
modules
* UDPs can represent sequential as well as combinational
elements
* UDP behavior is described in a truth table
* To use a UDP you instantiate like a built in primitive
Sandeepani
FEATURES www.sandeepani-vlsi.com

* UDPs can have only one output


* UDPs can have 1 to 10 inputs
* All ports must be scalar and no bi-directional ports are
allowed
* The Z logic value is not supported
* The output port must be listed first in the port list
* The UDP output terminal can be initialized to a known
value at the start of simulation
* UDP can not be synthesized
COMBINATIONAL EXAMPLE : 2 - 1 MULTIPLEXER Sandeepani www.sandeepani-vlsi.com

The output port must be the


This is the first port
name of the
primitive multiplexer (o, a, b, s);
primitive
output o;
input a, b, s;
table
// a b s : o
0 ? 1 : 0;
1 ? 1 : 1;
? 0 0 : 0;
? 1 0 : 1;
0 0 x : 0;
1 1 x : 1;
endtable These entries
endprimitive reduce pessimism

* UDP definitions occur outside of a module


* The output becomes x for any input combination not specified in table
Sandeepani
COMBINATIONAL EXAMPLE : FULL ADDER www.sandeepani-vlsi.com

Cin
A G1
G2 Sum
B
G4
G5 Cout
G3

Cin
A U_ADDR2_S Sum
B

U_ADDR2_C Cout

You can implement the full adder with only two combinational UDPs
cont........next...
Sandeepani
www.sandeepani-vlsi.com

//FULL ADDER SUM TERM


//FULL ADDER CARRY- OUT TERM primitive u_addr2_s (s, a, b, ci);
primitive u_addr2_c (co, a, b, ci); output s;
output co; input a, b, ci;
input a, b, ci;
table table // a b ci : s
a b ci : co 0 0 0 : 0;
1 1 ? : 1; 0 0 1 : 1;
1 ? 1 : 1; 0 1 0 : 1;
? 1 1 : 1; 0 1 1 : 0;
0 0 ? : 0; 1 0 0 : 1;
0 ? 0 : 0; 1 0 1 : 0;
? 0 0 : 0; 1 1 0 : 0
endtable 1 1 1 : 1
endprimitive endtable
endprimitive
Sandeepani
LEVEL - SENSITIVE SEQUENTIAL EXAMPLE : LATCH www.sandeepani-vlsi.com

primitive latch ( q, clock, data);


output q;
reg q; Note the use of a
input clock, data; register for storage
initial q = 1’ b1; The output is
table initialized to 1’ b1
// clock data current next
// state state
0 1 : ? : 1;
0 0 : ? : 0;
1 ? : ? : - ;
endtable
endprimitive Notice the additional
The ? is used to represent field used to specify
don’t care conditions in a next state
the inputs and current state
EDGE - SENSITIVE SEQUENTIAL EXAMPLE : D FLIP - FLOP Sandeepani
www.sandeepani-vlsi.com

primitive d_edge_ff ( q, clk, data );


output q;
input clk, data;
reg q
table
// clk dat state next :
(01) 0 : ? : 0 ;
(01) 1 : ? : 1 ;
(0x) 1 : 1 : 1 ;
(0x) 0 : 0 : 0 ;
(x1) 0 : 0 : 0 ;
(x1) 1 : 1 : 1 ;
// ignore negative edge of clock
(?0 ) ? : ? : - ;
(1x) ? : ? : - ;
// ignore data changes on steady clock
? (??) : ? : - ;
endtable
endprimitive
SHORTHAND TO IMPROVE READABILITY Sandeepani
www.sandeepani-vlsi.com

Verilog has symbols that can be used in UDP table to improve readability

Symbol Interpretation Explanation

b 0 or 1 Any known value

r ( 01) 0 -> transition

f ( 10 ) 1 -> 0 transition

p ( 01) or ( 0x ) or ( x1) Any positive edge,including unknowns

n ( 10 ) or ( 1x ) or ( x0 ) Any negative edge,including unknowns

* ( ?? ) Any transition
Sandeepani
SUMMARY www.sandeepani-vlsi.com

* UDPs allow you to create your own primitives to extend those built in
to Verilog
- Behavior is defined using a table
- UDPs are instantiated like built - in primitive
* They are a compact, efficient method of describing logic functions
- Both combinational and sequential behavior can be described
- UDPs are self - contained
- Many built - in primitives can be replaced by a single UDP
* There are some restrictions on using UDPs, including :-
- There must be a separate UDP for every output
- The Z value is not supported hence UDP ports can not be
bi - directional
- UDPs are not synthesisable
Sandeepani
www.sandeepani-vlsi.com

Verification Overview
Sandeepani
www.sandeepani-vlsi.com

Objectives

After completing this module ,you will be able to..

•Understand verification flow

•Testbench structure

•Different ways of generating vectors


Sandeepani
www.sandeepani-vlsi.com

Outline
Introduction
Vector generation
Simulation tips
summary
Sandeepani
www.sandeepani-vlsi.com

Verification Flow

System Specifications

TB RTL

Test Pass

Yes
Sandeepani
www.sandeepani-vlsi.com

Introduction

Purpose of writing testbench:

•Instantiate the hardware model under test


•Generate stimulus waveforms in the form of functional
test vectors during simulation
•Generate expected waveforms in the form of reference
vector and compare with the output from RTL model
•Pass or fail indication
Sandeepani
www.sandeepani-vlsi.com

Introduction
Testbench Structure

MODEL UNDER TEST


Stimulus
Output
Vectors
Vectors

WAVE FORM
Reference Vectors COMPARE Results Files
Test vectors
File GENERATION RESULTS
Sandeepani
www.sandeepani-vlsi.com

Outline
Introduction
Vector generation
Simulation tips
summary
Sandeepani
www.sandeepani-vlsi.com

Vector generation

•Generate vectors “on-the-fly”


•Read vectors from files
•Writing vectors to a test file
Sandeepani
www.sandeepani-vlsi.com

Vector generation
Different ways of generating system waveforms

a) Use continuous loops for repetitive signals

b) Use assignments for signals with few transitions

c) Use relative or absolute time generated signals

d) Use loop constructs for repetitive signal patterns


Sandeepani
www.sandeepani-vlsi.com

Vector generation

Reading test vectors from file

Writing vectors to a text file


Sandeepani
www.sandeepani-vlsi.com

Outline
Introduction
Vector generation
Simulation tips
summary
Sandeepani
www.sandeepani-vlsi.com

Simulation tips

Simulate Corner Cases only

Use code coverage tools

Use the triple equals

Use the $display and $stop statements


Sandeepani
www.sandeepani-vlsi.com

Summary

Verification flow

Testbenches

Simulation tips
Sandeepani
www.sandeepani-vlsi.com

Verilog Testbenches
Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


* Aims
Learn coding styles and methods that are
commonly used to create a test bench
* Topics
- Simulation behavior
- Testbench organization
- Stimulus
- Clock generation
Sandeepani
Design Organization
www.sandeepani-vlsi.com

vendor
include libraries
files
simulator

design data
files compilation clk
read
write

file input: file output:


stimulus simulation stimulus
expects patterns results patterns
Sandeepani
Simulation of a Verilog Model www.sandeepani-vlsi.com

initial procedure
avec = compilation procedure
-----
-----
procedure
initialization
procedure
x
x
x
procedure

procedure
o
l x
simulation
procedure

procedure
z
Sandeepani

Testbench
Testbench Organization www.sandeepani-vlsi.com

* Simple testbench
Design - Just send data to desgin
stimulus to verify - No interaction
- Few Processes

* Sophisticated testbench
- Models environment
Testbench around designs
- Talks to design
stimulus - Evolves towards
Design
verify system model
to verify - self - checking
results
Sandeepani
“In Line“ Stimulus www.sandeepani-vlsi.com

module inline_tb;
reg (7:0) data_bus, addr; * Variables can be listed
reg reset; only when their values
// instance of DUT change
initial * Complex timing
begin relationships are easy
reset = 1’bo; to define
data_bus = 8’hoo; * A test bench can
# 5 reset = 1’b1; become very large for
#15 reset = 1’bo; complex tests
#10 data_bus = 8’h45;
#15 addr = 8’hf0;
#40 data_bus = 8’h0f;
end
endmodule
Sandeepani
Stimulus From Loops www.sandeepani-vlsi.com

* The same set of stimulus


module loop_tb; variables are modified in
reg clk; every iteration
reg [7:0] stimulus; * Easy to enter
integer i; * Compact Description
//instance of DUT * Timing relationships
//clock generation regular in nature
initial * Best for stimulus:-
begin - Regular values
for(i = 0; i<256; i = i+1) - Set time period
@(negedge clk) stimulus = i;
end
endmodule **Important
Do not forget to insert timin
control in the loop
Sandeepani
www.sandeepani-vlsi.com

Simple Delays

initial clk=0;
always clk = ~clk;

Will above code generate clk?


Sandeepani
www.sandeepani-vlsi.com

Simple Delays

always #10 clk = ~clk;

#< value> provides simple time delay


This is useful in providing timing for
- Stimulus in testbenches
- propagation delays in gate level simulation models
Sandeepani
Summary www.sandeepani-vlsi.com

* There are several Verilog constructs which are very useful in


testbench construction e.g.
* Several methods of applying stimulus have been examined:-
- In-line stimulus from an initial block
- Stimulus from loop
- Creating clocks
Sandeepani
www.sandeepani-vlsi.com

System Control
Objective:Describe some of the compiler directives ,
system tasks and system functions
available in Verilog

Topics: Text output


Simulation control
Sandeepani
www.sandeepani-vlsi.com

$display
• displays specified variables on execution
-Example:
reg[7:0]in_bus;
………
#10;
$display(“At time %d in_bus is %h”,$time,in_bus)
……
• Output:

At time 10 in_bus is 1f
Sandeepani
www.sandeepani-vlsi.com

$monitor

-displays all values in the list each time any of them changes

-$monitor($time, " A = %b B = %b CIN = %b


SUM = %B CARRY = %b", A,B,CIN,SUM,CARRY);
Sandeepani
www.sandeepani-vlsi.com

$monitor
module TB_FULL_ADD;

reg A, B, CIN;
wire SUM, CARRY;

FULL_ADD U1(A, B, CIN, SUM, CARRY);

initial
begin
$monitor($time, " A = %b B = %b CIN = %b
SUM = %B CARRY = %b", A,B,CIN,SUM,CARRY);
A = 0; B = 0; CIN = 0;
#5 A =1;B = 0; CIN = 0;
#5 A =0;B = 1; CIN = 0;
#5 A =1;B = 1; CIN = 0;
#5 A =0;B = 0; CIN = 1;
#5 A =1;B = 0; CIN = 1;
#5 A =0;B = 1; CIN = 1;
#5 A =1;B = 1; CIN = 1;
#5 $finish;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

$monitor

Monitor list for full adder test bench

0 a=0 b=0 CIN=0 SUM =0 CARRY=0


5 a=1 b=0 CIN=0 SUM =1 CARRY=0
10 a=0 b=1 CIN=0 SUM =1 CARRY=0
15 a=1 b=1 CIN=0 SUM =0 CARRY=1
20 a=0 b=0 CIN=1 SUM =1 CARRY=0
25 a=1 b=0 CIN=1 SUM =0 CARRY=1
30 a=0 b=1 CIN=1 SUM =0 CARRY=1
35 a=1 b=1 CIN=1 SUM =1 CARRY=1
$finish at simulation 40
Sandeepani
www.sandeepani-vlsi.com

$monitor

$monitoron //switches monitor on

$monitoroff //switches monitor off


Sandeepani
www.sandeepani-vlsi.com

Simulation control

simulation flow

#200 $stop; simulation suspends


at time 200

#1000 $finish; simulation terminates


at time 1000
Sandeepani
www.sandeepani-vlsi.com

Compiler directives

`include <file name>


Example:file “global.txt”

//clock and simulator constants


Parameter initial_clk=1;
Parameter period=20;
Parameter max_cycle=5;
Parameter end_time=period*max_ cycle
Sandeepani
www.sandeepani-vlsi.com

Compiler directives:Example
Usage:
Module clock_gen;
`include “global.txt”
always
begin
$monitor( $time,”\t clk=%d”,clk);
clk=initial_clk;
while ($time<end_time)
begin
#(period/2)
clk=~clk ;
end
$display($time,”simulation ends”)
$finish;
End
endmodule
Sandeepani
www.sandeepani-vlsi.com

More compiler directives

`define add16 reg[15:0] add16 can be interpreted as


reg[15:0]
`add16 input adress; interpreted as reg[15:0]
input address

`timescale 10ns/1ns 10ns is the time unit for the


block and these are rounded
off to a 1ns precision
#10 clk =~clk

10 time units =100ns


Sandeepani
www.sandeepani-vlsi.com

File outputs

32 channels available

32’h000_0001 channel descriptor for standard


output(bit 0 set)

32’h000_0800 channel descriptor for 11th channel


(bit 11 set)
Sandeepani
www.sandeepani-vlsi.com

$fopen, $fclose
$fopen
integer chan_num1,chan_num2;

declaration of channel descriptors

Chan_num1=$fopen(“file1.out”);
Chan_num2=$fopen(“file2.out”);

Chan_num1=32h0000_0002(bit 1 set)
Chan_num2=32h0000_0004(bit 2 is set)
Sandeepani
www.sandeepani-vlsi.com

Writing into file

integer chan_num1;
initial
begin
chan_num1=$fopen(“file1.out”);
$fmonitor(chan_num1,$time,”add_in=%d,add_out=%b”,
add_in,add_out);

monitor results go to file1.out


Sandeepani
www.sandeepani-vlsi.com

Writing into multiple file


integer chan_num1,chan_num2,mdesc;
initial
begin
chan_num1=$fopen(“file1.out”);
chan_num2=$fopen(“file2.out”);
mdesc= chan_num1 | chan_num2;
$fmonitor(mdesc,$time,”add_in=%d,add_out=%b”,
add_in,add_out);

monitor results are written to file1.out


and file2.out
Files can be closed using $fclose
Sandeepani
www.sandeepani-vlsi.com

$readmemb and $readmemh

module mem8x8;
reg [0:7] mem8x8 [0:7];
integer chan_num1, i;
initial
begin
$readmemb("init8x8.dat", mem8x8);
chan_num1 = $fopen ("mem8x8.out");
for (i = 0; i < 8; i = i + 1)
$fdisplay(chan_num1, "memory [%0d] = %b", i, mem8x8[i]);
$fclose(chan_num1);
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

init8X8.dat
@2 start address specified with @
11111111 consecutive data applies to consecutive
10101010 address
00000000
@6
Xxxxzzzz
1x1x1x1x
Sandeepani
www.sandeepani-vlsi.com

mem8x8.out
memory[0]=xxxxxxxx
memory[1]=xxxxxxxx address 0,1 and 5 were not
memory[2]=11111111 initialized (==x)
memory[3]=10101010
memory[4]=00000000
memory[5]=xxxxxxxx
memory[6]=xxxxzzzz
memory[7]=1x1x1x1x
Sandeepani
www.sandeepani-vlsi.com

Tasks and Functions


Sandeepani
www.sandeepani-vlsi.com

Tasks and Functions

• Subprograms
-Encapsulate portions of repeated code
-Sequential statements
-Execute in sequence like ‘software’

• Task
- Zero or more input/outputs
- Is a procedural statements

• Function
- Multiple inputs, single return value
- Can only be used as part of assignment
Sandeepani
www.sandeepani-vlsi.com

Task Declaration and call


task zero_count; (Task name) 1.Task call is a procedural statement

input [7:0]in_bus; //input arguments


output [3:0] count; //output arguments
integer i; //Local variable

begin
count=0;
#5;
for (i=0;i<8;i=i+1)
if(!in_bus[i])
count=count+1; //assign outputs
end
endtask
Sandeepani
www.sandeepani-vlsi.com

Task Declaration and call


module zerotask();

reg[7:0] a_bus;
reg clk;
reg [3:0] a_count;
reg a_zero;
//task declaration
initial
begin
clk=0;
a_bus=8'b00011111;
end
always
# 20 clk =~clk ;
Sandeepani
www.sandeepani-vlsi.com

Task Declaration and call


always @(posedge clk)
begin
zero_count (a_bus, a_count);
if ( a_count == 4'b0010)
a_zero=1'b1;
else
a_zero=1'b0;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Multiple Task calls


• Tasks can be called from more than one
location
• Tasks are not duplicated like sub-routines
- only one copy of tasks exists
• Avoid simultaneous concurrent calls
-Can cause conflict with task variables abd
input/output arguments ,Example……
Sandeepani
www.sandeepani-vlsi.com

Multiple Task calls


task neg_edge;
input [31:0] no_of_edges;
begin
repeat(no_of_edges)
@(negedge clk);
end
endtask
Sandeepani
www.sandeepani-vlsi.com

Multiple Task calls


module multiple_task_calls;
reg clk;
reg p;

initial begin
clk=1;
p=0;
end
always #50 clk=~clk;

initial
begin
neg_edge(4);
p=1;
end
Sandeepani
www.sandeepani-vlsi.com

Multiple Task calls


always @(posedge clk)
begin
neg_edge(10);
p=0;

end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Task Calls from Different Modules


module mytasks;
task neg_edge;
input [31:0] no_of_edges;
begin
repeat(no_of_edges)
@(negedge clk);
end
endtask
Task cpu_driver;
….
…….

endmodule
Sandeepani
www.sandeepani-vlsi.com

Task Calls from Different Modules


//test bench
module test_busif;
reg clk;
//clock generation
…….
//instantiation of task module
mytask m1 ( ) ;
//creating stimulus..
Initial
begin
m1.neg_clocks(6);
m1.cpu_driver(8’h00);
……
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Disabling tasks and named blocks


• Tasks or named blocks can be disabled
- Here in Ex.if CPU interrupt is detected the
cpu_driver task is forced to exit
-The CPU interrupt can then be sreviced
- Does not prevent subsequent task calls

• Named blocks are disabled in the same way

• Example follows…..
Sandeepani
www.sandeepani-vlsi.com

Disabling tasks and named


blocks
module test_busif;

always #20 clk=~clk;
…..
initial
begin: stimulus
neg_clock(5);
cpu_driver(8’h00);
cpu_driver(8’hff);
……
always @(posedge interrupt)
begin
disable cpu_driver;
service_interupt;
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Task without timing controls


• A Task normally contains timing……
• But without timing controls it executes in zero
time
• A task without timing control can be always
be expressed as a function
Example follows…..
Sandeepani
www.sandeepani-vlsi.com

Task without timing controls


function integer zero_count;
task zero_count input [7:0]in_bus;
input [7:0]in_bus;
output [3:0] count; integer i;
integer i; begin
begin zero_count=0;
count=0; for (i=0;i<8;i=i+1)
for (i=0;i<8;i=i+1) if(!in_bus[i])
if(!in_bus[i]) zero_count=zero_count+1;
count=count+1; end
end endfunction
endtask
Sandeepani
www.sandeepani-vlsi.com

Function Declaration
function integer zero_count;
input [7:0]in_bus;

integer i;
begin
zero_count=0;
for (i=0;i<8;i=i+1)
if(!in_bus[i])
zero_count=zero_count+1;
end
endfunction
Sandeepani
www.sandeepani-vlsi.com

function Call
module zfunct (a_bus,b_bus,clk,azero,b_count);
input[7:0] a_bus,b_bus;
input clk;
output azero, b_count;
reg azero;
Wire[3:0] b_count;
//function declaration
assign b_count=zero_count(b_bus);
always @(posedge clk)
if(zero_count(a_bus)==32’0)
azero=1’b1;
else
azero=1’b0
endmodule
Sandeepani
Functions
www.sandeepani-vlsi.com

•Function can enable other functions but not another task

•Functions always execute in zero simulation time

•Functions cannot include delays,timing or timing control


statements

•Functions must have at least one input argument

•Functions return a single value.they cannot have output


or inout arguments
Sandeepani
www.sandeepani-vlsi.com

Examples

1.Write a function to add two 4 bit numbers

2.Write task for the waveform specification given below:

3.Write task to count number of clock cycles

4.Write task to load time in alarm clock design


Sandeepani
www.sandeepani-vlsi.com

Verilog PLI
Sandeepani
www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary
Sandeepani
www.sandeepani-vlsi.com

Introduction
• Verilog Programming Language Interface is
one of the most powerful features of Verilog

• PLI provides both H/S designers to interface their


programs to commercial Verilog simulators
Sandeepani
www.sandeepani-vlsi.com

Introduction
Generations of PLI

IEEE 1364 Verilog

– TF / ACC routines. PLI 1.0 1990

– VPI routines PLI 2.0 1993


Sandeepani

Introduction
www.sandeepani-vlsi.com

Capabilities of Verilog PLI

• Access to programming language


libraries
• Simulation analysis……
Sandeepani
www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary
Sandeepani
www.sandeepani-vlsi.com

User Defined
PLI Interface Invokes User-
Defined System
System Task #1
User-Defined
Task System Task #2
User Design Representation
And Stimulus User-Defined
System Task #3
Pass Invokes
data User-
PLI Library
Verilog Compilation defined C
Routines
routine
User-Defined
Access C routine # 1
Internal
Internal design structures
Representation User-Defined
(Data Structures) C routine # 2

User-Defined
C routine #3
Simulation
PLI Library
Routines to do
Miscellaneous
Simulation Output
Operations
Sandeepani
www.sandeepani-vlsi.com

Objects in Verilog
• Module instances, ports, pin-to-pin paths, intermodule paths

• Top-level modules

• Primitive instances, terminals

• Nets, registers, parameters, specparams

• Integer,time and real variables

• Timing checks & Named events


Sandeepani
www.sandeepani-vlsi.com

Conceptual Internal Representation a Module


Sandeepani
www.sandeepani-vlsi.com

Example
Example: 2-to-1 Multiplexer
Sandeepani
www.sandeepani-vlsi.com
Sandeepani
www.sandeepani-vlsi.com

Internal Data Representation of 2-to-1


Multiplexer
Sandeepani
www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary
Sandeepani
www.sandeepani-vlsi.com

TF/ACC Routines
Role of Access and Utility
Routine
Sandeepani
www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary
Sandeepani
www.sandeepani-vlsi.com

General steps to create PLI applications


1. Define system task / function

2. Write C language routine

3. Register system task/function name and


associate C language routine with Verilog
simulator

4. Compile C source file which contains PLI


application & link object files into Verilog
simulator.
Sandeepani

Some useful tf routines


www.sandeepani-vlsi.com

•int tf_nump()-Returns number of arguments in system


task

•int tf_typep(n)- Returns constants that reps.data type


•viod tf_error()-Prints error massage & causes simulation
to abort
Sandeepani
www.sandeepani-vlsi.com

Some useful ACC Routines


•handle acc_handle_tfarg(n)-Returns pointer to system t/f
handle

•int acc_fetch_type(object)- Returns constant that identifies


type of argument

•char *acc_fetch_fullname(object)-Returns fulltype


property of object

•char *acc_fetch_value(object,format_str,value)-Return
value of verilog object
Sandeepani
www.sandeepani-vlsi.com

PLI application example

• $show_value
Uses PLI to access specific activity within a Verilog
simulator, by listing the name and current value of
net

• This system task $show_value illustrates


using PLI to allow a C routine to read current logic
values within a Verilog simulation
Sandeepani
www.sandeepani-vlsi.com

Step I
module test;
reg a, b, ci;
wire sum, co;
...
initial
begin
...
$show_value (sum);
end
endmodule
Sandeepani
www.sandeepani-vlsi.com

Step II
Two user-defined C routines will be associated with
$show_value:

• A C routine to verify that $show_value has the correct


type of arguments

• A C routine to print the name and logic value of the


signal
Sandeepani
www.sandeepani-vlsi.com

Writing a checktf routine for $show_value


# include “veriuser.h” /* IEEE 1364 PLI TF routine
library */
# include “acc_user.h” /* IEEE 1364 PLI ACC routine
library */
Int ShowVal_checktf( )
{
int arg_type;
handle arg_handle;

if (tf_nump( ) != 1)
tf_error (“$show_value must have 1 argument.”);
else if (tf_typep(1) == TF_NULLPARAM)
tf_error (“$show_value arg cannot be null.”);

…contd
Sandeepani
www.sandeepani-vlsi.com

Writing a checktf routine for $show_value


else {
arg_handle = acc_handle_tfarg(1);
arg_type = acc_fetch_type(arg_handle);
if (! (arg_type == accNet || arg_type == accReg) )
tf_error (“$show_value arg must be a net or
reg.”);
}
return (0);
}
Sandeepani
www.sandeepani-vlsi.com

Writing a calltf routine for $show_value

# include “veriuser.h”
# include “acc_user.h”
int ShowValCalltf( )
{
handle arg_handle;
arg_handle = acc_handle_tfarg(1);
io_printf (“Signal %s has the value %s \n”,
acc_fetch_fullname(arg_handle), acc_fetch_value(arg_handle,
“%b”, null) );

return (0);
}
Sandeepani
www.sandeepani-vlsi.com

Step III : Registering the system task/function

Interface mechanism

• The type of application which is a system task or


system function
• The system task or system function name
• The name of the calltf routine and other C
routines associated with the system task/function.
• Other information about the system task/function
required by simulator
Sandeepani
www.sandeepani-vlsi.com

The default standard veriusertfs array


s_tfcell veriusertfs [ ] =
{
{ type, user_data, checktf_app, sizetf_app, calltf_app,
mistf_app, “tf_name”, 1, 0, 0 },

{ type, user_data, checktf_app, sizetf_app, calltf_app,


misctf_app, “tf_name”, 1, 0, 0 },
...

{ 0 }, /* first field in final array cell is 0 */


};
Sandeepani
www.sandeepani-vlsi.com

S-tfcell structure definition is:


typedef struct t_tfcell {
short type; /* one of the constants: usertask,
user function, user real
function */
short data; /* data passed to use routine */
int (*checktf) ( ); /* pointer to the checktf routine */
int (*sizetf) ( ); /* pointer to the sizetf routine */
int (*calltf) ( ); /* pointer to the calltf routine */
int (*misctf) ( ); /* pointer to the misctf routine */
char *tfname; /* name of the system task/function */
int forwref; /* usually set to 1 */
char *tfveritool; /* usually ignored */
char *tferrmessage; /* usually ignored */
} s_tfcell, *p_tfcell;
Sandeepani
www.sandeepani-vlsi.com

Example veriusertfs array for registering TF/ACC


applications

/* prototypes for the PLI application routines */

extern int Showval_checktf( ), pow_sizetf( );


extern int pow_checktf( ), pow_sizetf( ), pow_calltf( ), pow_misctf( );

/* the veriusertfs array */


s_tfcell veriusertfs [ ] =
{
{ usertask, /* type of PLI routine */
0, /* user_data value */
ShowVal_checktf /* checktf routine */
Sandeepani
www.sandeepani-vlsi.com

Interfacing PLI Application


Example veriusertfs array for registering TF/ACC
applications
0, /* sizetf routine */
ShowVal_calltf, /* calltf routine */
0, /* misctf routine */
“$show_value”, /* system task/function name */
1 /* forward reference = true */
},
{ /* type of PLI routine */
/* user_data value */
/* checktf routine */
/* sizetf routine */
/* calltf routine */
Sandeepani
www.sandeepani-vlsi.com

Example veriusertfs array for registering TF/ACC


applications

/* misctf routine */
/*system task/function
name
1 /* forward reference = true
},

{0} /*** final entry must be 0


};
Sandeepani
www.sandeepani-vlsi.com

Interfacing PLI Application

Compiling and linking PLI applications

cl –c –I <simulator path>\include <name of c file>

link -dll –export:veriusertfs <name of .obj file> <simulator path>\


Win32\mtipli.lib
Sandeepani
www.sandeepani-vlsi.com

A test case for $show_value

`timescale 1ns / 1ns


module test;
reg a, b, ci, clk;
wire sum, co;
addbit i1 (a, b, ci, sum, co);
initial
begin
a = 0;
b = 0;
ci = 0;
#10 a = 1;
…contd
Sandeepani
www.sandeepani-vlsi.com

$show_value(sum);
$show_value(co);
$show_value(i1.n3);

#10 $stop;
$finish;
end
Endmodule
Sandeepani
www.sandeepani-vlsi.com

Output from running the $show_value test case


Compiling source file “show_value_test.v”
Highest level modules:
Test

Signal test.sum has the value 1


Signal test.co has the value 0
Signal test.11.n3 has the value 0
L32 “show_value_test.v”: $stop at simulation time 20
Sandeepani
www.sandeepani-vlsi.com

Thank You
Sandeepani
www.sandeepani-vlsi.com

Verilog Sample Design


Sandeepani
www.sandeepani-vlsi.com

Aims and Topics


• Aims
– To review basic Verilog concepts and code structures
– To explore a real life example
• Topics
– FIFO (First-in First-out) design specification
– Implementation
– Module declarations
– Functional code
– Testbench design and implementation
Sandeepani
FIFO Specification www.sandeepani-vlsi.com

• FIFO design is a register block at the end of a data path


• FIFO is synchronous
– Data is read and written on rising edge of clock
– Asynchronously resetable
• When write enable is high, data is written into FIFO and
stored
• When read enable is high, data is read from FIFO
– In the same order that it was written
• Both enable lines are not allowed to be active in the same
clock cycle
– If this occurs, both read and write operations are suppressed
• When the FIFO is full, set f_full high and ignore write
operations
• When the FIFO is empty, set f_empty high and ignore read
operations
• FIFO should be parameterisable for data width and FIFO
Sandeepani
www.sandeepani-vlsi.com

FIFO Implementation FIFO length


0 1 2 3 . . . . . . . n
 Use register array for
FIFO contents
 Array accessed by write FIFO
and read pointers width
Status of FIFO derived
 from pointer addresses
 FIFO full
 FIFO empty

rd_ptr wr_ptr

Read pointer FIFO write:


three

follows write assign data to


and accesses current write
data in same pointer &
order as increment
rd_ptr wr_ptr written wr_ptr
Sandeepani
www.sandeepani-vlsi.com

FIFO Model Structure


module fifo (data_in, data_out, clock, reset,
wr_en, rd_en, f_full, f_empty);
// parameter declarations
// input declarations
// output declarations
// register declarations
// internal variable declarations
// functional code
// clocked procedures
// combinational procedures

endmodule
Sandeepani
www.sandeepani-vlsi.com

Design Constants
• Parameters used to 0 1 2 3 . . . . . . LENGTH-1
define data and 0
address width 1
•Must be declared 2
before input/output .
ports .
• Values can be changed WIDTH-1
in module instantiation rd_ptr[ADDRESS_WIDTH-1 : 0]
module fifo (data_in, ……

// parameter declarations
parameter WIDTH = 8;
parameter ADDRESS_WIDTH = 5;
parameter LENGTH = (1 << ADDRESS_WIDTH );

// 16 location fifo of 16 bit data


fifo #(16,4) fifo16x16. (…
Sandeepani
www.sandeepani-vlsi.com

FIFO I/O
module fifo (data_in, data_out, clock, reset,
wr_en, rd_en, f_full, f_empty

// parameter declarations
parameter WIDTH = 8;
parameter ADDRESS_WIDTH 5;
parameter LENGTH = (1 << ADDRESS_WIDTH );

// input declarations data_in data_out


input [WIDTH-1:0] data_in;
input clock, reset; WIDTH fifo WIDTH
input wr_n, rd_en;
wr_en f_full
// output declarations
output f_full; rd_en f_empty
output f_empty;
output [WIDTH-1:0] data_out;
reset
// register declarations
// internal variable declarations clock
// functional code
endmodule
Sandeepani
Register and Internal Variable www.sandeepani-vlsi.com

Declarations
module fifo……. wr_ptr
// parameter declarations rd_ptr fiforeg
parameter WIDTH = 8;
parameter ADDRESS_WIDTH = 5; 0
parameter LENGTH = (1 << ADDRESS_WIDTH); . 1
. 2
// input and output declarations . 3
. .
// FIFO array declaration
. .
reg [WIDTH – 1:0] fiforeg [LENGTH – 1:0];
. .
// pointer declarations . .
reg [ADDRESS_WIDTH – 1:0] wr_ptr; . .
reg [ADDRESS_WIDTH – 1:0] rd_ptr; . .
. .
// integer needed with for loops LENGTH-1.
integer I;
[WIDTH –1 :0]
// functional code.
endmodule
Sandeepani
FIFO Functional Code www.sandeepani-vlsi.com

always @ (posedge clock or posedge reset)


if (reset)
begin • Clocked procedure
rd_ptr < = {ADDRESS_WIDTH {1’b0}}; describes functionally
wr_ptr < = {ADDRESS_WIDTH {1’b0}}; for:-
for (I = 0; I < LENGTH; I = I + 1) •Reset
fiforeg[1] < = {WIDTH {1;B0}}; •Pointer updates
end •Writing to FIFO array
else
begin Clocked procedure
if (rd_en && (!wr_en) && (!f_empty)) Uses non-blocking
rd_ptr < = rd_ptr + 1; assignment

if ((rd_en) && wr_en && (if_full)) read operation:


begin increment read pointer
fiforeg[wr_ptr] < = data_in;
wr_ptr < = wr_ptr + 1 ; write operation: write
end data at current pointer
end and update pointer
Sandeepani
www.sandeepani-vlsi.com

FIFO Outputs

If write pointer cather


read pointer FIFO full
Module fifo ……
/ / declarations
/ / clocked procedure
/ / full and empty pointers
assign and empty pointers
assign f_full = ( ( rd_ptr – wr_ptr) = = 5’b000001);
assign data_out= fiforeg[rd_ptr];
End module If read pointer
catchers write
• Outputs are pointer, FIFO empty
combinational
Sandeepani
www.sandeepani-vlsi.com

Testbench

• Instantiates and connects Design Under Test (DUT)


•Applys stimuli to input data and control ports
•Monitors output ports to check for correct behavior for
given stimuli
•Monitors output ports to check for correct behaviour for
given stimuli
- may be done via waveform display in simulator
Sandeepani
www.sandeepani-vlsi.com

DUT Instantiation

module fifo_tb; • fifo is the reference name of the


/ / Data type declaration module under test
•dut is the name of this instance
/ / FIFO instantiation
•FIFO parameters are reassigned in
fifo # (WIDTH, the instantiation
ADDRESS_WIDTH) dut (
•Named port connection used to link
.data_in (data_in) FIFO ports to local variables

.data_out (data_out), -Syntax


.port (variable)
.clock (clock)
•Local variables and parameters must
.reset (reset) be defined
.wr_en (rd_en)
.f_full (f_full),
.f_empty (f_empty)
Question
/ / Apply stimuls Why are there no ports for the test
endmodule fixture ?
Sandeepani
www.sandeepani-vlsi.com

Testbench Declarations
module fifo_tb
Parameter WIDTH =8;
Parameter ADDRESS_WIDTH = 5:
Parameter PERIOD = 10;

/ / input declarations
reg [WIDTH-1:0] data;
reg clock, wr_en, rd_en, reset;

/ / output declarations
wire f_full;
Wire f_empty;
wire
endmodule
Sandeepani
www.sandeepani-vlsi.com

Describing Stimulus
initial Initial clock = 1’b0;
begain Always # PERIOD clock = - clock,
data = { WIDTH {1’b0}};
{wr_en, rd_en} = 2’b00;
Any tune these signals change, display their stable
$monitor (data_out,, f_full,,,f_empty values in the standard output
reset=1’b0;
#2; read from an empty fifo to check the empty flag
reset = 1’b1;
#5;
reset =1’b0; Fill FIFO and then write to check full flag
@(negedge clock) ;
rd_en = 1’b0;
read two words to check advancing read pointer
wr_en = 1’b1;
for (i = 0, i <35; i = i + 1)
begin
@(negedge clock);
data = 255 – i; halt simulation
end
Sandeepani
www.sandeepani-vlsi.com

Describing Stimulus

rd_en = 1’b1;
wr_en = 1’b0;
repeat (2)
@(negedge clock);
$stop;
end
Sandeepani
www.sandeepani-vlsi.com

Review

1.How can you change the value of parameter ?


2. What are basic fundamental blocks of
test fixture ?
3.Using a parameter, write code that creates a
clock stimulus.

You might also like