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

03-Verilog Modules and Ports-Merged

Uploaded by

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

03-Verilog Modules and Ports-Merged

Uploaded by

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

Digital System Design

Verilog® HDL
Modules and Ports
Outline
•Components of a Verilog Module

•Defining and Connecting Ports


Modules
•Basic building block in Verilog
•Hierarchical design (top-down vs. bottom-up)
•Multiple modules in a single file
•Order of definition not important
Modules
Module Example: SR-Latch
SR-Latch Example
module SR_latch(Q, Qbar, Sbar, Rbar);
output Q, Qbar;
input Sbar, Rbar;

nand n1(Q, Sbar, Qbar);

nand n2(Qbar, Rbar, Q);

endmodule
Ports
•Interface of the module to the environment
• Internals of the module are not visible to the
environment
• Internals can be changed as long as the interface
(ports) is not changed
Port Declaration
• All ports in the list of ports must be declared in the
module
• Verilog keyword Type (mode) of port

input Input port


output Output port
inout Bidirectional port
Port Declaration
• All ports in the list of ports must be declared in the module

• Example:
module fulladd4(sum, c_out, a, b, c_in);
output [3:0] sum;
output c_out;
input [3:0] a, b;
input c_in;
...
endmodule
Port Declaration
•Note: all ports are wire by default
• No need to declare it again as wire
• If expected to be reg, the port needs to be declared again
Example: the q port in DFF module

module DFF(q, d, clk, reset);


output q;
reg q; // Output port q holds value => reg
input d, clk, reset;
...
endmodule
Module Instantiation
• Recall the Ripple-carry counter and TFF

module TFF(q, clk, reset);


output q;
input clk, reset;
...
endmodule

module ripple_carry_counter(q, clk, reset);


output [3:0] q;
input clk, reset;

//4 instances of the module TFF are created.


TFF tff0(q[0],clk, reset);
TFF tff1(q[1],q[0], reset);
TFF tff2(q[2],q[1], reset);
TFF tff3(q[3],q[2], reset);
endmodule
module TFF(q, clk, reset); Module Instantiation
output q;
input clk, reset;
...
endmodule

module ripple_carry_counter(q, clk, reset);


output [3:0] q;
input clk, reset;

//4 instances of the module TFF are created.


TFF tff0(q[0],clk, reset);
TFF tff1(q[1],q[0], reset);
TFF tff2(q[2],q[1], reset);
TFF tff3(q[3],q[2], reset);
endmodule
Module Instantiation
• General syntax

<module_name> <instance_name>(port connection list);

• Example:
// assuming module ripple_carry_counter(q, clk, reset);

ripple_carry_counter cntr1(wire_vec1, wire2, wire3);


Port Connection Rules
•Two parts of a port: internal and external to the
module
Port Connection Rules
• Width matching
• Legal to connect items of different sizes
• A warning may be issued by Verilog simulator

• Unconnected ports
• Allowed in Verilog
• Example:
// module fulladd4(sum, c_out, a, b, c_in);
fulladd4 fa0(SUM, , A, B, C_IN); // output port c_out is
unconnected
• Example of illegal port connection Port Connection
Rules
module Top;
// Declare connection variables
reg [3:0] A, B;
reg C_IN;
reg [3:0] SUM;
wire C_OUT;

// Instantiate fulladd4, call it fa0


fulladd4 fa0(SUM, C_OUT, A, B, C_IN);
// Illegal connection because output port sum is
connected to reg

...

endmodule // Top
Connecting Ports to External Signals
• Two ways for port mapping
• Connecting by ordered list
• More intuitive for beginners
• Mostly used when having few ports

• Connecting by name
• Used when having more ports
• Gives independence from order of ports
• The order of ports in the port list of a module can be changed without
changing the instantiations
Connecting by Ordered List
module fulladd4(sum, c_out, a, b, c_in);
...
endmodule

module Top;
// Declare connection variables
reg [3:0] A, B;
reg C_IN;
wire [3:0] SUM;
wire C_OUT;

// Signals are connected to ports in order (by position)


fulladd4 fa_ordered(SUM, C_OUT, A, B, C_IN);
...
endmodule
Connecting Ports by Name
module fulladd4(sum, c_out, a, b, c_in);
...
endmodule

module Top;
// Declare connection variables
reg [3:0] A, B;
reg C_IN;
wire [3:0] SUM;
wire C_OUT;

// Signals are connected to ports by name


fulladd4 fa_byname(.c_out(C_OUT), .sum(SUM), .b(B), .a(A));
...
endmodule
Hierarchical Names
•Hierarchical design
• An identifier for every signal, variable, or module
instance
• The same identifier can be used in different levels of the
hierarchy
• Hierarchical name referencing
• Unique name to every identifier in the hierarchy
• Syntax:

