Digital System Design
Verilog® HDL
Useful Modeling Techniques
Maziar Goudarzi
Today Program
Procedural Continuous Assignment
Overriding Parameters
Conditional Compilation and Execution
Useful System Tasks
12/4/2022 Verilog HDL 2
Procedural Continuous
Assignment
Useful Modeling Techniques
Procedural Continuous Assignment
Overrides, for a certain time, the effect of regular
assignments to a variable.
Two types
assign/deassign
Works only on register data types
force/release
Works on both register and net data types
Note:
Not synthesizable. Use only for modeling and simulation
12/4/2022 Verilog HDL 4
Procedural Continuous Assignment
(cont’d)
assign/deassign
Keywords
assign: overrides regular procedural assignments
• LHS: reg or concatenation of regs. No nets. No arrays.
No bit-select or part-select
deassign: re-enables regular procedural
assignments
After deassign:
Last value remains on the register until a new
procedural assignment changes it.
12/4/2022 Verilog HDL 5
12/4/2022 Verilog HDL 6
Procedural Continuous Assignment
(cont’d)
force/release
Keywords:
force: overrides all procedural/continuous/
procedural continuous assignments
release: re-enables other assignments
Hence, assignments in priority order:
1. force
2. assign (procedural continuous)
3. Procedural/continuous assignments
12/4/2022 Verilog HDL 7
force/release on reg variables
12/4/2022 Verilog HDL 8
force/release on nets
Net value immediately returns to its normal
assigned value when released
12/4/2022 Verilog HDL 9
Overriding Parameters
Useful Modeling Techniques
Overriding Parameters
Two methods
defparam statement
Module instance parameter value assignment
defparam statement
Keyword: defparam
Syntax:
defparam <parameter_hierarchical_name>=<value>;
12/4/2022 Verilog HDL 11
12/4/2022 Verilog HDL 12
Overriding Parameters (cont’d)
Module instance parameter values
Parameters are overridden when the module is
instantiated
Syntax:
<module_name> #(<param_vals>) <instance_name>;
12/4/2022 Verilog HDL 13
Example with multiple parameters
12/4/2022 Verilog HDL 14
Conditional Compilation and
Execution
Useful Modeling Techniques
Conditional Compilation
Usage:
To compile some part of code under certain
conditions
Keywords:
‘ifdef, `else, `endif
‘define to define the flag
12/4/2022 Verilog HDL 16
12/4/2022 Verilog HDL 17
Conditional Execution
Usage:
To execute some part of code when a flag is set at runtime
Used only in behavioral modeling
Keywords:
$test$plusargs
Syntax:
$test$plusargs( <argument_to_check> )
12/4/2022 Verilog HDL 18
12/4/2022 Verilog HDL 19
Useful System Tasks
Useful Modeling Techniques
Useful System Tasks
File Output
Opening a file
Syntax:
<file_handle> = $fopen( “<file_name>” );
<file_handle> is a 32 bit value, called multi-channel descriptor
Only 1 bit is set in each descriptor
Standard output has a descriptor of 1 (Channel 0)
12/4/2022 Verilog HDL 21
Useful System Tasks
File Output (cont’d)
Writing to files
$fdisplay, $fmonitor, $fstrobe
$strobe, $fstrobe
The same as $display, $fdisplay, but
executed after all other statements schedule in the
same simulation time
Syntax:
$fdisplay(<handle>, p1, p2,…, pn);
Closing files
$fclose(<handle>);
12/4/2022 Verilog HDL 22
Example: Simultaneously writing to
multiple files
12/4/2022 Verilog HDL 23
Strobe
//Strobing
always @(posedge clock)
begin
a = b;
c = d;
end
always @(posedge clock)
$strobe("Displaying a = %b, c = %b", a, c); // display values
at posedge
12/4/2022 Verilog HDL 24
Useful System Tasks
Random Number Generation
Syntax:
$random;
$random(<seed>);
Returns a 32 bit random value
12/4/2022 Verilog HDL 25
reg [23:0] rand1, rand2;
rand1 = $random % 60; //Generates a random
//number between -59 and 59
rand2 = {$random} % 60; //Addition of
//concatenation operator to $random generates a
//positive value between0 and 59.
12/4/2022 Verilog HDL 26
Digital System Design
Verilog® HDL
Behavioral Modeling (2)
Today program
Behavioral Modeling
Timing controls
Other features
12/4/2022
Behavioral Modeling
Timing Controls in
Behavioral Modeling
Introduction
No timing controls No advance in
simulation time
Three methods of timing control
delay-based
event-based
level-sensitive
12/4/2022
Delay-based
Timing Controls
Delay Duration between encountering
and executing a statement
Delay symbol: #
Delay specification syntax:
<delay>
::= #<NUMBER>
||= #<identifier>
||= #<mintypmax_exp> <,<mintypmax_exp>>*)
12/4/2022
Delay-based
Timing Controls (cont’d)
Types of delay-based timing controls
1. Regular delay control
2. Intra-assignment delay control
3. Zero-delay control
12/4/2022
Delay-based
Timing Controls (cont’d)
Regular Delay Control
Symbol: non-zero delay before a procedural assignment
Used in most of our previous examples
12/4/2022
Delay-based
Timing Controls (cont’d)
Intra-assignment Delay Control
Symbol: non-zero delay to the right of the
assignment operator
Operation sequence:
1. Compute the right-hand-side expression at the
current time.
2. Defer the assignment of the above computed value
to the LHS by the specified delay.
12/4/2022
Delay-based
Timing Controls (cont’d)
Intra-assignment delay examples
12/4/2022
Delay-based
Timing Controls (cont’d)
Zero-Delay Control
Symbol: #0
Different initial/always blocks in the same
simulation time
Execution order non-deterministic
Zero-delay ensures execution after all other
statements
Eliminates race conditions
Multiple zero-delay statements
Non-deterministic execution order
12/4/2022
Delay-based
Timing Controls (cont’d)
Zero-delay control examples
12/4/2022
Event-based
Timing Control
Event
Change in the value of a register or net
Used to trigger execution of a statement or
block (reactive behavior/reactivity)
Types of Event-based timing control
1. Regular event control
2. Named event control
3. Event OR control
4. Level-sensitive timing control (next section)
12/4/2022
Event-based
Timing Control (cont’d)
Regular event control
Symbol: @(<event>)
Events to specify:
posedge sig
• Change of sig from any value to 1
or from 0 to any value
negedge sig
• Change of sig from any value to 0
or from 1 to any value
sig
• Any chage in sig value
12/4/2022
Event-based
Timing Control (cont’d)
Regular event control examples
12/4/2022
Event-based
Timing Control (cont’d)
Named event control
You can declare (name) an event, and then
trigger and recognize it.
Verilog keyword for declaration: event
event calc_finished;
Verilog symbol for triggering: ->
->calc_finished
Verilog symbol for recognizing: @()
@(calc_finished)
12/4/2022
Event-based
Timing Control (cont’d)
Named event control examples
12/4/2022
Event-based
Timing Control (cont’d)
Event OR control
Used when need to trigger a block upon occurrence of
any of a set of events.
The list of the events: sensitivity list
Verilog keyword: or
12/4/2022
Level-sensitive
Timing Control
Level-sensitive vs. event-based
event-based: wait for triggering of an event
(change in signal value)
level-sensitive: wait for a certain condition (on
values/levels of signals)
Verilog keyword: wait()
always
wait(count_enable) #20 count=count+1;
12/4/2022
Behavioral Modeling
Other Features
Contents
Sequential and Parallel Blocks
Special Features of Blocks
12/4/2022
Sequential and Parallel Blocks
Blocks: used to group multiple statements
Sequential blocks
Keywords: begin end
Statements are processed in order.
A statement is executed only after its preceding
one completes.
Exception: non-blocking assignments with intra-
assignment delays
A delay or event is relative to the simulation
time when the previous statement completed
execution
12/4/2022
Sequential and Parallel Blocks (cont’d)
Parallel Blocks
Keywords: fork, join
Statements in the blocks are executed
concurrently
Timing controls specify the order of execution of
the statements
All delays are relative to the time the block was
entered
The written order of statements is not important
12/4/2022
Sequential and Parallel Blocks (cont’d)
initial
begin
x=1’b0;
#5 y=1’b1;
#10 z={x,y};
#20 w={y,x};
end
initial
fork
x=1’b0;
#5 y=1’b1;
#10 z={x,y};
#20 w={y,x};
join
12/4/2022
Sequential and Parallel Blocks (cont’d)
Parallel execution Race conditions may arise
initial
begin
x=1’b0;
y=1’b1;
z={x,y};
w={y,x};
end
z, w can take either 2’b01, 2’b10
or 2’bxx, 2’bxx depending on simulator
12/4/2022
Special Features of Blocks
Contents
Nested blocks
Named blocks
Disabling named blocks
12/4/2022
Special Features of Blocks (cont’d)
Nested blocks
Sequential and parallel blocks can be mixed
initial
begin
x=1’b0;
fork
#5 y=1’b1;
#10 z={x,y};
join
#20 w={y,x};
end
12/4/2022
Special Features of Blocks (cont’d)
Named blocks
Syntax:
begin: <the_name> fork: <the_name>
… …
end join
Advantages:
Can have local variables
Are part of the design hierarchy.
Their local variables can be accessed using hierarchical
names
Can be disabled
12/4/2022
Special Features of Blocks (cont’d)
module top;
initial
begin : block1
integer i; //hiera. name: top.block1.i
…
end
initial
fork : block2
reg i; //hierarchical name: top.block2.i
…
join
endmodule
12/4/2022
Special Features of Blocks (cont’d)
Disabling named blocks
Keyword: disable
Action:
Similar to break in C/C++, but can disable any
named block not just the inner-most block.
12/4/2022
Special Features of Blocks (cont’d)
module find_true_bit; while(i < 16)
begin
reg [15:0] flag; if (flag[i])
integer i; begin
$display("Encountered a
initial TRUE bit at element
begin number %d", i);
flag = 16'b disable block1;
0010_0000_0000_0000; end // if
i = 0; i = i + 1;
begin: block1 end // while
end // block1
end //initial
endmodule
12/4/2022
Behavioral Modeling
Examples
4-to-1 Multiplexer
// 4-to-1 multiplexer. Port list is taken exactly from
// the I/O diagram.
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
// Port declarations from the I/O diagram
output out;
input i0, i1, i2, i3;
input s1, s0;
reg out; //output declared as register
//recompute the signal out if any input signal changes.
//All input signals that cause a recomputation of out to
//occur must go into the always @(...)
always @(s1 or s0 or i0 or i1 or i2 or i3)
begin
case ({s1, s0})
2'b00: out = i0;
2'b01: out = i1;
2'b10: out = i2;
2'b11: out = i3;
default: out = 1'bx;
endcase
end
12/4/2022
endmodule
4-bit Counter
//Binary counter
module counter(Q , clock, clear);
// I/O ports
output [3:0] Q;
input clock, clear;
//output defined as register
reg [3:0] Q;
always @( posedge clear or negedge clock)
begin
if (clear)
Q = 4'd0;
else
//Q = (Q + 1) % 16;
Q = (Q + 1) ;
end
endmodule
12/4/2022
Traffic Signal Controller
12/4/2022
`define TRUE 1'b1
`define FALSE 1'b0
`define RED 2'd0
`define YELLOW 2'd1
`define GREEN 2'd2
//State definition HWY CNTRY
`define S0 3'd0 //GREEN RED
`define S1 3'd1 //YELLOW RED
`define S2 3'd2 //RED RED
`define S3 3'd3 //RED GREEN
`define S4 3'd4 //RED YELLOW
//Delays
`define Y2RDELAY 3 //Yellow to red delay
`define R2GDELAY 2 //Red to Green Delay
module sig_control (hwy, cntry, X, clock, clear);
//I/O ports
output [1:0] hwy, cntry; //2 bit output for 3 states of signal GREEN, YELLOW, RED;
reg [1:0] hwy, cntry; //declare output signals are registers
input X; //if TRUE, indicates that there is car on the country road, otherwise FALSE
input clock, clear;
//Internal state variables
reg [2:0] state;
reg [2:0] next_state;
12/4/2022
//Signal controller starts in S0 state
initial begin
state = `S0;
next_state = `S0;
hwy = `GREEN;
cntry = `RED;
end
always @(posedge clock) //state changes only at positive edge of clock
state = next_state;
always @(state) //Compute values of main signal and country signal
begin
case(state)
`S0: begin
hwy = `GREEN;
cntry = `RED;
end
`S1: begin
hwy = `YELLOW;
cntry = `RED;
end
`S2: begin
hwy = `RED;
cntry = `RED;
end
`S3: begin
hwy = `RED;
cntry = `GREEN;
end
`S4: begin
hwy = `RED;
cntry = `YELLOW;
12/4/2022 end
endcase
end
//State machine using case statements
always @(state or clear or X)
begin
if(clear)
next_state = `S0;
else
case (state)
`S0: if( X)
next_state = `S1;
else
next_state = `S0;
`S1: begin //delay some positive edges of clock
repeat(`Y2RDELAY) @(posedge clock) ;
next_state = `S2;
end
`S2: begin //delay some positive edges of clock
repeat(`R2GDELAY) @(posedge clock)
next_state = `S3;
end
`S3: if( X)
next_state = `S3;
else
next_state = `S4;
`S4: begin //delay some positive edges of clock
repeat(`Y2RDELAY) @(posedge clock) ;
next_state = `S0;
end
default: next_state = `S0;
endcase
end
endmodule
12/4/2022
Digital System Design
Verilog® HDL
Behavioral Modeling (1)
Today program
Behavioral Modeling
Concepts
Constructs
12/4/2022 Verilog HDL 65
Introduction
The 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)
12/4/2022 Verilog HDL 66
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
12/4/2022 Verilog HDL 67
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
12/4/2022 Verilog HDL 68
Structured Procedures:
initial statement (cont’d)
Example:
module stimulus;
initial
reg x, y, a, b, m;
#50 $finish;
endmodule
initial
m= 1’b0;
initial
begin
#5 a=1’b1;
#25 b=1’b0;
end
initial
begin
#10 x=1’b0;
#25 y=1’b1;
end
12/4/2022 Verilog HDL 69
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 Can we move this to
clock = 1’b0; the always block?
// Toggle clock every half-cycle (time period =20)
always
#10 clock = ~clock;
initial
What happens if such a
#1000 $finish; $finish is not included?
endmodule
12/4/2022 Verilog HDL 70
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)
12/4/2022 Verilog HDL 71
Procedural Assignments (cont’d)
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)
12/4/2022 Verilog HDL 72
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
12/4/2022 Verilog HDL 73
Conditional Statements (cont’d)
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.”);
12/4/2022 Verilog HDL 74
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
12/4/2022 Verilog HDL 75
Multiway Branching (cont’d)
Examples:
reg [1:0] alu_control;
...
case (alu_control)
2’d0: y = x + z;
2’d1: y = x – z;
2’d2: y = x * z;
default: $display(“Invalid ALU control signal.”);
Now, you write a 4-to-1 multiplexer.
12/4/2022 Verilog HDL 76
Multiway Branching (cont’d)
Example 2:
module mux4_to_1(out, i0, i1, i2, i3, s1, s0);
output out;
input i0, i1, i2, i3, s1, s0;
reg out;
always @(s1 or s0 or i0 or i1 or i2 or i3)
case ({s1,s0})
2’d0: out = i0;
2’d1: out = i1;
2’d2: out = i2;
2’d3: out = i3;
endcase
endmodule
12/4/2022 Verilog HDL 77
Multiway Branching (cont’d)
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} )
2’b00: begin ... end
2’b01: begin ... end
2’b10: begin ... end
2’b11: begin ... end
2’bx0, 2’bx1, 2’bxz, 2’bxx, 2’b0x, 2’b1x, 2’bzx:
begin ... end
2’bz0, 2’bz1, 2’bzz, 2’b0z, 2’b1z:
begin ... end
default: $display(“Unspecified control signals”);
endcase
endmodule
12/4/2022 Verilog HDL 78
Multiway Branching (cont’d)
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)
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
12/4/2022 Verilog HDL 79
Behavioral Modeling Statements:
Loops
Loops in Verilog
while, for, repeat, forever
The while loop syntax:
while (<expression>)
statement;
Example:
Look at p. 136 of your book
12/4/2022 Verilog HDL 80
Loops (cont’d)
The for loop
Similar to C
Syntax:
for( init_expr; cond_expr; change_expr)
statement;
Example:
Look at p. 137 of your book
12/4/2022 Verilog HDL 81
Loops (cont’d)
The repeat loop
Syntax:
repeat( number_of_iterations )
statement;
The number is evaluated only when the loop is
first encoutered
Example:
Look at p. 138 of your book
12/4/2022 Verilog HDL 82
Loops (cont’d)
The forever loop
Syntax:
forever
statement;
Equivalent to while(1)
Example:
Look at pp. 139-140 of your book
12/4/2022 Verilog HDL 83
Procedural Assignments (cont’d)
The two types of procedural assignments
Blocking assignments
Non-blocking assignments
Blocking assignments
are executed in order (sequentially)
Example:
reg x, y, z;
reg [15:0] reg_a, reg_b;
integer count; All executed at time 0
initial 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;
12/4/2022 end Verilog HDL 84
All executed at time 25
Procedural Assignments (cont’d)
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
12/4/2022 end Verilog HDL 85
Procedural Assignments (cont’d)
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
12/4/2022 Verilog HDL 86
Procedural Assignments (cont’d)
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)
begin
temp_b = b;
temp_a = a;
b = temp_a;
a = temp_b;
end
12/4/2022 Verilog HDL 87
Procedural Assignments (cont’d)
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
12/4/2022 Verilog HDL 88
Verilog HDL -Introduction
Typical Design Flow (in 1996)
1. Design specification
2. Behavioral description
3. RTL description
4. Functional verification and testing
5. Logic synthesis
6. Gate-level netlist
7. Logical verification and testing
8. Floor planning, automatic place & route
9. Physical layout
Basics of Digital Design Using
HDLs
Stimulus block
Generating Checking
inputs Circuit Under Design outputs
to CUD (CUD) of CUD
4
8
Test bench
Simulation- Test Bench Styles
Design Methodologies
4-bit Ripple Carry Counter
T-flipflop and the Hierarchy
Ports
Ports provide interface for by which a module can
communicate with its environment
Port connection rules
Connecting Ports
Suppose we have a module
Module- Basic building block
A module can be an element or collection of low level design
blocks
Module
Modules (cont’d)
Verilog supported levels of abstraction
Behavioral (algorithmic) level
Describe the algorithm used
Very similar to C programming
102
Dataflow level
Describe how data flows between registers and is processed
Gate levelInterconnect logic gates
Switch level
Interconnect transistors (MOS transistors)
Register-Transfer Level (RTL)
Generally known as a combination of behavioral+dataflow that
Instance
A module provides a template which you
can create actual objects.
When a module is invoked, Verilog
creates a unique object from the template
The process of creating a object from
module template is called instantiation
The object is called instance
Instances
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);
Instances (cont’d)
module TFF(q, clk, reset);
output q;
input clk, reset;
wire d;
DFF dff0(q, d, clk, reset);
not n1(d, q); // not is a Verilog provided primitive.
endmodule
// module DFF with asynchronous reset
module DFF(q, d, clk, reset);
output q;
input d, clk, reset;
reg q;
always @(posedge reset or negedge clk)
if (reset)
q = 1'b0;
else
q = d;
endmodule
How to build and test a module
Construct a “test bench” for your design
– Develop your hierarchical system within a module that has
input and output ports (called “design” here)
– Develop a separate module to generate tests for the module
(“test”)
– Connect these together within another module (“testbench”)
module testbench (); module design (a, b, c);
wire l, m, n; input a, b;
output c;
design d (l, m, n); …
test t (l, m);
initial begin
//monitor and display
module test (q, r);
…
output q, r;
initial begin
//drive the outputs with signals
…
Another view of this
• 3 chunks of verilog, one for each of:
TESTBENCH is the final piece of hardware which
connect DESIGN with TEST so the inputs generated
go to the design you want to test...
Another piece of
hardware, called Your hardware
TEST, to generate called
interesting inputs DESIGN
Verilog Examples
Module testAdd generated inputs for module halfAdd and
displayed changes. Module halfAdd was the design
module testAdd(a, b, sum, cOut);
module tBench;
input sum, cOut;
wire su, co, a, b;
output a, b;
reg a, b;
halfAdd ad(su, co, a, b);
testAdd tb(a, b, su, co);
initial begin
endmodule
$monitor ($time,,
“a=%b, b=%b, sum=%b, cOut=%b”,
a, b, sum, cOut);
module halfAdd (sum, cOut, a, b); a = 0; b = 0;
output sum, cOut; #10 b = 1;
input a, b; #10 a = 1;
#10 b = 0;
xor #2 (sum, a, b); #10 $finish;
and #2 (cOut, a, b); end
endmodule endmodule
Gate Level Modeling
A logic circuit can be designed by use of logic
gates.
Verilog supports basic logic gates as predefined
primitives. These primitives are instantiated like
modules except that they are predefined in Verilog
and do not need a module definition.
Gate gate_name(out,in1,in2…)
Buf/not gates
Buflnot gates have one scalar input and
one or more scalar outputs.
Bufif/notif
Instantiation of bufif gates
Design of 4:1 Multiplexer
Contd..
Stimulus
4 bit full adder
Declaration:
Code contd..
4 bit adder using 1 bit adder
Stimulus
Gate Delays:
Rise Delay: Delay associated with a
o/p transition to 1 from any value.
Fall Delay: Delay associated with o/p
transition to 0 from any value.
Turn off Delay: Delay associate with
o/p transition to Z from another
value.
Min value
The min vale is the minimum delay value that the designer expects the
gate to have.
Type value
The type value is the typical delay value that the designer expects the gate
to have.
Max value
The max value is the maximum delay value that the designer expects the
gate to have.
//min delay=4
//type delay=5
//max delay=6
and #(4:5:6) a1(out, i1, i2) ;
//min delay, rise=3 , fall =5
//type delay, rise=4 , fall =6
//max delay, rise=5 , fall =7
and #(3:4:5, 5:6:7) a2(out, i1, i2 ) ;
//min delay, rise=2 , fall =3 , turn-off =4
//type delay, rise=3 , fall =4 , trun-off=5
//max delay, rise=4 , fall =5 , trun-off=6
and #(2:3:4, 3:4:5, 4:5:6) a3(out, i1, i2 ) ;
Dataflow Modeling
In complex designs the number of gates
is very large
Currently, automated tools are used to
create a gate-level circuit from a
dataflow design description. This
process is called logic synthesis
Continuous Assignment
Rules:
The left hand side of an assignment must always
be a scalar or vector net
It cannot be a scalar or vector register.
Continuous assignments are always active.
The assignment expression is evaluated as soon
as one of the right-hand-side operands changes
and the value is assigned to the left-hand-side
net.
The operands on the right-hand side can
be registers or nets.
Delay values can be specified for
assignments in terms of time units. Delay
values are used to control the time when
a net is assigned the evaluated value
• Implicit Continious Assignment
//Regular Continious Assignment
wire= out;
assign out = in1& in2;
//same effect is achieved by an implicit assignment
Wire out = in1& in2;
• Implicit Net Declaration
//Continious Assignment,out is a net
Wire i1, i2;
assign out = in1& in2;
Delay
Implicit Continuous Assignment Delay
wire #10 out = in1 & in2;
Net Declaration Delay
wire #10 out ;
assign out = in1 & in2;
Operator Types
Conditional Operator
4:1 Multiplexer Example
User Defined Primitives (UDPs)
• Keywords and, or, not, xor, etc. are System
Primitives
• Can Define your Own Primitives (UDPs)
• Can do this in a variety of ways including Truth
Tables
• Instead of module/endmodule use the keywords
primitive/endprimitive
• Only one output and must be listed first
• Keywords table and endtable used
• Input values listed in order
• Output is always last entry
HDL Example 2
//User defined primitive(UDP)
primitive crctp (x,A,B,C); // user defined
output x;
input A,B,C;
//Truth table for x(A,B,C) = Minterms ( ? )
table // truth table
// A B C : x (Note that this is only a comment)
0 0 0 : 1;
0 0 1 : 0;
0 1 0 : 1;
0 1 1 : 0;
1 0 0 : 1;
1 0 1 : 0;
1 1 0 : 1;
1 1 1 : 1;
endtable
endprimitive
Primitives
• Pre-defined primitives
– Total 26 pre-defined primitives
– All combinational
– Tri-state primitives have multiple output, others have single
output
• User-Defined Primitives (UDP)
– Combinational or sequential
– Single output
• UDP vs. modules
– Used to model cell library
Shorthand Notation
primitive mux_prim ( out, select, a, b );
output out;
input select, a, b;
table
//select a b : out
0 0 ? : 0; // ? => iteration of table entry over 0, 1, x.
select
0 1 ? : 1; a
// i.e., don’t care on the input
mux_prim
1 ? 0 : 0; b out
1 ? 1 : 1;
? 0 0 : 0;
UDP: Sequential Behavior
• In table description, n+2 columns for n
input
• n input columns + internal state column
+ output (next state) column
• Output port -> reg variable
Level-sensitive Behavior
primitive transparent_latch(out, enable, in);
enable
output out;
in Transparent out
input enable, in;
latch
reg out;
table
//enable in state out/next_state
1 1 :? : 1;
1 0 :? : 0;
0 ? :? : -; // ‘-’ -> no change
x 0 :0 : -;
Edge-sensitive Behavior
primitive d_flop( q, clock, d );
clock
output q;
d d_flop q
input clock, d;
reg q;
table
// clock d state q/next_state
(01) 0 : ? : 0; // Parentheses indicate signal transition
(01) 1 : ? : 1; // Rising clock edge
(0?) 1 : 1 : 1;
(0?) 0 : 0 : 0;
(?0) ? : ? : -; // Falling clock edge
Digital System Design
Verilog® HDL
Timing and Delays
Maziar Goudarzi
Today Program
Delays and their definition and use in
Verilog
2005 Verilog HDL 149
Introduction:
Delays and Delay Back-annotation
2005 Verilog HDL 150
Introduction (cont’d)
Functional simulation vs. Timing simulation
Delays are crucial in REAL simulations
Post-synthesis simulation
Post-layout simulation
FPGA counter-part: Post-P&R simulation
Delay Models
Represent different physical concepts
Two most-famous models
Inertial delay
Transport delay (path delay)
2005 Verilog HDL 151
Delay Models:
Inertial Delay
The inertia of a circuit node to change
value
Abstractly models the RC circuit seen at
the node
Different types
Inputinertial delay
Output inertial delay
2005 Verilog HDL 152
Delay Models:
Transport Delay (Path Delay)
Represents the propagation time of
signals from module inputs to its outputs
Models the internal propagation delays of
electrical elements
2005 Verilog HDL 153
Specifying Delays in
Verilog
Delays in Verilog
Specifying Delays in Verilog
Delays are shown by # sign in all Verilog
modeling levels
Supported delay types
Rise, Fall, Turnoff types
Min, Typ, Max values
2005 Verilog HDL 155
Delay Types in Verilog
Rise Delay
From any value to 1
Fall Delay
From any value to 0
Turn-Off Delay
From any value to z
From any value to x
Minimum of the three delays
Min/Typ/Max Delay values
2005 Verilog HDL 156
Specifying Delays in Verilog (cont’d)
Rise/Fall/Turnoff delay types (cont’d)
If no delay specified
Default value is zero
If only one value specified
It is used for all three delays
If two values specified
They refer respectively to rise and fall delays
Turn-off delay is the minimum of the two
2005 Verilog HDL 157
Specifying Delays in Verilog (cont’d)
Min/Typ/Max Values
Another level of delay control in Verilog
Each of rise/fall/turnoff delays can have min/typ/max values
not #(min:typ:max, min:typ:max, min:typ:max) n(out,in)
Only one of Min/Typ/Max values can be used in the entire
simulation run
It is specified at start of simulation, and depends on the
simulator used
ModelSim options
ModelSim> vsim +mindelays
ModelSim> vsim +typdelays
ModelSim> vsim +maxdelays
Typ delay is the default
2005 Verilog HDL 158
Specifying Delays in Verilog (cont’d)
General syntax
#(rise_val, fall_val, turnoff_val)
#(min:typ:max, min:typ:max, min:typ:max)
Gate-Level and Dataflow Modeling
All of the above syntaxes are valid
Behavioral Modeling
Rise/fall/turnoff
delays are not supported
Only min:typ:max values can be specified
Applies to all changes of values
2005 Verilog HDL 159
Delays in
Gate-Level Modeling
Delays in Verilog
Delays in Gate-Level Modeling
The specified delays are output-inertial
delays
and #(rise_val, fall_val, turnoff_val) a(out,in1, in2)
not #(min:typ:max, min:typ:max, min:typ:max) b(out,in)
Examples:
and #(5) a1(out, i1, i2);
and #(4, 6) a2(out, i1, i2);
and #(3, 4, 5) a2(out, i1, i2);
and #(1:2:3, 4:5:6, 5:6:7) a2(out, i1, i2);
2005 Verilog HDL 161
Delays in Gate-Level Modeling (cont’d)
2005 Verilog HDL 162
Delays in Gate-Level Modeling (cont’d)
2005 Verilog HDL 163
Delays in
Dataflow Modeling
Delays in Verilog
Delays in Dataflow Modeling
As in Gate-Level Modeling the delay is
output-inertial delay
Regular assignment delay syntax
assign #delay out = in1 & in2;
Implicit continuous assignment delay
wire #delay out = in1 & in2;
Net declaration delay
Can also be used in Gate-Level modeling
wire #delay w;
2005 Verilog HDL 165
Delays in Dataflow Modeling (cont’d)
Examples
wire #10 out = in1 & in2; wire out;
assign #10 out = in1 & in2;
wire #10 out;
assign out = in1 & in2;
Note: pulses with a width less than the
delay are not propagated to output
2005 Verilog HDL 166
Delays in Dataflow Modeling (cont’d)
// Lumped delays in dataflow modeling
module M(out, a, b, c, d);
output out;
input a, b, c, d;
wire e, f;
// Lumped delay model
assign e=a & b;
assign f=c & d;
assign #11 out = e & f;
endmodule
2005 Verilog HDL 167
Delays in
Behavioral Modeling
Delays in Verilog
Delay in Behavioral Modeling
Only min:typ:max values can be set
i.e. rise/fall/turnoff delays are not supported
Three categories
Regular delays
Intra-assignment delays
Zero delay
2005 Verilog HDL 169
Path (Transport ) Delays
in Verilog
Delays in Verilog
Transport Delays in Verilog
Also called
Pin-to-Pin delay
Path delay
Gate-level, dataflow, and behavioral delays
Property of the elements in the module (white box)
Styles: Distributed or Lumped
Path delay
A property of the module (black box)
Delay from any input to any output port
2005 Verilog HDL 171
Transport Delays in Verilog (cont’d)
2005 Verilog HDL 172
Transport Delays in Verilog (cont’d)
specify block
Assign pin-to-pin delays
Define specparam constants
Setup timing checks in the design
2005 Verilog HDL 173
specify blocks
Parallel connection
Syntax:
specify
(<src_field> => <dest_field>) = <delay>;
endspecify
<src_field> and <dest_field> are vectors of equal
length
Unequal lengths, compile-time error
2005 Verilog HDL 174
specify blocks (cont’d)
Full connection
Syntax:
specify
(<src_field> *> <dest_field>) = <delay>;
endspecify
No need to equal lengths in <src_field> and
<dest_field>
2005 Verilog HDL 175
specify blocks (cont’d)
2005 Verilog HDL 176
specify blocks (cont’d)
specparam constants
Similar to parameter, but only inside specify block
Recommended to be used instead of hard-coded delay
numbers
2005 Verilog HDL 177
specify blocks
(cont’d)
Conditional path
delays
Delay depends on
signal values
Also called State-
Dependent Path
Delay (SDPD)
2005 Verilog HDL 178
specify blocks (cont’d)
Rise, Fall, and Turn-off delays
2005 Verilog HDL 179
specify blocks (cont’d)
Rise, Fall, and Turn-off delays
2005 Verilog HDL 180
specify blocks (cont’d)
Min, Typ, Max delays
Any delay value can also be specified as
(min:typ:max)
2005 Verilog HDL 181
specify blocks (cont’d)
Handling x transitions
Pessimistic approach
Transition to x: minimum possible time
Transition from x: maximum possible time
2005 Verilog HDL 182
specify blocks (cont’d)
Timing Checks
A number of system tasks defined for this
$setup: checks setup-time of a signal before
an event
$hold: checks hold-time of a signal after an
event
$width: checks width of pulses
2005 Verilog HDL 183
specify blocks (cont’d)
Timing Checks
$setup check
Syntax:
$setup(data_event, reference_event, limit);
2005 Verilog HDL 184
specify blocks (cont’d)
Timing Checks
$hold check
Syntax:
$hold(reference_event, data_event, limit);
2005 Verilog HDL 185
specify blocks (cont’d)
Timing Checks
$width check
Syntax:
$width(reference_event, limit);
2005 Verilog HDL 186
Today Summary
Delays
Models
Inertial (distributed and lumped delay)
Transport (path/pin-to-pin delay)
Types
Rise/Fall/Turn-off
Min/Typ/Max Values
Delays in Verilog
Syntax and other common features
Gate-Level and Dataflow Modeling
Behavioral Modeling
2005 Verilog HDL 187
Other Notes
Homework 9
Chapter 10:
All exercises
Due date: Sunday, Day 11th
2005 Verilog HDL 188
Digital System Design
Verilog® HDL
Tasks and Functions
Maziar Goudarzi
Today program
Reusing code
Tasks and Functions
12/4/2022 Verilog HDL 190
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
12/4/2022 Verilog HDL 191
Contents
Functions
Tasks
Differences between tasks and functions
12/4/2022 Verilog HDL 192
Tasks and Functions
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
12/4/2022 Verilog HDL 194
Functions (cont’d)
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
12/4/2022 Verilog HDL 195
Functions (cont’d)
Function Declaration and Invocation
Invocation syntax:
<func_name> (<argument(s)>);
12/4/2022 Verilog HDL 196
Functions (cont’d)
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
12/4/2022 Verilog HDL 197
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
endmodule
always @(addr)
begin
parity = calc_parity(addr);
$display("Parity calculated = %b",
calc_parity(addr) );
end
12/4/2022 Verilog HDL 198
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
12/4/2022 Verilog HDL 199
//Define a factorial with a recursive
// Call the function
function
integer result;
module top;
initial
...
begin
// Define the function
result = factorial(4); // Call
function automatic integer factorial;
the factorial of 7
input [31:0] oper;
$display("Factorial of 4 is
integer i;
%0d", result); //Displays 24
begin
end
if (operand >= 2)
...
factorial = factorial (oper -1) * oper;
...
//recursive call
endmodule
else
factorial = 1 ;
end
endfunction
12/4/2022 Verilog HDL 200
Tasks and Functions
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
12/4/2022 Verilog HDL 202
Tasks (cont’d)
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
12/4/2022 Verilog HDL 203
Tasks (cont’d)
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
12/4/2022 Verilog HDL 204
Tasks (cont’d)
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
12/4/2022 Verilog HDL 205
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;
begin
initial #delay ab_and = a & b;
$monitor( …); ab_or = a | b;
ab_xor = a ^ b;
initial end
begin endtask
…
end
endmodule
always @(A or B)
begin
bitwise_oper(AB_AND, AB_OR,
AB_XOR, A, B);
end
12/4/2022 Verilog HDL 206
Task Examples
Use of module local variables
// clk2 runs at twice the frequency of clk // These two always blocks will
and is synchronous call the bitwise_xor task
// with clk.
// concurrently at each positive
module top;
reg [15:0] cd_xor, ef_xor; //variables in
edge of clk. However, since
module top // the task is re-entrant, these
reg [15:0] c, d, e, f; //variables in concurrent calls will work
module top
correctly.
-
task automatic bitwise_xor; always @(posedge clk)
output [15:0] ab_xor; //output from the bitwise_xor(ef_xor, e, f);
task
input [15:0] a, b; //inputs to the task
-
begin always @(posedge clk2) // twice the
#delay ab_and = a & b; frequency as the previous block
ab_or = a | b;
bitwise_xor(cd_xor, c, d);
ab_xor = a ^ b;
end -
endtask -
endmodule
12/4/2022 Verilog HDL 207
Tasks and Functions
Differences between
Tasks and Functions
Differences between...
Functions Tasks
Can enable (call) just Can enable other tasks
another function (not and functions
task) May execute in non-
Execute in 0 simulation zero simulation time
time May contain any timing
No timing control control statements
statements allowed May have arbitrary
At lease one input input, output, or
Return only a single inout
value Do not return any value
12/4/2022 Verilog HDL 209
Differences between… (cont’d)
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
12/4/2022 Verilog HDL 210
Differences between… (cont’d)
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
12/4/2022 Verilog HDL 211