Verilog
Verilog
Verilog
[1]
Outline
Introduction to Verilog HDL
Syntax in Verilog HDL
Gate-Level Modeling
Test-Bench
[2]
Outline
Introduction to Verilog HDL
Syntax in Verilog HDL
Gate-Level Modeling
Test-Bench
[3]
Background on HDLs
Verilog history.
1983 Gateway Design Automation released
the Verilog HDL and a simulator for it.
1989 Cadence acquired Gateway.
1990 Cadence separated the Verilog HDL from
their simulator product, Verilog-XL, releasing
the
HDL into the public domain, guarded by OVI.
1995 IEEE adopted Verilog as standard 1364.
2001 IEEE ratified 1364-2001 (Verilog-2001).
[4]
Technology No. Of Transistors
SSI 1-20
MSI 20-200
LSI 200-2,000
VLSI 2,000-20,000
ULSI >20,000
[5]
[6]
[7]
[8]
[9]
[10]
[11]
What is Verilog HDL?
Why using Hardware Description
Language?
Design abstraction: HDL ←→ layout by
human
Hardware modeling
Reduce cost and time to design hardware
Two Popular HDLs
VHDL
Verilog
[12]
What is Verilog HDL?
Key features of Verilog
Supports various levels of abstraction
Behavior level
Register transfer level
Gate level
Switch level
Simulate design functions
[13]
Different Levels of Abstraction
System
Architectural / Algorithmic Level
Implement a design algorithm in Algorithm
these data.
Transistor Level
[14]
Different Levels of Abstraction
Gate Level
System
Transistor Level
[15]
Simplified ASIC Design Flow
Designer
Level Cost
RTL RTL High Low
Simulation Editor
Post Gate
Level Place & Route
Simulation
Physical Layout
Tape Out
Low High
Chip
[16]
Advantages Of verilog
Most of us are familiar with C-like
syntax.
Simple module/port syntax is familiar
way to organize hierarchical building
blocks and manage complexity.
With care it is well suited for both
verification and synthesis.
Choice of many US design teams.
[17]
Example: 1-bit Multiplexer
sel sel in1 in2 out
to “select” output 0 0 0 0
in1 0 0 0 1 0
0 1 0 1
out
0 1 1 1
in2 1 1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
[18]
Gate Level Description
in1
a1_o
sel a1 out
in2 o1
a2 a2_o
n1
sel iv_sel
Gate Level: you see only netlist (gates and wires) in the code.
[19]
Outline
Introduction to Verilog HDL
Syntax in Verilog HDL
Gate-Level Modeling
Test-Bench
[20]
A Simple Verilog Code
declaration
syntax
port/wire
declaration
kernel hardware
gate-connection/
behavior
[21]
Another simple Verilog Example
Verilog Code Circuit
[22]
Module – Block Diagram
MODULE-1 MODULE-2
Input Port
Output Port
I/O Port
[23]
Module
Basic building block in Verilog
Module
1. Created by “declaration” (can’t be nested)
2. Used by “instantiation”
Interface is defined by ports
May contain instances of other modules
All modules run concurrently
[24]
Module Declaration
Identifiers - must not be keywords!
Verilog Keywords:
always Nand buf Force Signed Deassign
endmodule Repeat event Notif0 Vectored Highz1
medium Tri Nor Rtranif1 Casez Pmos
reg Attribute rtran Trireg Function Specparam
tranif() Endtable tri Case Output Weak()
and Negedge and Forever Small Default
endprimitive Rnmos Bufif() Notif1 Wait If
module Tri() for Scalared Cmos Posedge
release Begin not Unsigned Highz() Strength
tranif1 Endtask rtrani() Casex Parameter Weak1
assign Nmos trior Fork Specify Defparam
endspecify Rpmos bufif1 or Wand Ifnone
[25]
Ports
• First example of signals
• Scalar: e. g., E_n
• Vector: e. g., A[1:0], A[0:1], D[3:0], and D[0:3]
Range is MSB to LSB
Can refer to partial ranges - D[2:1]
• Type: defined by keywords
input
output
inout (bi-directional)
[26]
Module definition
Modules are the basic building blocks in Verilog. A module
definition starts with the keyword module ends with the
keyword endmodule
module name (port_list)
Elements in a module
port declarations
parameter declarations
— Interface: consisting of port and
parameter declarations `include directives
endmodule
[27]
module name (port_list) Module and2 (a, b ,c);
port declarations input a, b;
parameter declarations output c;
`include directives
variable declarations
assignments assign c = a & b;
low-level module instantiation
initial and always blocks
task and function
endmodule endmodule
[28]
Instances
A module provides a template from
which you can create actual objects.
When a module is invoked, Verilog
creates a unique object from the
template.
Each object has its own name,
variables, parameters and I/O
interface.
[29]
Full Adder using Half Adder
module full_add (A, B, CI, S, CO); module half_add (X, Y, S,
C);
input A, B, CI ;
output S, CO ; input X, Y ;
output S, C ;
wire N1, N2, N3;
xor (S, X, Y) ;
half_add HA1 (A, B, N1, N2), and (C, X, Y) ;
HA2 (N1, CI, S, N3);
endmodule
or P1 (CO, N3, N2);
endmodule
[30]
Module Instantiation
Adder
instance
example
Adder Adder
Adder_tree
[31]
Module Instantiation
Example
module decoder4x16_with_enable (A, E_n, D) ;
input [3:0] A ;
input E_n ;
output [15:0] D ;
wire [3:0] S;
wire [3:0] S_n;
decoder2x4_with_enable DE (A[3:2], E_n, S);
not N0 (S_n, S);
decoder2x4_with_enable D0 (A[1:0], S_n[0], D[3:0]);
decoder2x4_with_enable D1 (A[1:0], S_n[1], D[7:4]);
decoder2x4_with_enable D2 (A[1:0], S_n[2], D[11:8]);
decoder2x4_with_enable D3 (A[1:0], S_n[3], D[15:12]);
endmodule
[32]
Module Instantiation
More Examples
• Single module instantiation for five module instances
• Named_port connection
[33]
Primitives
No declaration; can only be instantiated
All output ports appear in list before any input ports
Optional drive strength, delay, name of instance
Example: and N25 (Z, A, B, C); //instance name
Example: and #10 (Z, A, B, X); // delay
(X, C, D, E); //delay
/*Usually better to provide instance name for
debugging.*/
[34]
Verilog Language Rule
Case sensitive
Identifiers
Digits 0123456789
Underscore _
Upper and lower case letters from the alphabet
Terminate statement/declaration with
semicolon “;”
Comments
Single line: // it’s a single line comment example
Multi-line: /* When the comment exeeeds single
line, multi-line comment is necesssary */
[35]
Styles
RTL/Dataflow level
continuous assignments
Behavioral level
procedural assignments
Structural/Gate level
instantiation of primitives and modules
Transistor level
[36]
Style Example - RTL/Dataflow
module fa_rtl (A, B, CI, S, CO) ;
input A, B, CI ;
output S, CO ;
endmodule
[37]
Style Example - Behavioral
module fa_bhv (A, B, CI, S, CO) ;
input A, B, CI ;
output S, CO ;
reg S, CO; // required to “hold” values between events.
always@(A or B or CI) //;
begin
S <= A ^ B ^ CI; // procedural assignment
CO <= A & B | A & CI | B & CI; // procedural assignment
end
endmodule
[38]
Style Example - Structural
module full_add (A, B, CI, S, CO) ; module half_add (X, Y, S,
C);
input A, B, CI ;
output S, CO ; input X, Y ;
output S, C ;
wire N1, N2, N3;
xor (S, X, Y) ;
half_add HA1 (A, B, N1, N2), and (C, X, Y) ;
HA2 (N1, CI, S, N3);
endmodule
or P1 (CO, N3, N2);
endmodule
[39]
Style Example - Transistor
module cmosnand(a, b, w);
input a, b;
output w; vdd
supply1 vdd;
supply0 gnd;
wire im1;
w
nmos #(2, 3, 4)(im1, gnd, b); a
nmos #(2, 3, 4)(w, im1, a);
pmos #(3, 4, 5)(w, vdd, b); im1 b
pmos #(3, 4, 5)(w, vdd, a);
endmodule
[40]
Connections
By position association
module decoder2x4_with_enable (A, En, D);
decoder2x4_with_enable DX (X[3:2], Wn,
word);
A = X[3:2], En = Wn, D = word
By name association
module decoder2x4_with_enable (A, En, D);
decoder2x4_with_enable DX (.En(Wn),
.A(X[3:2]), .D(word));
A = X[3:2], En = Wn, D = word
[41]
Connections
Empty Port Connections
module C_2_4_decoder_with_enable (A, En, D);
C_2_4_decoder_with_enable DX (X[3:2], Wn,
word);
Input En is at high-impedance state (z)
C_2_4_decoder_with_enable DX (X[3:2], Wn ,);
Output D[3:0] unused.
[42]
Port Connection
[43]
Arrays of Instances
{ , } is concatenate
Example
module add_array (A, B, CIN, S, COUT) ;
input [3:0] A, B ;
input CIN ;
output [3:0] S ;
output COUT ;
endmodule
[44]
Language Conventions
Case-sensitivity
Verilog is case-sensitive.
Some simulators are case-insensitive
Advice: - Don’t use case-sensitive feature!
Keywords are lower case
Different names must be used for different items
within the same scope
Identifier alphabet:
Upper and lower case alphabets
decimal digits
underscore
[45]
Language Conventions
Maximum of 1024 characters in identifier
First character not a digit
Statement terminated by ;
Free format within statement except for within
quotes
Strings enclosed in double quotes and must be on a
single line
Comments:
All characters after // in a line are treated as a comment
Multi-line comments begin with /* and end with */
Built-in system tasks or functions begin with $
[46]
Variables
Nets
Used for structural connectivity
Registers
Abstraction of storage (May or may not be
real physical storage)
Properties of Both
Informally called signals
May be either scalar (one bit) or vector
(multiple bits)
[47]
Data Type: Register
Register
Keyword: reg, integer, time, real
Event-driven modeling
Storage element (modeling sequential
circuit)
Assignment in “always” block (LHS of
expressions)
[48]
Data Types - Register Semantics
reg - stores a logic value
integer – stores values which are not to
be stored in hardware
Defaults to simulation computer register
length or 32 bits whichever is larger
No ranges or arrays supported
May yield excess hardware if value needs to
be stored in hardware; in such a case, use
sized reg.
time - stores time 64-bit unsigned
real - stores values as real num
realtime - stores time values as real numbers
[49]
Register Types
reg
any size, unsigned
Integer
integer a,b; // declaration
32-bit signed (2’s complement)
Time
64-bit unsigned, behaves like a 64-bit reg
$display(“At %t, value=%d”,$time,val_now)
real
real c,d; //declaration
64-bit real number
Defaults to an initial value of 0
[50]
Register Assignment
A register may be assigned value only
within:
a procedural statement
a user-defined sequential primitive
a task, or
a function.
A reg object may never be assigned value
by:
a primitive gate output or
a continuous assignment
[51]
Register Examples
reg a, b, c;
reg [15:0] counter, shift_reg;
reg [8:4] flops;
integer sum, difference;
[52]
Data Type: Net
Net
Keyword: wire, wand, wor, tri, triand,
trior, supply0, supply1
Doesn’t store value, just a connection
Input, output and inout ports are default
“wire”
[53]
Data Types - Nets - Semantics
wire - connectivity only; no logical
tri - same as wire, but indicated as 3-stated in hardware
tri0, tri1, trireg
tri0 = 0 and tri1 = 1 if not connected to any signal.
wand – cumulative and of all variables
wor – cumulative or of all variables
triand - same as wand, but 3-state
trior - same as wor but 3-state
supply0 - Global net GND
supply1 - Global Net VCC (VDD)
[54]
Net Examples
wire x;
wire x, y;
wire [15:0] data, address;
wire [1:7] control;
wire address = offset + index;
wor interrupt_1, interrupt_2;
tri [31:0] data bus, operand bus;
Value implicitly assigned by connection to
primitive or module output
[55]
wor- Example wand- Example
module wortest(); module wandtest();
wor w1, w2, w3, w4; wand w1, w2, w3, w4;
assign w1 = 0; assign w1 = 0;
assign w1 = 0; assign w1 = 0;
assign w2 = 0; assign w2 = 0;
assign w2 = 1; assign w2 = 1;
assign w3 = 1; assign w3 = 1;
assign w3 = 0; assign w3 = 0;
assign w4 = 1; assign w4 = 1;
assign w4 = 1; assign w4 = 1;
initial begin initial begin
$display(w1, w2, w3, w4); $display(w1, w2, w3, w4);
end end
endmodule 0111 endmodule 0001
[56]
An example for wire, tri0, tri1
module tritest();
wire w1, w2, w3, w4; tri0 t01, t02, t03, t04; tri1 t11, t12, t13, t14;
assign w1 = 0;
assign t01 = 0;
assign t11 = 0;
assign w2 = 1'bz;
assign t02 = 1'bz;
assign t12 = 1'bz;
assign w3 = 1;
assign t03 = 1; Results:
assign t13 = 1;
initial
begin
0z1z
#1;$display(w1, w2, w3, w4);
$display(t01, t02, t03, t04);
0010
$display(t11, t12, t13, t14); 0111
end
endmodule
[57]
Initial Value & Undeclared Nets
Initial value of a net
At tsim = 0, initial value is x.
Undeclared Nets - Default type
Not explicitly declared default to wire
Default_net type compiler directive can
specify others except for supply0 and
supply1
[58]
Strings
No explicit data type
Must be stored in reg whose size is
8*(num. of characters)
reg [255:0] buffer;
//stores 32 characters
[59]
Constants (Paramters)
Declaration of parameters
parameter A = 2’b00, B = 2’b01, C = 2’b10;
parameter regsize = 8;
reg [regsize-1:0] a; /* illustrates use of
parameter regsize and the length of a is 8 bits*/
[60]
Four-valued Logic Value
Nets and registers in Verilog codes hold
four-valued data
0 represent a logic ‘0’ or false condition
1 represent a logic ‘1’ or true condition
z
Output of an undriven tri-state driver – High-Z
value
Models case where nothing is setting a wire’s
value
[61]
Four-valued Logic Value
x
Models when the simulator can’t decide the
value – un-initialized or unknown logic value
Initial state of registers
A wire is being driven to 0 and 1 simultaneously
It is the Output of a gate with z inputs
[62]
Logic Values
Verilog signal values
0 - Logical 0 or FALSE
1 - Logical 1 or TRUE
x, X - Unknown logic value
z, Z - High impedance condition
Also may have associated signal and
charge strengths for switch level modeling
of MOS devices
7 signal strengths plus 3 charge strengths
[63]
Logic System
Four values: 0, 1, x/X, z/Z (not case
sensitive)
The logic value x denotes an unknown
(ambiguous) value
The logic value z denotes a high-impedance
value (High-Z value)
Primitives have built-in Logic
Simulators describe 4-value logic
[64]
Logic System: Example
a y
0 1 X Z b
0 0 0 0 0
a 0 1 x z
1 0 1 X X
X 0 X X X b x z x z x z x z
Z 0 X X X
y x x x
[65]
Number Representation
Format:
<size>’<base_format><number>
<size> - decimal specification of bits count
Default: unsized and machine-dependent but at
least 32 bits
<base_format> - ' followed by arithmetic
base of number
d or D – decimal (default if no base format given)
h or H – hexadecimal
o or O – octal
b or B – binary
[66]
Number Representation
<number> - value given in base of
base format
_ can be used for reading clarity
x and z are automatically extended
If first character of sized, binary number
is 0, 1, the value is 0-filled up to size. If
x or z, value is extended using x or z,
respectively.
[67]
[68]
Number Representation
Examples:
6’b010_111 gives 010111
8’b0110 gives 00000110
4’bx01 gives xx01
16’H3AB gives 0000001110101011
24 gives 0…0011000
5’O36 gives 11110
16’Hx gives xxxxxxxxxxxxxxxx
8’hz gives zzzzzzzz
[69]
Number Representation
659 // un sized decimal // underline usage
‘h 837ff // un sized hexadecimal 27_195_000
‘o7460 // un sized octal 16’b0001_0101_0001_1111
4af // illegal syntax 32’h12ab_f001
4’b1001 // 4-bit binary
// X and Z is sign-extended
5’D 3 // 5-bit decimal
3’b01x // 3-bit number with
reg [11:0] a;
unknown LSB
initial
12’hx // 12-bit unknown
begin
8’d -6 // illegal syntax a = ‘hx; // yields xxx
-8’d 6 // phrase as - (8’d6) a = ‘h3x; // yields 03x
a = ‘h0x; // yields 00x
end
[70]
Net Concatenation
Module B
Module A
Module C
3‘o7
Representations Meanings
{b[3:0],c[2:0]} {b[3] ,b[2] ,b[1] ,b[0], c[2] ,c[1] ,c[0]}
{a,b[3:0],w,3’b101} {a,b[3] ,b[2] ,b[1] ,b[0],w,1’b1,1’b0,1’b1}
{4{w}} {w,w,w,w}
{b,{3{a,b}}} {b,a,b,a,b,a,b}
[71]
Operators
Arithmetic Operators +, -, *, /, %
Relational Operators <, <=, >, >=
Equality Operators ==, !=, ===, !==
Logical Operators !, &&, ||
Bit-wise Operators ~, &, |, ^, ~^
Unary Reduction &, ~&, |, ~|, ^, ~^
Shift Operators >>, <<
Conditional Operators ?:
Concatenations {}
== tests logical equality (tests for 1 and 0, all other will result in x)
=== tests 4-state logical equality (tests for 1, 0, z and x)
[72]
Operator Examples
[73]
Expression Bit Widths
Unsized constant number- same as
integer (usually 32 bits)
Sized constant number - as specified
x op y where op is +, -, *, /, %, &, |,
^, ^~:
Arithmetic binary and bitwise
Bit width = max (width(x), width(y))
[74]
Expression Bit Widths
(continued)
op x where op is +, -
Arithmetic unary
Bit width = width(x)
op x where op is ~
Bitwise negation
Bit width = width(x)
[75]
Expression Bit Widths
(continued)
x op y where op is ==, !==, ===,
!===, &&, ||, >, >=, <, <= or x op y
where op is ~&, ~|, ~^
Logical, relational and reduction
Bit width = 1
x op y where op is
<<(Left Sift), >>(Right Shift)
Shift
Bit width = width(x)
[76]
Expression Bit Widths
(continued)
output=x ? y : z
Conditional
Bit width = max(width(y), width(z))
module test;
reg r = 1'b1;
wire w;
assign w = r ? 1'b1 : 1'b0;
initial begin
#1;
$display("OUTPUT: %s", r ? "HI THERE" : "POTATO");
$display("Value of w: %b", w);
$display("%h", (10 > 5) ? 16'habcd : 16'h1234);
end
endmodule // check the code at https://www.jdoodle.com/execute-verilog-online/
[77]
Expression Bit Widths
(continued)
{x, …, y}
Concatenation
Bit width = width(x) + … + width(y)
{x{y, …, z}}
Replication
Bit width = x * (width(y) + … + width(z))
[78]
Expressions with Operands
Containing x or z
Arithmetic
If any bit is x or z, result is all x’s.
Divide by 0 produces all x’s.
Relational
If any bit is x or z, result is x.
Logical
== and != If any bit is x or z, result is x.
=== and !== All bits including x and z
values must match for equality
[79]
Expressions with Operands
Containing x or z
Bitwise
Defined by tables for 0, 1, x, z operands.
Reduction
Defined by tables as for bitwise operators.
Shifts
z changed to x. Vacated positions zero filled.
Conditional
If conditional expression is ambiguous (e.g.,
x or z), both expressions are evaluated and
bitwise combined as follows: f(1,1) = 1,
f(0,0) = 0, otherwise x.
[80]
Simulation Time Scales
Compiler Directive
`timescale <time_unit> /<time_precision>
time_unit - the time multiplier for time
values
time_precision - minimum step size during
simulation - determines rounding of
numerical values
Allowed unit/precision values:
{1| 10 | 100, s | ms | us | ns | ps}
[81]
Simulation Time Scales
(continued)
Example:
`timescale 10ps / 1ps
nor #3.57 (z, x1, x2);
nor delay used = 3.57 x 10 ps = 35.7 ps => 36 ps
Different timescales can be used for
different sequences of modules
The smallest time precision determines the
precision of the simulation.
[82]
Operator Precedence
[83]
Example
assign A1 = (3+2) %2; // A1 = 1
assign A2 = 4 >> 1; assign A4 = 1 <<2; // A2 = 2 A4 = 4
assign Ax = (1= =1'bx); //Ax=x
assign Bx = (1'bx!=1'bz); //Bx=x
//D0=False
assign D0 = (1= =0);
//D1=True
assign D1 = (1= =1); //E0=False
assign E0 = (1= = =1'bx); //E1=True
assign E1 = (4'b01xz = = = 4'b01xz);; //F1= True
assign F1 = (4'bxxxx = = = 4'bxxxx); //if (a) then x = b else
x=c
assign x = a ? b : c
[84]
Memory
Memories are modeled in verilog as an array of registers
Each element of the array is known as word
Each word can have one or multiple bits
A particular word in memory can be obtained by using the
address as a memory array subscript
reg mem1bit [0 : 1023];
//memory mem1bit with 1K 1-Bit words
reg [7:0] mem1byte [0:1023];
//memory mem1byte with 1K 8-bit words
mem1byte[511]; //access the 1 byte word
from address 511
[85]
Behavioral Constructs
Concurrent communicating behaviors =>
processes same as behaviors
Two constructs
initial - one-time sequential activity flow -
not synthesizable but good for test benches
Always - cyclic (repetitive) sequential
activity flow
Use procedural statements that assign
only register variables
[87]
Behavioral Constructs
(continued)
Continuous assignments and primitives
assign outputs whenever there are events
on the inputs
Behaviors assign values when an
assignment statement in the activity flow
executes.
[88]
Behavioral Constructs
(continued)
Body may consist of a single statement or a
block statement
A block statement begins with begin and
ends with end
Statements within a block statement
execute sequentially
Behaviors are an elaborate form of
continuous assignments or primitives but
operate on registers (with one exception)
rather than nets.
[89]
Behavioral Constructs -
Example
module test;
integer one, two, three, four, five;
initial begin
one = 1;
two = one + 1;
three = two + 1;
four = three + 1;
five = four + 1;
$display("Value of five: %d", five);
end
endmodule
Value of five: 5
[90]
Behavioral Constructs -
Example
Value of F1: 1
Always: Value of F2: 0
module test; Value of F1: 1
reg F1, F2; Value of F2: 0
always Value of F1: 1
begin Value of F2: 0
F1 = 0; Value of F1: 1
F2 = 0; Value of F2: 0
# 2 F1 <= 1; Value of F1: 1
# 4 F2 <= 0; Value of F2: 0
# 2 F1 <= 1; Value of F1: 1
Value of F2: 0
# 4;
Value of F1: 1
$display("Value of F1: %d", F1); Value of F2: 0
$display("Value of F2: %d", F2); Value of F1: 1
end Value of F2: 0
Value of F1: 1
endmodule Value of F2: 0
[91]
Procedural Assignments
Types
= blocking assignment
assign = continuous assignment
<= non-blocking assignment
Assignments (with one exception of data
type net) to:
reg
integer
real
realtime
time
[92]
Clock division and use in DFF
module clk_div(
input clk_in,
else always@(posedge
begin
input rst,
if (count<100000000)
clk_out)
input d,
output clk_out, begin begin
output q count<=count+1;
); end
if(rst==0)
reg [27:0] count, clk_out,q;
always @(posedge clk_in or
else q<=d;
begin
posedge rst)
begin count<=0;
else
if(rst)
begin
clk_out<=~clk_out; q<=q;
end
count<=0;
end
end
clk_out<=0;
end end endmodule
[93]
Test bench
module clkdiv_tb(); initial begin
rst=1'b1;
reg clk_in, rst, d; #10;
wire clk_out, q; rst=0;
while(1)
clk_div c1(clk_in, rst, d,
begin
clk_out, q); clk_in=0;
initial begin #2.5;
d=1'b1; clk_in=1;
#2.5;
#1000000000; end
d=1'b0; end
endmodule
end
[94]
Procedural Assignments - Some
Rules
Register variable can be referenced anywhere in
module
Register variable can be assigned only with
procedural statement, task or function
Register variable cannot be input or inout
Net variable can be referenced anywhere in module
Net variable may not be assigned within behavior,
task or function. Exception: force … release
Net variable within a module must be driven by
primitive, continuous assignment, force … release
or module port
[95]
Procedural Timing, Controls &
Synchronization
Mechanisms
Delay Control Operator (#)
Event Control Operator (@)*
Event or
Named Events – not used much
wait construct
[96]
Procedural Timing, Controls &
Synchronization
Delay Control Operator (#)
Precedes assignment statement - postpones
execution of statement
For blocking assignment (=), delays all
statements that follow it
Blocking assignment statement must execute
before subsequent statements can execute.
Example: always @(posedge clk),
#10 Q = D;
[97]
Procedural Timing, Controls &
Synchronization
Event Control Operator (@)*
Synchronizes the activity flow of a behavior to
an event (change) in a register or net variable or
expression
Example 1: @ (start) RegA = Data;
Example 2: @(toggle) begin
…
@ (posedge clk) Q = D;
…
end
*Ignored by FPGA express unless a
synchronous trigger that infers a register
[98]
Procedural Timing, Controls &
Synchronization
Event or - allows formation of event
expression
Example:
always @ (X1 or X2 or X3)
assign Y = X1 & X2 | ~ X3;
All RHS variables in sensitivity list and no
unspecified conditional results =>
combinational logic
[99]
Procedural Timing, Controls &
Synchronization
Meaning of posedge: 0 -> 1, 0 -> x,
x -> 1
Special Example:
always @ (set or reset or posedge clk)
begin
if (reset == 1) Q = 0;
else if (set == 1) Q = 1;
else if (clk == 1) Q = data;
end
// Does this work correctly? Why or why not?
[100]
Procedural Timing, Controls &
Synchronization (FIO)
wait Construct
Suspends activity in behavior until expression
following wait is TRUE
Example:
always
begin
a = b;
c = d;
wait (advance);
end
[101]
Blocking Assignments
Identified by =
Sequence of blocking assignments executes
sequentially
Example:
always @(posedge clk)
begin
b = 0; c = 0;
b = a + a;
c = b + a;
d = c + a;
end
[102]
Non-Blocking Assignments
Identified by <=
Sequence of non-blocking assignments executes
concurrently
Example 1:
always @(posedge clk)
begin /*Calculates b = 2a, c = b + a,
b <= 0; c <= 0; d <= c + a. All values used
on RHS are those at
b <= a + a; posedge clock. Note that
c <= b + a; there are two assignments
to b and c. Only the last one
d <= c + a; is effective. */
end
[103]
Blocking Assignments - Inter-
Assignment Delay
Delays evaluation of RHS and assignment to
LHS
Example:
always @(posedge clk)
begin
b = 0; c = 0;
b = a + a; // uses a at posedge clock
#5 c = b + a; // uses a at posedge clock + 5
d = c + a; // uses a at posedge clock + 5
end /*c = 2a(at posedge clock)+ a(at posedge clock + 5)
d = 2a(at posedge clock) + 2 a(at posedge clock + 5)*/
[104]
Blocking Assignment - Intra-
Assignment Delay
Delays assignment to LHS and subsequent
statements, not evaluation of RHS
Example:
always @(posedge clk)
begin
b = 0; c = 0;
b = a + a; // uses a at posedge clock
c = #5 b + a; // uses a at posedge clock
d = c + a; // uses a at posedge clock + 5
end /* c = 3a(at posedge clock)
d = 3a (at posedge clock)+ a (at posedge clock + 5)*/
[105]
Non-Blocking Assignment -
Inter-Assignment Delay
Delays evaluation of RHS and assignment to LHS
Delays subsequent statements
Example:
always @(posedge clk)
begin
b <= 0; c <= 0;
b <= a + a; // uses a at posedge clock
#5 c <= b + a; // uses b and a at posedge clock + 5
d <= c + a; // uses a at posedge clock + 5
end
/*c = b(at posedge clock + 5) + a(at posedge clock + 5)
d = c(at posedge clock + 5) + a (at posedge clock +5) */
[106]
Non-Blocking Assignment -
Intra-Assignment Delay
Delays only assignment to LHS
Example:
always @(posedge clk)
begin
b <= 0; c <= 0;
b <= a + a; // uses a at posedge clock
c <= #5 b + a; // uses a and b at posedge clock
d <= c + a; // uses a and c at posedge clock
end /* Calculates *c(posedge clock + 5) = b(at posedge
clock)+ a(at posedge clock); d(posedge clock) =
c(at posedge clock) + a (at posedge clock) */
[107]
Activity Control
Overview
Constructs for Activity Control
• Conditional operator
• case statement
• if … else statement
• Loops : repeat, for, while, forever
• disable statement
• fork … join statement
Tasks and Functions
[108]
Conditional Operator
?…:
Same as for use in continuous
assignment statement for net types
except applied to register types
Example:
always@(posedge clock)
Q <= S ? A : B //combined DFF and 2-to-1
MUX
[109]
case Statement
Requires complete bitwise match over all four values so
expression and case item expression must have same bit
length
Example: always@(state, x) begin
reg[1:0] state;
case (state)
2’b00: next_state <= s1;
2’b01: next_state <= s2;
2’b10: if x next_state <= s0;
else next_state <= s1;
end
default next_state = 1’bx;
endcase
end
[110]
casex Statement
Requires bitwise match over all but
positions containing x or z; executes first
match encountered if multiple matches.
Example:
always@(code) begin
casex (code)
2’b0x: control <= 8’b00100110; //same for 2’b0z
2’b10: control <= 8’b11000010;
2’b11: control <= 8’b00111101;
default control <= 8b’xxxxxxxx;
endcase
end
[111]
casez Statement
Requires bitwise match over all but
positions containing z or ? (? is explicit
don’t care); executes first match
encountered if multiple matches.
Example:
reg [1:0] code;
always@(code) begin
casez (code)
2’b0z: control <= 8’b00100110;
2’b1?: control <= 8’b11000010;
default control <= 8b’xxxxxxxx;
endcase
end
[112]
Conditional (if … else)
Statement Example
always@(a or b or c) begin
if (a == b)
begin
q <= data;
stop <= 1’b1;
end
else if (a > b)
q <= a;
else
q <= b;
end
end
end
[113]
Conditional (if … else)
Statement (continued)
Must be careful to define outcome for all possible
conditions – failure to do so can cause unintentional
inference of latches!
else is paired with nearest if when ambiguous -
use begin and end in nesting to clarify.
Nested if … else will generate a “serial” or priority
like circuit in synthesis which may have a very
long delay - better to use case statements to get
“parallel” circuit.
[114]
for Loop Example
Example:
initial
integer r, i;
begin
r = 0;
for (i = 1; i <= 7; i = i + 2)
begin
r[i] = 1;
end
end
[115]
while Loop Example
initial
begin
r = 0;
i = 0;
while (i <= 7)
begin
r[i] = 1;
i = i + 2;
end
end
[116]
forever Loop Example
initial
begin
clk = 0;
forever
begin
#50 clk = 1;
#50 clk = 0;
end
end
Usually used in testbenches rather
than for synthesized logic.
[117]
Tasks
Declared within a module
Referenced only by a behavior within the
module
Parameters passed to task as inputs and
inouts and from task as outputs or inouts
Local variables can be declared
Recursion not supported although nesting
permitted (nested copies of variables use
same storage)
[118]
Task Example
task leading_1;
input [7:0] data_word;
output [2:0] position;
reg [7:0] temp;
reg [2:0] position;
begin
temp = data_word;
position = 3'b111;
while (!temp[7])
@(posedge clock)
begin
temp = temp << 1;
position = position - 1;
end
end
endtask // Code is not synthesizable
[119]
Functions
Implement combinational behavior
No timing controls or tasks which implies no
while
May call other functions with no recursion
Reference in an expression, e.g. RHS
No output or inout allowed
Implicit register having name and range of
function
[120]
Function Example
function [2:0] leading_1;
input [7:0] data_word;
reg [7:0] temp;
begin
temp = data_word;
leading_1 = 3'b111;
while (!temp[7])
begin
temp = temp << 1;
leading_1 = leading_1 - 1;
end
end
endfunction
Is the above code synthesizable? No
[121]
Compiler Directives
Useful for controlling what is synthesized and the
resulting logic
Warning: Not recognized by other compilers –
therefore reduce code portability
Examples:
// synopsys translate_off
Code here describes something that is not to be
synthesized such at a simulation testbench -
can contain non-synthesizable constructs such
as delays)
// synopsys translate_on
[122]
Compiler Directives (Continued)
Examples:
// synopsys parallel_case
Forces generation of multiplexer-like structure
instead of priority structure when included after
case declaration
// synopsys full_case
Indicates that all cases have been considered
when included in case declaration; when used,
no default statement needed and latches will
not be inferred can be used in combination with
parallel case:
case (state) // synopsys parallel_case full_case
[123]
Multiplexer_1
Verilog code for Multiplexer implementation using assign
module mux1( select, d, q );
input [1:0] select;
input [3:0] d;
output q;
wire q;
wire[1:0] select;
wire[3:0] d;
assign q = d[select];
endmodule
[124]
Multiplexer_2
Verilog code for Multiplexer implementation using
always block.
module mux2( select, d, q );
input[1:0] select;
input[3:0] d;
output q;
reg q;
wire[1:0] select;
wire[3:0] d;
always @(d or select)
q = d[select];
endmodule
[125]
Multiplexer_3
module mux4_1 (out, in0, in1, in2, in3, sel) ;
output out ;
input in0,in1,in2,in3 ;
input [1:0] sel ;
assign out = (sel == 2'b00) ? in0 :
(sel == 2'b01) ? in1 :
(sel == 2'b10) ? in2 :
(sel == 2'b11) ? in3 :
1'bx ;
endmodule
[126]
Flip-Flops
always@(posedge clk)
begin
a<=b;
a<=b&c;
end
C B D
B
Q A
clk CLK
[127]
D Flip-Flop with Asynchronous
Reset
always@(posedge clk or
negedge clr) rst
begin
clr
if (!clr) a<=0; B D
else a<=b;
end Q A
clk CLK
[128]
D Flip-flop with Synchronous
reset and Enable
always@(posedge clk)
begin
if (rst) a<=0; rst D
else if (enable) a<=b; B
EN
end enable Q A
clk CLK
[129]
Shift Registers
reg[3:0] Q;
always@(posedge clk or
posedge rset )
begin
if (rset) Q<=0;
else begin D Q D Q D Q D Q
Q[0]<=Q[3]; clk
end
[130]
Counters
module cnt(rst, clk, en, count);
always@(posedge clk or
negedge rst)
begin
if (rst) count<=0; count
else if (en)
count<=count+1;
end
endmodule
[131]
Finite State Machines
[132]
Standard Form for a Verilog
FSM
// state flip-flops // REGISTER DEFINITION
reg [2:0] state, nxt_st; always@(posedge clk)
// state definitions begin
parameter
reset=0,S1=1,S2=2,S3=3,..
state<=next_state;
end
// NEXT STATE
CALCULATIONS // OUTPUT CALCULATIONS
always@(state or inputs or output= f(state, inputs)
...)
begin
…
next_state= … …
end
[133]
0111 Sequence Detector
(Moore Machine)
1
1 S0
0
z=0
S4 0 S1 0
z=1 z=0
0
1 0 1
S3 S2
z=0 z=0
[134]
Example
module myFSM (clk, reset, x, z); case (state)
input clk, x, reset; output z; S0: if(x) nxt_st=S0;
// state flip-flops else nxt_st=S1;
reg [2:0] state, nxt_st; S1: if(x) nxt_st=S2;
// state definition else nxt_st=S1;
parameter S2: if(x) nxt_st=S3;
S0=0,S1=1,S2=2,S3=3,S4=4; else nxt_st=S1;
// REGISTER DEFINITION S3: if(x) nxt_st=S4;
always @(posedge clk) else nxt_st=S1;
begin S4: if(x) nxt_st=S0;
state<=nxt_st; else nxt_st=S4;
end default: nxt_st = S0;
// NEXT STATE CALCULATIONS Endcase
always @(state or x) end
begin // OUTPUTCALCULATIONS
if(reset) assign z = (state==S4);
state = S0; endmodule
else state = nxt_st;
[135]
Outline
Introduction to Verilog HDL
Syntax in Verilog HDL
Gate-Level Modeling
Test-Bench
[136]
Gate Level Modeling
Steps
Develop the Boolean function of output
Draw the circuit with logic gates/primitives
Connect gates/primitives with net (usually
wire)
HDL: Hardware Description Language
Figure out architecture first, then write code.
[137]
Primitives
Primitives are modules ready to be
instanced
Smallest modeling block for simulator
Verilog build-in primitive gate
and, or, xor, nand, nor, xnor
prim_name #delay inst_name( out0, in0, in1,.... );
not, buf
prim_name #delay inst_name( out0, out1, ..., in0);
User defined primitive (UDP)
building block defined by designer
[138]
Case Study: Full Adder
Ci A B Co S
A B 0 0 0 0 0
0 0 1 0 1
0 1 0 0 1
Full
Co Ci 0 1 1 1 0
Adder
1 0 0 0 1
1 0 1 1 0
S
1 1 0 1 0
1 1 1 1 1
[139]
Case Study: Full Adder
Co = AB + BCi + CiA
A
B
B
Co
Ci
Ci
A
[140]
Case Study: Full Adder
sum = a b ci
a
b
c sum
a
b sum
c
[141]
Case Study: Full Adder
Full Adder Connection
Instance ins_c full adder
sum
connection
a
b sum
c
[142]
Rule #1
If the procedure has several
paths, every path must evaluate
Method1:
all outputs
Set all outputs to some value at the start of the procedure.
Later on different values can overwrite those values.
always @(...
begin
x=0;y=0;z=0;
if (a) x=2; elseif (b) y=3; else z=4;
End
Method2:
Be sure every branch of every if and case generate every output
always @(...
begin
if (a) begin x=2; y=0; z=0; end
elseif (b) begin x=0; y=3; z=0; end
else begin x=0; y=0; z=4; end
end
[143]
Rule #2
All inputs used in the procedure
must appear in the trigger list
Right-hand side variables:
Except variables both calculated and used in the procedure.
always @(a or b or c or x or y)
begin
x=a; y=b; z=c;
w=x+y;
end
Branch controlling variables:
Be sure every branch of every if and case generate every output
always @(a or b)
begin
if (a) begin x=2; y=0; z=0; end
elseif (b) begin x=0; y=3; z=0; end
else begin x=0; y=0; z=4; end
end
[144]
Rule #3
All possible inputs used control
statements must be covered
End all case statements with the default case
whether you need it or not.
case(state)
...
default: next_state = reset;
endcase
Do not forget the self loops in your state graph
if(a|b&c) next_state=S1;
elseif(c&d) next_state=S2;
else next_state=reset;
[145]
Outline
Introduction to Verilog HDL
Syntax in Verilog HDL
Gate-Level Modeling
Test-Bench
[146]
Test Methodology
Systematically verify the functionality of
a model.
Procedure of simulation
Detect syntax varifications in source code
Simulate behavior
Monitor results
[147]
Test Methodology
Stimulus
Hardware Design
Testbench
(Design Under Test)
Response
[148]
Test bench Approach
Use Verilog module to produce testing
environment including stimulus
generation and/or response
monitoring
Stimulus Response
UUT
Module
[149]
Verilog Simulator
[150]
Testbench for Full Adder
module t_full_add();
reg a, b, cin; // for stimulus waveforms
wire sum, c_out;
full_add M1 (sum, c_out, a, b, cin); //DUT
initial #200 $finish; // Stopwatch
initial begin // Stimulus patterns
While(1)
begin
a = 0; b = 0; cin = 0; // Execute in sequence
#10 a = 0; b = 1; cin = 0;
#10 a = 1; b = 0; cin = 0;
#10 a = 1; b = 1; cin = 0;
#10 a = 0; b = 0; cin = 1;
#10 a = 0; b = 1; cin = 1;
#10 a = 1; b = 0; cin = 1;
#10 a = 1; b = 1; cin = 1;
end
end
endmodule
[151]
Summary
Design module / DUT
Divide-and-Conquer
Partition the whole design into several parts
Architecture figure of each sub-module
Make architecture figures before you write Verilog
codes
Create hardware design in gate-level or RT-level
Connection of sub-modules
Test-bench
Feed input data and compare output values at right
timing slots
Usually describe in behavioral level
Not real hardware, just like software programming
(e.g. C/C++)
[152]
Note
Verilog is a platform
Support hardware design (design module)
Also support C/C++ like coding (test bench)
How to write verilog well?
Know basic concepts and syntax
Get a good reference codes
(a person or some code files)
Form a good coding style
Hardware
Combinational circuits
Sequential circuits
[153]
Let’s Fight!
Which is “better” Verilog or VHDL?
Both are adequate for our purposes…
What you use in industry may be dictated by
company preference or government
requirement.
VHDL may be more powerful but very rigid.
Very Hard and Difficult to Learn?
For beginners, do you want to spend your
time in logic design, or fighting the language?
Verilog may be easier, but you can hang
yourself if you are not careful...
[154]
[155]