<top-module-name>.<instance-name>.<identifier>
Hierarchical Names

Stimulus

m1
S
set q
Q

qbar
reset R Qbar
Primitive Gates in Verilog
Primitive Gates in Verilog
•Syntax
• Similar to module instantiations

•Examples
wire out, in1, in2, in3;

and a1(out, in1, in2);


nand na1(out, in1, in2);
nand na1_3inp(out, in1, in2, in3);
Gate Level Modeling
• Most digital design is now done at gate level or
higher levels of abstraction.
• At gate level, the circuit is described in terms of gates
(e.g., and, nand).
• Hardware design at this level is intuitive for a user
with a basic knowledge of digital logic design because
it is possible to see a one-to-one correspondence
between the logic circuit diagram and the Verilog
description.
• Verilog supports basic logic gates as predefined
primitives.
Gate Level Modeling
• All logic circuits can be designed by using basic
gates.
• There are two classes of basic gates: and/or gates
and buf/not gates.
• And/or gates have one scalar output and multiple
scalar inputs.
• The first terminal in the list of gate terminals is an
output and the other terminals are inputs.
• The output of a gate is evaluated as soon as one of
the inputs changes.
• The and/or gates available in Verilog are: and, nand,
or, nor, xor, xnor.
AND/OR Gate
Buf/Not Gates
• Buf/not gates have one scalar input and one or
more scalar outputs.
• The last terminal in the port list is connected to the
input.
• Other terminals are connected to the outputs.
Buf/not gate with additional control signal
• These gates are used when signal is to be driven
only when control signal is asserted.
• Such a situation is applicable when multiple
drivers drive the signal.
• These drivers are designed to drive the signal
mutually exclusive control signals
Array of Instances
• Verilog allows array of primitive instances to be
defined
Gate-level Half Adder
Gate Level Full Adder
Full Adder using Half Adder
Gate-level 4:1 Multiplexer
Ripple Carry Full Adder
4-Bit Adder
// Define a 4-bit full adder
module fulladd4(sum, c_out, a, b, c_in);

// I/O port declarations


output [3:0] sum;
output c_out;
input[3:0] a, b;
input c_in;

// Internal nets
wire c1, c2, c3;

// Instantiate four 1-bit full adders.


fulladd fa0(sum[0], c1, a[0], b[0], c_in);
fulladd fa1(sum[1], c2, a[1], b[1], c1);
fulladd fa2(sum[2], c3, a[2], b[2], c2);
fulladd fa3(sum[3], c_out, a[3], b[3], c3);

endmodule
Gate Delays
• Rise Delay

• Fall Delay
Gate Delays

• Turn-off Delay:

• When gate output is transit to High Impedance


(z) from any other value

• Note: if the value changes to x, the minimum of


the three delays is considered.
Types of Delay Specification
min/typ/max Values
• Verilog provides an additional level of control for
rise, fall and turn-off delay using three values:
min, typ, max

• These values can be chosen at Verilog run time.

• Specifying different delays allow designer to


experiment with circuit behaviour without
modifying design
Min, Max and Typical Delay Values
Delay Example
Waveforms for Delay Simulation
Verilog® HDL Dataflow
Modeling
Outline

•The assign statement

•Expressions, operators, and operands

•Issues with 4-valued logic

•Specifying delays in Dataflow modeling


Introduction
•Usages of gate-level modeling
–Small designs
–Netlist of gates, Logic Synthesis

•Next level up: Dataflow modeling


–Continuous assignment
• The assign keyword

module my_and(output out, input in1, in2);


assign out = in1 & in2;
endmodule
Rules for assign statement

• LHS data type: only net (wire)

• RHS data type: any type (register, net) or function

• Continuous assignments are always active. Assignment


expression is evaluated as soon as the right side operand
changes and value is assigned to the left hand side net.

• Delay values can be specified for assignment in terms of


time units. Similar to gate delays
Rules for assign statement
Implicit continuous assignment

Implicit net declaration


Specifying Delays at Dataflow Level
1. Regular Assignment Delay
assign #10 out = in1 & in2;

Any change in values of in1 or in2will result in delay value of 10


time units before recomputation of the of the expression
If in1 and in2 changes value again before 10 time units when the
result propagates to out, the values of in1 and in2 at the
time of recomputation are considered. This is called inertial
delay.
An input pulse that is shorter than the delay of the assignment
statement does not propagate to the output
Delays at Dataflow Level are
Inertial Delay

assign #10 out = in1 & in2;


Specifying Delays at Dataflow Level
1. Implicit Continuous Assignment Delay
wire #10 out = in1 & in2;

//same as
wire out;
assign #10 out = in1 & in2;

2. Net Declaration Delay


wire # 10 out;
assign out = in1 & in2;

//same as
Wire out;
assign #10 out = in1 & in2;
Expression, Operand, Operator

integer count, final_count;


final_count = count + 1; // integer operand

real a, b, c;
c = a - b; // real operands

reg [15:0] reg1, reg2;


reg [3:0] reg_out;
reg_out = reg1[3:0] ^ reg2[3:0]; // part-select operands

reg ret_value;
ret_value = calculate_parity(A, B); // function type operand
Operator category Operators symbol
Arithmetic * / + - % **
Logical ! && ||
Relational > < <= >=
Equality == != === !===
Bitwise ~ & | ^ ^~ ~^
Reduction & ~& | ~| ^ ~^ ^~
Shift >> << >>> <<<
Reduction & ~& | ~| ^~ or ~^

Concatenation {}
Replication {{}}
Conditional ?:
Arithmetic Operators
A = 4'b0011; +5
-4
B = 4'b0100;
D = 6; E = 4; F=2; -10/5
-6’d10/5 // Do NOT use
A * B // =(2's complement of 10)/5
// =(232 - 10)/5
D / E
A + B • 4-valued logic issue:
B - A x and z values
F = E ** F; If any operand bit has a value x, then
result of the entire expression is x
13 % 3
16 % 4 in1 = 4'b101x;
-7 % 2 /* takes the
in2 = 4'b1010;
sign of first operand*/
sum = in1 + in2;
//sum will be evaluated
7 % -2 to the value 4’bx
Logical Operators
Relational Operators
Equality Operators

// A = 4, B = 3
// X = 4'b1010, Y = 4'b1101

A == B // Z = 4'b1xxz, M = 4'b1xxz
X != Y // N = 4'b1xxx

X == Z
Z === M
Z === N
M !== N
Bitwise Operators
// X = 4'b1010
// Y = 4'b1101
// Z = 4'b10x1

~X
X & Y
X | Y
X ^ Y
X ^~ Y
X & Z

 Bitwise vs. Logical operators

 Bit-width mismatch issue


Bitwise Operators

 Bitwise vs. Logical operators

 Bit-width mismatch issue:

 If one operand is shorter than other, it will be bit-


extended with zeros to match the length of the
longer operand
Reduction Operators
• It is unary operator, perform a bitwise operation on
a single vector operand and yield 1-bit result
• Reduction operator works bit by bit from right to left

• // X = 4'b1010
&X
|X
^X
Shift Operators
// X = 4'b1100

Y = X >> 1;
Y = X << 1;
Y = X << 2;

integer a, b, c;
a = 0;
b = -10;
c = a + (b >>> 3);
Concatenation Operator
•Unsized operands not allowed

// A = 1'b1, B = 2'b00,
// C = 2'b10, D = 3'b110

Y = {B , C}
Y = {A , B , C , D , 3'b001}
Y = {A , B[0], C[1]}
Replication Operator
reg A;
reg [1:0] B, C;
reg [2:0] D;
A = 1'b1;
B = 2'b00;
C = 2'b10;
D = 3'b110;
Y = { 4{A} }
Y = { 4{A} , 2{B} }
Y = { 4{A} , 2{B} , C }
Conditional
Operator

assign addr_bus = drive_enable ? addr_out :


36'bz;

assign out = control ? in1 : in0;


assign out = (A == 3) ? ( control ? x : y ):
( control ? m : n) ;
• Unary Operators
•* / % Precedence
•+ -
• >> <<
• < <= => >
• == != === !==
• Reduction
• Logical
• Conditional
Gate Level vs. Dataflow Modeling
module mux4_to_1 (output out, input i0, i1,
i2, i3, s1, s0);

wire s1n, s0n, y0, y1, y2, y3;

not (s1n, s1);


Gate Level
not (s0n, s0);
Model
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0);
and (y2, i2, s1, s0n);
and (y3, i3, s1, s0);

or (out, y0, y1, y2, y3);

endmodule
Gate Level vs. Dataflow Modeling

Dataflow Model

module mux4_to_1 (output out,


input i0, i1, i2, i3, s1, s0);

assign out = (~s1 & ~s0 & i0)|


(~s1 & s0 & i1)|
( s1 & ~s0 & i2)|
( s1 & s0 & i3);
endmodule
Gate Level vs. Dataflow Modeling
Gate Level Model
module mux4_to_1 (output out,
input i0, i1, i2, i3, s1, s0);

wire s1n, s0n, y0, y1, y2, y3;

not (s1n, s1);


not (s0n, s0);

Dataflow Model
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0); module mux4_to_1 (output out,
and (y2, i2, s1, s0n); input i0, i1, i2, i3, s1, s0);
and (y3, i3, s1, s0);
assign out = (~s1 & ~s0 & i0)|
or (out, y0, y1, y2, y3); (~s1 & s0 & i1)|
( s1 & ~s0 & i2)|
endmodule ( s1 & s0 & i3);
endmodule
Another alternative for Mux 4-to-1
• Use conditional operator
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);

//port declaration
Output out;
input i0, i1, i2, i3;
input s1, s0;

//use nested conditional operator


assign out = s1 ?(s0 ? i3 : i2):(s0 ? i3 : i2)

endmodule
4-bit Full-adder Example
Full-adder Example
module fulladd (sum, c_out, a, b, c_in);

// I/O port declarations

output sum, c_out;

input a, b, c_in;

//specify the function of full adder

assign {c_out, sum} = a + b + c_in;

endmodule
module fulladd (sum, c_out, a, b, c_in); 4-bit Full-adder
Example
// I/O port declarations

output [3:0] sum;

output c_out;

input [3:0] a, b,

input c_in;

//specify the function of full adder

assign {c_out, sum} = a + b + c_in;

endmodule
Example: Carry Look ahead
Adder
module fulladd4(sum, c_out, assign c1 = g0 | (p0 & c_in),
a, b, c_in); c2 = g1 | (p1 & g0) |
(p1 & p0 & c_in),
output [3:0] sum;
c3 = g2 | (p2 & g1) |
output c_out;
(p2 & p1 & g0) |
input [3:0] a,b;
(p2 & p1 & p0 & c_in),
input c_in;
c4 = g3 | (p3 & g2) |
wire p0,g0, p1,g1, p2,g2, (p3 & p2 & g1) |
p3,g3, c4, c3, c2, c1; (p3 & p2 & p1 & g0) |
(p3 & p2 & p1 & p0 & c_in);
assign p0 = a[0] ^ b[0],
p1 = a[1] ^ b[1], assign sum[0] = p0 ^ c_in,
p2 = a[2] ^ b[2], sum[1] = p1 ^ c1,
p3 = a[3] ^ b[3]; sum[2] = p2 ^ c2,
sum[3] = p3 ^ c3;
assign g0 = a[0] & b[0],
g1 = a[1] & b[1], assign c_out = c4;
g2 = a[2] & b[2],
endmodule
g3 = a[3] & b[3];
Example: 4-bit Ripple Carry
Counter
Dataflow Modeling of D Flip flop
• Negative Edge Triggered D-FF

module edge_dff(q, qbar, d, clk,


clear);
output q,qbar;
input d, clk, clear;
wire s, sbar, r, rbar,cbar;
assign cbar = ~clear;
assign sbar = ~(rbar & s),
s = ~(sbar & cbar & ~clk),
r = ~(rbar & ~clk & s),
rbar = ~(r & cbar & d);
assign q = ~(s & qbar),
qbar = ~(q & r & cbar);
endmodule
Edge-Triggered T-FF

module edge_dff(q, qbar, d, clk,


clear);
. . .
endmodule

module T_FF(q, clk, clear);


output q;
input clk, clear;
edge_dff ff1(q, ,~q, clk, clear);
endmodule
Verilog® HDL
Behavioral Modeling
 Behavioral Modeling

 Concepts

 Constructs

Verilog HDL 2005


Introduction
 Move toward higher abstractions

 Gate-level modeling
Netlist of gates

 Dataflow modeling
Boolean function assigned to a net

 Now, behavioral modeling


A sequential algorithm (quite similar to software) that
determines the value(s) of signal(s)
Verilog HDL 2005
Structured Procedures

 Two basic structured procedure statements

always

initial
 All behavioral statements can appear only inside these blocks

 Each always or initial block has a separate activity flow


(concurrency)

 Start from simulation time 0

 Cannot be nested
Verilog HDL 2005
Structured Procedures: initial statement

 Starts at time 0

 Executes only once during a simulation

 Multiple initial blocks, execute in parallel

 All start at time 0

 Each finishes independently


 Syntax:
initial
begin
// behavioral statements
end
Verilog HDL 2005
Structured Procedures: initial statement
 Example:
module stimulus;
reg x, y, a, b, m;
initial
initial #50 $finish;
m= 1’b0; endmodule

initial
begin
#5 a=1’b1;
#25 b=1’b0;
end

initial
begin
#10 x=1’b0;
#25 y=1’b1;
end 2005 Verilog HDL
Structured Procedures: always statement
 Start at time 0

 Execute the statements in a looping fashion

 Example
module clock_gen;
reg clock;

// Initialize clock at time zero


initial
clock = 1’b0;

// Toggle clock every half-cycle (time period =20)


always
#10 clock = ~clock;

initial
#1000 $finish;
endmodule

Verilog HDL 2005


Procedural Assignments

 Assignments inside initial and always

 Are used to update values of reg, integer, real, or time

variables

 The value remains unchanged until another


procedural assignment updates it

 In contrast to continuous assignment (Dataflow


Modeling, previous chapter)
Verilog HDL 2005
Procedural Assignments
 Syntax
 <lvalue> = <expression>

 <lvalue> can be
 reg, integer, real, time

 A bit-select of the above (e.g., addr[0])

 A part-select of the above (e.g., addr[31:16])

 A concatenation of any of the above

 <expression> is the same as introduced in dataflow modeling

 What happens if the widths do not match?


 LHS wider than RHS => RHS is zero-extended

 RHS wider than LHS => RHS is truncated (Least significant part is kept)
Verilog HDL 2005
Procedural Assignments

 The two types of procedural assignments

 Blocking assignments

 Non-blocking assignments

Verilog HDL 2005


Procedural Assignments
 Blocking assignments

 are executed in order (sequentially)

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

Verilog HDL 2005


Procedural Assignments
 Non-blocking assignments
 The next statements are not blocked for this one
 Syntax:
 <lvalue> <= <expression>
 Example:
reg x, y, z;
reg [15:0] reg_a, reg_b;
integer count; All executed at time 0
initial begin
x=0; y=1; z=1;
count=0;
reg_a= 16’b0; reg_b = reg_a;
reg_a[2] <= #15 1’b1; Scheduled to run at time 15
reg_b[15:13] <= #10 {x, y, z};
count <= count + 1; Scheduled to run at time 10
end
Verilog HDL 2005
Procedural Assignments
 Application of non-blocking assignments
 Used to model concurrent data transfers
 Example: Write behavioral statements to swap values of two
variables
 Another example

always @(posedge clock)


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

Verilog HDL 2005


Procedural Assignments

 Race condition
 When the final result of simulating two (or more) concurrent
processes depends on their order of execution
 Example:
always @(posedge clock)
b = a;
always @(posedge clock)
a = b;
always @(posedge clock)
 Solution: begin
always @(posedge clock) temp_b = b;
temp_a = a;
b <= a; b = temp_a;
always @(posedge clock) a = temp_b;
end
a <= b;
Verilog HDL 2005
Procedural Assignments

 Recommendation

 Concurrent data transfers => race condition

 Use non-blocking assignments wherever concurrent


data transfers

 Example: pipeline modeling

 Disadvantage:

Lower simulation performance


Higher memory usage in the simulator
Verilog HDL 2005
Timing Controls

 Delay based timing control

 Event based timing control

 Level-sensitive timing control


Delay based timing control
 Delay based timing control in an expression specifies the

time duration between statement encountered and


statement executed

 Delays are specified by the symbol #

 Delays can be specified by a number, identifier or

mintypmax expression

 There are three types of delay control for procedural

assignments
1. Regular delay control
 Non-zero delay is specified to the left of procedural assignment
2. Intra-assignment delay control
 Non-zero delay is specified to the right of assignment operator
3. Zero delay control
 Procedural statements in different always –initial blocks may be

evaluated at the same simulation time.

 Order of execution of these statements is nondeterministic

 Zero delay control is a method to ensure that statement is executed

last after all other statements


Event-based timing control
 An event is the change in the value on a register or a net.

 Events can be utilized to trigger execution of a statement

or a block of statements

 Four types

 Regular event control

 Named event control

 Event OR control

 Level-sensitive timing control


1. Regular event control
 @ symbol is used to specify an event control
2. Named event control
 Verilog provides the capability to declare event and then
trigger and recognize the event.
 Keyword used is event and triggered by the symbol ->
3. Event OR control
 Sensitivity list
Level Sensitive Timing Control

 @ : it provides edge sensitive control

 Keyword wait is used for level sensitive constructs


Behavioral Modeling Statements:
Conditional Statements
 Just the same as if-else in C

 Syntax:
if (<expression>) true_statement;

if (<expression>) true_statement;
else false_statement;

if (<expression>) true_statement1;
else if (<expression>) true_statement2;
else if (<expression>) true_statement3;
else default_statement;

 True is 1 or non-zero

 False is 0 or ambiguous (x or z)

 More than one statement: begin end


Verilog HDL 2005
Conditional Statements

 Examples:
if (!lock) buffer = data;

if (enable) out = in;

if (number_queued < MAX_Q_DEPTH)


begin
data_queue = data;
number_queued = number_queued +1;
end
else $display(“Queue full! Try again.”);

if (alu_control==0)
y = x+z;
else if (alu_control==1)
y = x-z;
else if (alu_control==2)
y = x*z;
else
$display(“Invalid ALU control signal.”);
Verilog HDL 2005
Behavioral Modeling Statements:
Multiway Branching
 Similar to switch-case statement in C
 Syntax:
case (<expression>)
alternative1: statement1;
alternative2: statement2;
...
default: default_statement; // optional
endcase
 Notes:
 <expression> is compared to the alternatives in the order
specified.
 Default statement is optional

Verilog HDL 2005


Multiway Branching
 Examples:
reg [1:0] alu_control;
...
case (alu_control)
2’b00: y = x + z;
2’b01: y = x – z;
2’b10: y = x * z;
default: $display(“Invalid ALU control signal.”);

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


Verilog HDL 2005
Multiway Branching
 Example:
module mux4_to_1(out, i0, i1, i2, i3, s1, s0);
output out;
input i0, i1, i2, i3, s1, s0;
reg out;
// 0, 1, x, z

always @(*)
case ({s1,s0}) // {s0,s1} = s0s1= 00, 01, 10, 11
2’d0: out = i0;
2’d1: out = i1;
2’d2: out = i2;
2’d3: out = i3;
default: out = 1’bz;
endcase
endmodule

Verilog HDL 2005


Multiway Branching
 The case statements compares <expression> and alternatives bit-for-bit
 x and z values should match
module demultiplexer1_to_4(out0, out1, out2, out3, in, s1, s0);
output out0, out1, out2, out3;
input in, s1, s0;
always @(s1 or s0 or in)
case( {s1, s0} ) // {s1, s0} = s1s0 =00, 01 ,10 , 11;
2’b00: begin out0=in;out1=1’bz;out2=1’bz;out3=1’bz; end
2’b01: begin out0=1’bz;out1=in;out2=1’bz;out3=1’bz; end
2’b10: begin out0=1’bz;out1=1’bz;out2=in;out3=1’bz; end
2’b11: begin out0=1’bz;out1=1’bz;out2=1’bz;out3=in; end
2’bx0, 2’bx1, 2’bxz, 2’bxx, 2’b0x, 2’b1x, 2’bzx:
begin out0=1’bx;out1=1’bx;out2=1’bx;out3=1’bx; end
2’bz0, 2’bz1, 2’bzz, 2’b0z, 2’b1z:
begin out0=1’bz;out1=1’bz;out2=1’bz;out3=1’bz; end

endcase
endmodule

Verilog HDL 2005


Multiway Branching

 casex and casez keywords


 casez treats all z values as “don’t care”

 casex treats all x and z values as “don’t care”


 Example:
reg [3:0]
integer state;
casex(encoding) //encoding = 4’bxxx0
4’b1xxx: next_state=3;
4’bx1xx: next_state=2;
4’bxx1x: next_state=1;
4’bxxx1: next_state=0;
default: next_state=0;
endcase
Verilog HDL 2005
Behavioral Modeling Statements:Loops

 Loops in Verilog
 while, for, repeat, forever

 The while loop syntax:


while (<expression>)
statement;
 Example:
integer count=0;
while(count<128)
begin
$display(“count=%d”,count);
count=count+1;
end
Verilog HDL 2005
Loops
 The for loop

 Similar to C

 Syntax:
for( init_expr; cond_expr; change_expr)

statement;

 Example:

integer count;

for(count=0; count<127; count=count+1)

$display(“count=%d”,count);
Verilog HDL 2005
 The repeat loop Loops
 Syntax:
repeat( number_of_iterations )
statement;
 The number is evaluated only when the loop is first
encoutered
 Example:

integer count=0;
initial
begin
repeat(127)
begin
$display(“count=%d”, count);
count=count+1;
end
Verilog HDL
end 2005
 The forever loop Loops
 Syntax:
forever
statement;

 Equivalent to while(1)

 Loop does not contain any expression and executes forever


until the $finish task is encountered

 A forever loop is typically used in conjunction with timing


control constructs.

 If timing constructs are not used , the Verilog simulator would


execute this statement infinitely without advancing simulation
time and rest of the design would never be executed
Verilog HDL 2005
 Example Loops

Verilog HDL 2005


Block Types

 Sequential block

 Parallel block
Sequential Block
 Keywords begin and end are used to group statements into sequential
blocks
Parallel Block

 Keywords fork and join are used to group statements into

parallel blocks

 Statements in a parallel block are executed concurrently

 Ordering of the statements is controlled by the delay or

event control assigned to each statement.

 If delay or event control is specified, it is relative to time

the block was entered.

 Disadvantage : Possibility of race condition


 Example: Parallel Block
Special Features of Blocks

 Nested Blocks

 Named Blocks

 Disabling Named Blocks


Nested Blocks
 Sequential and parallel blocks can be nested
Named Blocks

 Blocks can be given names

 Local variables can be declared for the named blocks

 Named blocks are a part of the design hierarchy.

Variables in a named block can be accessed by using


hierarchical name referencing

 Named blocks can be disabled that is their execution

can be stopped
 Example: Named Blocks
Disabling Named Blocks

 Keyword disable provides a way to terminate the

execution of the named block.

 It is used to get out of loops, handle error condition, or

control execution of piece of code based on control


signal

 Similar to break statement used in C language


Disabling Named Blocks
Generate Blocks
 “generate” statements allow Verilog code to be generated

dynamically before the simulation or synthesis begins.

 Very convenient to create parameterized module descriptions.

 Example: N-bit ripple carry adder for arbitrary value of N.

 Requires the keywords “generate” and “endgenerate”.

 Generate instantiations can be carried out for various blocks:

 Modules, user-defined primitives, gates, continuous

assignments, “initial” and “always” blocks, etc.


 Generated instances have unique identifier names and can be

referenced hierarchically.
Methods to create generate
statements:

 Generate loop

 Generate conditional

 Generate case
Generate Loop
 A generate loop permits following to be instantiated

multiple times using a for loop

 Variable Declarations

 Modulus

 User defined primitives, gate primitives

 Continuous assignments

 initial and always blocks


Special “genvar” variables:
 The keyword “genvar” can be used to declare variables

that are used only in the evaluation of generate block.

 These variables do not exist during simulation or

synthesis.

 Value of a “genvar” can be defined only in a generate loop

 Every generate loop is assigned a name, so that variables

inside the generate loop can be referenced hierarchically.


Example1: Bitwise xor of two n-bit buses

module xor_bitwise (f, a, b);


parameter N = 16;
input [N-1:0] a, b;
output [N-1:0] f;
genvar p;
generate for (p=0; p<N; p=p+1)
begin xorlp
xor XG (f[p], a[p], b[p]);
end
endgenerate
endmodule
Example2: Design of N-bit Ripple Carry Adder

// Structural gate-level description of a full adder


module full_adder (a, b, c, sum, cout);
input a, b, c;
output, sum, cout;
wire t1, t2, t3;
xor G1 (t1, a, b), G2 (sum, t1, c);
and G3 (t2, a, b), G4 (t3, t1, c);
or G5 (cout, t2, t3);
endmodule
Example2: Design of N-bit Ripple Carry Adder

module RCA (carry_out, sum, a, b, carry_in);

parameter N = 8;

input [N-1:0] a, b;

input carry_in;

output [N-1:0] sum, output carry_out;

wire [N:0] carry; // carry[N] is carry out

assign carry[0] = carry_in;

assign carry_out = carry[N];


Example2: Design of N-bit Ripple Carry Adder
genvar i;
generate for (i=0; i<N; i++)
begin fa_loop
wire t1, t2, t3;
xor G1 (t1, a[i], b[i]), G2 (sum[i], t1, carry[i]);
and G3 (t2, a[i], b[i]), G4 (t3, t1, carry[i]);
or G5 (carry[i+1], t2, t3);
end
endgenerate
endmodule
Example of behavioral modeling
module mux4_to_1(out, i0, i1, i2, i3, s1, s0);
output out;

input i0, i1, i2, i3, s1, s0;

reg out;

always @(*)

case ({s1,s0})
2’b00: out = i0;
2’b01: out = i1;
2’b10: out = i2;
2’b11: out = i3;
default: out = 1’bx;
endcase
endmodule
Compare with other modeling styles
module counter (Q, clk, clear);
output reg [3:0] count;
4-bit counter
input clk, clear
reg[3:0] Q;

always @ (negedge clock )


begin
if (clear)
Q <= 4’d0;
else
Q<= Q + 1;
end
endmodule
module counter (Q, clk, clear); Parameterized N-bit counter
parameter N=4;
output reg [N:0] Q;
input clk, clear
always @ (negedge clock )
begin
if (clear)
Q <= 0;
else
Q<= Q + 1;
end
endmodule
Up-down counter (synchronous clear)
module counter (mode, clr, ld, d_in, clk, count);
input mode, clr, ld, clk;
input [0:7] d_in;
output reg [0:7] count;
always @ (posedge clk)
begin
if (ld) count <= d_in;
else if (clr) count <= 0;
else if (mode) count <= count + 1;
else count <= count – 1;
end
endmodule
Task and Functions

 Reusing code

 Tasks and Functions

Verilog HDL 2005


Introduction
 Procedures/Subroutines/Functions in SW

programming languages

 The same functionality, in different places

 Verilog equivalence:

 Tasks and Functions

 Used in behavioral modeling

 Part of design hierarchy  Hierarchical name


Verilog HDL 2005
Contents

 Functions

 Tasks

 Differences between tasks and functions

Verilog HDL 2005


FUNCTIONS
Functions

 Keyword: function, endfunction

 Can be used if the procedure

 does not have any timing control constructs

 returns exactly a single value

 has at least one input argument


Verilog HDL 2005
Functions
 Function Declaration and Invocation
 Declaration syntax:

function <range_or_type> <func_name>;

<input declaration(s)>

<variable_declaration(s)>
begin // if more than one statement needed

<statements>

end // if begin used

endfunction
Verilog HDL 2005
Functions

 Function Declaration and Invocation

 Invocation syntax:

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

Verilog HDL 2005


Functions
 Semantics
 much like function in Pascal

 An internal implicit reg is declared inside the function


with the same name

 The return value is specified by setting that implicit reg

 <range_or_type> defines width and type of the


implicit reg

 <type> can be integer or real

 default bit width is 1


Verilog HDL 2005
Function Examples Parity Generator
module parity; function calc_parity;
reg [31:0] addr; input [31:0] address;
reg parity; begin
calc_parity = ^address;
initial begin
end

endfunction
end

always @(addr) endmodule


begin
parity = calc_parity(addr);
$display("Parity calculated = %b",
calc_parity(addr) );
end

Verilog HDL 2005


Function Examples Controllable Shifter
module shifter; function [31:0] shift;
`define LEFT_SHIFT 1'b0 input [31:0] address;
`define RIGHT_SHIFT 1'b1 input control;
reg [31:0] addr, left_addr, begin
right_addr;
shift = (control==`LEFT_SHIFT)
reg control; ?(address<<1) : (address>>1);
end
initial endfunction
begin
… endmodule
end

always @(addr)
begin
left_addr =shift(addr, `LEFT_SHIFT);
right_addr =shift(addr,`RIGHT_SHIFT);
end

Verilog HDL 2005


TASKS
Tasks

 Keywords: task, endtask

 Must be used if the procedure has

 any timing control constructs

 zero or more than one output arguments

 no input arguments

Verilog HDL 2005


Tasks
 Task declaration and invocation

 Declaration syntax

task <task_name>;

<I/O declarations>

<variable and event declarations>


begin // if more than one statement needed

<statement(s)>
end // if begin used!

endtask
Verilog HDL 2005
Tasks
 Task declaration and invocation

 Task invocation syntax


<task_name>;

<task_name> (<arguments>);

 input and inout arguments are passed into the task

 output and inout arguments are passed back to the


invoking statement when task is completed

Verilog HDL 2005


Tasks
 I/O declaration in modules vs. tasks

 Both used keywords: input, output, inout

 In modules, represent ports

 connect to external signals

 In tasks, represent arguments

 pass values to and from the task


Verilog HDL 2005
Task Examples
Use of input and output arguments
module operation;
task bitwise_oper;
parameter delay = 10;
output [15:0] ab_and, ab_or,
reg [15:0] A, B;
ab_xor;
reg [15:0] AB_AND, AB_OR, AB_XOR;
input [15:0] a, b;
initial begin
$monitor( …);
#delay ab_and = a & b;
initial
begin ab_or = a | b;
… ab_xor = a ^ b;
end
end
always @(A or B)
begin endtask

bitwise_oper(AB_AND, AB_OR, endmodule


AB_XOR, A, B);
end
Verilog HDL 2005
Task Examples
Use of module local variables
module sequence; task init_sequence;
reg clock;
clock = 1'b0;

initial endtask
begin
… task asymmetric_sequence;
end
begin

initial #12 clock = 1'b0;


init_sequence; #5 clock = 1'b1;

#3 clock = 1'b0;
always
asymmetric_sequence; #10 clock = 1'b1;

end

endtask
Verilog HDL 2005
DIFFERENCES BETWEEN
TASKS AND FUNCTIONS
Differences between...
 Tasks
 Functions
 Can enable other tasks and
 Can enable (call) just
functions
another function (not task)
 May execute in non-zero
 Execute in 0 simulation
simulation time
time
 May contain any timing
 No timing control
control statements
statements allowed
 May have arbitrary input,
 At lease one input
output, or inout
 Return only a single value
Verilog HDL  Do not return any value 2005
Differences between…

 Both
 are defined in a module

 are local to the module

 can have local variables (registers, but not nets) and events

 contain only behavioral statements

 do not contain initial or always statements

 are called from initial or always statements or other


tasks or functions
Verilog HDL 2005
Differences between…

 Tasks can be used for common Verilog code

 Function are used when the common code

 is purely combinational

 executes in 0 simulation time

 provides exactly one output

 Functions are typically used for conversions and

commonly used calculations


Verilog HDL 2005
Summary

 How to define tasks and functions

 Where to use each of them

 The same purpose as subroutines in SW

 Provide more readability, easier code management

 Are part of design hierarchy

 Tasks are more general than functions

 Can represent almost any common Verilog code

 Functions can only model purely combinational calculations


Verilog HDL 2005

You might also like