0% found this document useful (0 votes)
11 views113 pages

Onur Digitaldesign 2019 Lecture7.2 HDL Afterlecture

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)
11 views113 pages

Onur Digitaldesign 2019 Lecture7.2 HDL Afterlecture

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/ 113

Design of Digital Circuits

Lecture 7.2: Hardware Description


Languages and Verilog
Prof. Onur Mutlu
ETH Zurich
Spring 2019
14 March 2019
Required Readings (This Week)
n Hardware Description Languages and Verilog
q H&H Chapter 4 in full

n Timing and Verification


q H&H Chapters 2.9 and 3.5 + (start Chapter 5)

n By tomorrow, make sure you are done with


q P&P Chapters 1-3 + H&H Chapters 1-4

2
Required Readings (Next Week)
n Von Neumann Model, LC-3, and MIPS
q P&P, Chapter 4, 5
q H&H, Chapter 6
q P&P, Appendices A and C (ISA and microarchitecture of LC-3)
q H&H, Appendix B (MIPS instructions)

n Programming
q P&P, Chapter 6

n Recommended: Digital Building Blocks


q H&H, Chapter 5

3
Agenda
n Hardware Description Languages

n Implementing Combinational Logic (in Verilog)

n Implementing Sequential Logic (in Verilog)

n The Verilog slides constitute a tutorial. We will not cover all.


n All slides will be beneficial for your labs.

4
Hardware Description Languages
& Verilog (Combinational Logic)

5
2017: Intel Kaby Lake
• 64-bit processor
• 4 cores, 8 threads
• 14-19 stage
pipeline
• 3.9 GHz clock
• 1.75B transistors
• In ~47 years,
about 1,000,000-
fold growth in
https://en.wikichip.org/wiki/intel/microarchitectures/kaby_lake transistor count
and performance!

6
How to Deal with This Complexity?
n Hardware Description Languages!

n A fact of life in computer engineering


q Need to be able to specify complex designs
n communicate with others in your design group
q … and to simulate their behavior
n yes, it’s what I want to build

q … and to synthesize (automatically design) portions of it


n have an error-free path to implementation

n Hardware Description Languages


q Many similarly featured HDLs (e.g., Verilog, VHDL, ...)
n if you learn one, it is not hard to learn another
n mapping between languages is typically mechanical, especially for
the commonly used subset
7
Hardware Description Languages
n Two well-known hardware description languages

n Verilog
q Developed in 1984 by Gateway Design Automation
q Became an IEEE standard (1364) in 1995
q More popular in US

n VHDL (VHSIC Hardware Description Language)


q Developed in 1981 by the US Department of Defense
q Became an IEEE standard (1076) in 1987
q More popular in Europe

n In this course we will use Verilog

8
Hardware Design Using Verilog

9
Hierarchical Design
https://techreport.com/review/21987/intel
n Design hierarchy of modules is built -core-i7-3960x-processor

using instantiation
q Predefined “primitive” gates (AND, OR, …)
q Simple modules are built by instantiating
these gates (components like MUXes)
q Other modules are built by instantiating
simple components, …
n Hierarchy controls complexity
q Analogous to the use of function
abstraction in SW
n Complexity is a BIG deal
q In real world how big is size of one “blob”
of random logic that we would describe as How many?

an HDL, then synthesize to gates?

10
Top-Down Design Methodology
n We define the top-level module and identify the
sub-modules necessary to build the top-level module
n Subdivide the sub-modules until we come to leaf cells
q Leaf cell: circuit components that cannot further be divided
(e.g., logic gates, cell libraries)
Top-level
Module

Sub-module Sub-module Sub-module

… … … …
Leaf-cell Leaf-cell Leaf-cell Leaf-cell

11
Bottom-Up Design Methodology
n We first identify the building blocks that are available to us
n Build bigger modules, using these building blocks
n These modules are then used for higher-level modules until
we build the top-level module in the design
Top-level
Module

Sub-module Sub-module Sub-module


… … … …

Leaf-cell Leaf-cell Leaf-cell Leaf-cell

12
Defining a Module in Verilog
n A module is the main building block in Verilog

n We first need to define:


q Name of the module
q Directions of its ports (e.g., input, output)
q Names of its ports
n Then:
q Describe the functionality of the module

a
Verilog
b example y
Module
c
inputs output

13
Implementing a Module in Verilog

a
Verilog
b example y
Module
c

name of Port list


module (inputs and outputs)

module example (a, b, c, y);


ports have a
input a;
declared type
input b;
input c;
output y; a module
definition
// here comes the circuit description

endmodule

14
A Question of Style

n The following two codes are functionally identical

module test ( a, b, y ); module test ( input a,


input a; input b,
input b; output y );
output y;
endmodule
endmodule

port name and direction declaration


can be combined

15
What If We Have Multi-bit Input/Output?
n You can also define multi-bit Input/Output (Bus)
q [range_end : range_start]
q Number of bits: range_end – range_start + 1
n Example:
input [31:0] a; // a[31], a[30] .. a[0]
output [15:8] b1; // b1[15], b1[14] .. b1[8]
output [7:0] b2; // b2[7], b2[6] .. b2[0]
input c; // single signal

n a represents a 32-bit value, so we prefer to define it as:


[31:0] a
n It is preferred over [0:31] a which resembles array definition
n It is good practice to be consistent with the representation
of multi-bit signals, i.e., always [31:0] or always [0:31]
16
Manipulating Bits
n Bit Slicing
n Concatenation
n Duplication

// You can assign partial buses


wire [15:0] longbus;
wire [7:0] shortbus;
assign shortbus = longbus[12:5];

// Concatenating is by {}
assign y = {a[2],a[1],a[0],a[0]};

// Possible to define multiple copies


assign x = {a[0], a[0], a[0], a[0]}
assign y = { 4{a[0]} }

17
Basic Syntax
n Verilog is case sensitive
q SomeName and somename are not the same!
n Names cannot start with numbers:
q 2good is not a valid name
n Whitespaces are ignored

// Single line comments start with a //

/* Multiline comments
are defined like this */

18
Two Main Styles of HDL Implementation
n Structural (Gate-Level)
q The module body contains gate-level description of the circuit
q Describe how modules are interconnected
q Each module contains other modules (instances)
q … and interconnections between these modules
q Describes a hierarchy

n Behavioral
q The module body contains functional description of the circuit
q Contains logical and mathematical operators
q Level of abstraction is higher than gate-level
n Many possible gate-level realizations of a behavioral description

n Practical circuits use a combination of both


19
Structural (Gate-Level) HDL

20
Structural HDL: Instantiating a Module

i_first
i_second

Schematic of module “top” that is built from


two instances of module “small”

21
Structural HDL Example
n Module Definitions in Verilog
module top (A, SEL, C, Y); i_first
input A, SEL, C; i_second

output Y;
wire n1;

module small (A, B, Y);


input A;
input B;
output Y;

endmodule // description of small

endmodule

22
Structural HDL Example
n Defining wires (module interconnections)
module top (A, SEL, C, Y); i_first
input A, SEL, C; i_second

output Y;
wire n1;

module small (A, B, Y);


input A;
input B;
output Y;

endmodule // description of small

endmodule

23
Structural HDL Example
n The first instantiation of the “small” module
module top (A, SEL, C, Y); i_first
input A, SEL, C; i_second

output Y;
wire n1;

// instantiate small once


small i_first ( .A(A),
.B(SEL),
.Y(n1) );
module small (A, B, Y);
input A;
input B;
output Y;

endmodule // description of small

endmodule

24
Structural HDL Example
n The second instantiation of the “small” module
module top (A, SEL, C, Y); i_first
input A, SEL, C; i_second

output Y;
wire n1;

// instantiate small once


small i_first ( .A(A),
.B(SEL),
.Y(n1) );
module small (A, B, Y);
// instantiate small second time input A;
small i_second ( .A(n1), input B;
.B(C), output Y;
.Y(Y) );
// description of small
endmodule
endmodule

25
Structural HDL Example
n Short form of module instantiation
module top (A, SEL, C, Y); i_first
input A, SEL, C; i_second

output Y;
wire n1;

// alternative
small i_first ( A, SEL, n1 );

/* Shorter instantiation,
pin order very important */ module small (A, B, Y);
input A;
// any pin order, safer choice input B;
small i_second ( .B(C), output Y;
.Y(Y),
.A(n1) ); // description of small

endmodule endmodule

Short form is not good practice


as it reduces code maintainability 26
Structural HDL Example 2
n Verilog supports basic logic gates as predefined primitives
q These primitives are instantiated like modules except that they
are predefined in Verilog and do not need a module definition

module mux2(input d0, d1,


input s,
output y);
wire ns, y1, y2;

not g1 (ns, s);


and g2 (y1, d0, ns);
and g3 (y2, d1, s);
or g4 (y, y1, y2);

endmodule

27
Behavioral HDL

28
Recall: Two Main Styles of HDL Implementation
n Structural (Gate-Level)
q The module body contains gate-level description of the circuit
q Describe how modules are interconnected
q Each module contains other modules (instances)
q … and interconnections between these modules
q Describes a hierarchy

n Behavioral
q The module body contains functional description of the circuit
q Contains logical and mathematical operators
q Level of abstraction is higher than gate-level
n Many possible gate-level realizations of a behavioral description

n Practical circuits would use a combination of both


29
Behavioral HDL: Defining Functionality
module example (a, b, c, y);
input a;
input b;
input c;
output y;

// here comes the circuit description


assign y = ~a & ~b & ~c |
a & ~b & ~c |
a & ~b & c;

endmodule

30
Behavioral HDL: Schematic View
A behavioral implementation still models a
hardware circuit!

a AND

AND OR y
b

AND
c

31
Bitwise Operators in Behavioral Verilog
module gates(input [3:0] a, b,
output [3:0] y1, y2, y3, y4, y5);

/* Five different two-input logic


gates acting on 4 bit buses */

assign y1 = a & b; // AND


assign y2 = a | b; // OR
assign y3 = a ^ b; // XOR
assign y4 = ~(a & b); // NAND
assign y5 = ~(a | b); // NOR

endmodule

32
Bitwise Operators: Schematic View

33
Reduction Operators in Behavioral Verilog
module and8(input [7:0] a,
output y);

assign y = &a;

// &a is much easier to write than


// assign y = a[7] & a[6] & a[5] & a[4] &
// a[3] & a[2] & a[1] & a[0];

endmodule

34
Reduction Operators: Schematic View

[0]
[1]

[2]

[3]
[7:0]
a[7:0] [4]
AND y
[5]
[6]
[7] 8-input AND gate

35
Conditional Assignment in Behavioral Verilog
module mux2(input [3:0] d0, d1,
input s,
output [3:0] y);

assign y = s ? d1 : d0;
// if (s) then y=d1 else y=d0;

endmodule

n ? : is also called a ternary operator as it operates on three


inputs:
q s
q d1
q d0

36
Conditional Assignment: Schematic View

37
More Complex Conditional Assignments
module mux4(input [3:0] d0, d1, d2, d3
input [1:0] s,
output [3:0] y);

assign y = s[1] ? ( s[0] ? d3 : d2)


: ( s[0] ? d1 : d0);
// if (s1) then
// if (s0) then y=d3 else y=d2
// else
// if (s0) then y=d1 else y=d0

endmodule

38
Even More Complex Conditional Assignments
module mux4(input [3:0] d0, d1, d2, d3
input [1:0] s,
output [3:0] y);

assign y = (s == 2’b11) ? d3 :
(s == 2’b10) ? d2 :
(s == 2’b01) ? d1 :
d0;
// if (s = “11” ) then y= d3
// else if (s = “10” ) then y= d2
// else if (s = “01” ) then y= d1
// else y= d0

endmodule

39
Precedence of Operations in Verilog
Highest

Lowest

40
How to Express Numbers ?
N Bxx
8 b0000_0001
n (N) Number of bits
q Expresses how many bits will be used to store the value

n (B) Base
q Can be b (binary), h (hexadecimal), d (decimal), o (octal)

n (xx) Number
q The value expressed in base
q Can also have X (invalid) and Z (floating), as values
q Underscore _ can be used to improve readability
41
Number Representation in Verilog

Verilog Stored Number Verilog Stored Number

4’b1001 1001 4’d5 0101

8’b1001 0000 1001 12’hFA3 1111 1010 0011

8’b0000_1001 0000 1001 8’o12 00 001 010

8’bxX0X1zZ1 XX0X 1ZZ1 4’h7 0111

‘b01 0000 .. 0001 12’h0 0000 0000 0000

32 bits
(default)

42
Reminder: Floating Signals (Z)
n Floating signal: Signal that is not driven by any circuit
q Open circuit, floating wire
n Also known as: high impedance, hi-Z, tri-stated signals
module tristate_buffer(input [3:0] a,
input en,
output [3:0] y);

assign y = en ? a : 4'bz;

endmodule

en
[3:0] [3:0] [3:0] [3:0]
a[3:0] y[3:0]

y_1[3:0]
43
Recall: Tri-State Buffer
n A tri-state buffer enables gating of different signals onto a
wire

44
Recall: Example Use of Tri-State Buffers
n Imagine a wire connecting the CPU and memory

q At any time only the CPU or the memory can place a value on
the wire, both not both

q You can have two tri-state buffers: one driven by CPU, the
other memory; and ensure at most one is enabled at any time

45
Recall: Example Design with Tri-State Buffers

GateCPU

CPU

GateMem

Memory
Shared Bus

46
Truth Table for AND with Z and X

A
AND
0 1 Z X

0 0 0 0 0

1 0 1 X X
B Z 0 X X X

X 0 X X X

47
What Happens with HDL Code?
n Synthesis
q Modern tools are able to map synthesizable HDL code into
low-level cell libraries à netlist describing gates and wires
q They can perform many optimizations
q … however they can not guarantee that a solution is optimal
n Mainly due to computationally expensive placement and routing
algorithms
q Most common way of Digital Design these days

n Simulation
q Allows the behavior of the circuit to be verified without
actually manufacturing the circuit
q Simulators can work on structural or behavioral HDL

48
Recall This “example”
module example (a, b, c, y);
input a;
input b;
input c;
output y;

// here comes the circuit description


assign y = ~a & ~b & ~c |
a & ~b & ~c |
a & ~b & c;

endmodule

49
Synthesizing the “example”

a AND

AND OR y
b

AND
c

50
Simulating the “example”
AND
a

AND OR y
b

AND
c

1
signals

1
1
0

Waveform Diagram time


51
What We Have Seen So Far
n Describing structural hierarchy with Verilog
q Instantiate modules in an other module
n Describing functionality using behavioral modeling

n Writing simple logic equations


q We can write AND, OR, XOR, …
n Multiplexer functionality
q If … then … else

n We can describe constants

n But there is more...


52
More Verilog Examples

n We can write Verilog code in many different ways

n Let’s see how we can express the same functionality by


developing Verilog code

q At low-level
n Poor readability
n More optimization opportunities (especially for low-level tools)

q At a higher-level of abstraction
n Better readability
n Limited optimization opportunities

53
Comparing Two Numbers
n Defining your own gates as new modules

n We will use our gates to show the different ways of


implementing a 4-bit comparator (equality checker)

An XNOR gate An AND gate


module MyXnor (input A, B, module MyAnd (input A, B,
output Z); output Z);

assign Z = ~(A ^ B); //not XOR assign Z = A & B; // AND

endmodule endmodule

54
Gate-Level Implementation
module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3, c01, c23;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR
MyAnd haha (.A(c0), .B(c1), .Z(c01) ); // AND
MyAnd hoho (.A(c2), .B(c3), .Z(c23) ); // AND
MyAnd bubu (.A(c01), .B(c23), .Z(eq) ); // AND

endmodule

55
Using Logical Operators
module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3, c01, c23;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR
assign c01 = c0 & c1;
assign c23 = c2 & c3;
assign eq = c01 & c23;

endmodule

56
Eliminating Intermediate Signals
module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR
// assign c01 = c0 & c1;
// assign c23 = c2 & c3;
// assign eq = c01 & c23;
assign eq = c0 & c1 & c2 & c3;

endmodule

57
Multi-Bit Signals (Bus)
module compare (input [3:0] a, input [3:0] b,
output eq);
wire [3:0] c; // bus definition

MyXnor i0 (.A(a[0]), .B(b[0]), .Z(c[0]) ); // XNOR


MyXnor i1 (.A(a[1]), .B(b[1]), .Z(c[1]) ); // XNOR
MyXnor i2 (.A(a[2]), .B(b[2]), .Z(c[2]) ); // XNOR
MyXnor i3 (.A(a[3]), .B(b[3]), .Z(c[3]) ); // XNOR

assign eq = &c; // short format

endmodule

58
Bitwise Operations
module compare (input [3:0] a, input [3:0] b,
output eq);
wire [3:0] c; // bus definition

// MyXnor i0 (.A(a[0]), .B(b[0]), .Z(c[0]) );


// MyXnor i1 (.A(a[1]), .B(b[1]), .Z(c[1]) );
// MyXnor i2 (.A(a[2]), .B(b[2]), .Z(c[2]) );
// MyXnor i3 (.A(a[3]), .B(b[3]), .Z(c[3]) );

assign c = ~(a ^ b); // XNOR

assign eq = &c; // short format

endmodule

59
Highest Abstraction Level: Comparing Two Numbers

module compare (input [3:0] a, input [3:0] b,


output eq);

// assign c = ~(a ^ b); // XNOR

// assign eq = &c; // short format

assign eq = (a == b) ? 1 : 0; // really short

endmodule

60
Writing More Reusable Verilog Code
n We have a module that can compare two 4-bit numbers

n What if in the overall design we need to compare:


q 5-bit numbers?
q 6-bit numbers?
q …
q N-bit numbers?
q Writing code for each case looks tedious

n What could be a better way?

61
Parameterized Modules

In Verilog, we can define module parameters

module mux2
#(parameter width = 8) // name and default value
(input [width-1:0] d0, d1,
input s,
output [width-1:0] y);

assign y = s ? d1 : d0;
endmodule

We can set the parameters to different values


when instantiating the module

62
Instantiating Parameterized Modules
module mux2
#(parameter width = 8) // name and default value
(input [width-1:0] d0, d1,
input s,
output [width-1:0] y);

assign y = s ? d1 : d0;
endmodule

// If the parameter is not given, the default (8) is assumed


mux2 i_mux (d0, d1, s, out);

// The same module with 12-bit bus width:


mux2 #(12) i_mux_b (d0, d1, s, out);

// A more verbose version:


mux2 #(.width(12)) i_mux_b (.d0(d0), .d1(d1),
.s(s), .out(out));

63
What About Timing?
n It is possible to define timing relations in Verilog. BUT:
q These are ONLY for simulation

q They CAN NOT be synthesized

q They are used for modeling delays in a circuit

‘timescale 1ns/1ps
module simple (input a, output z1, z2);

assign #5 z1 = ~a; // inverted output after 5ns


assign #9 z2 = a; // output after 9ns

endmodule

More to come later today!

65
Good Practices
n Develop/use a consistent naming style

n Use MSB to LSB ordering for buses


q Use a[31:0] , not a[0:31]

n Define one module per file


q Makes managing your design hierarchy easier

n Use a file name that equals module name


q e.g., module TryThis is defined in a file called TryThis.v

n Always keep in mind that Verilog describes hardware


66
Summary (HDL for Combinational Logic)

n We have seen an overview of Verilog

n Discussed structural and behavioral modeling

n Showed combinational logic constructs

67
Implementing Sequential Logic
Using Verilog

68
Combinational + Memory = Sequential

Sequential Circuit

outputs
inputs

Combinational
Circuit

Storage
Element

69
Sequential Logic in Verilog
n Define blocks that have memory
q Flip-Flops, Latches, Finite State Machines

n Sequential Logic state transition is triggered by a “CLOCK”


signal
q Latches are sensitive to level of the signal
q Flip-flops are sensitive to the transitioning of signal

n Combinational constructs are not sufficient


q We need new constructs:
n always
n posedge/negedge

70
The “always” Block

always @ (sensitivity list)


statement;

Whenever the event in the sensitivity list occurs,


the statement is executed

71
Example: D Flip-Flop
module flop(input clk,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk)


q <= d; // pronounced “q gets d”

endmodule

n posedge defines a rising edge (transition from 0 to 1).

n Statement executed when the clk signal rises (posedge of clk)

n Once the clk signal rises: the value of d is copied to q

72
Example: D Flip-Flop
module flop(input clk,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk)


q <= d; // pronounced “q gets d”

endmodule

n assign statement is not used within an always block


n <= describes a non-blocking assignment
q We will see the difference between blocking assignment and
non-blocking assignment soon

73
Example: D Flip-Flop
module flop(input clk,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk)


q <= d; // pronounced “q gets d”

endmodule

n Assigned variables need to be declared as reg


n The name reg does not necessarily mean that the value is a
register (It could be, but it does not have to be)
n We will see examples later

74
Asynchronous and Synchronous Reset
n Reset signals are used to initialize the hardware to a known
state
q Usually activated at system start (on power up)

n Asynchronous Reset
q The reset signal is sampled independent of the clock
q Reset gets the highest priority
q Sensitive to glitches, may have metastability issues
n Will be discussed in Lecture 8

n Synchronous Reset
q The reset signal is sampled with respect to the clock
q The reset should be active long enough to get sampled at the
clock edge
q Results in completely synchronous circuit
75
D Flip-Flop with Asynchronous Reset
module flop_ar (input clk,
input reset,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk, negedge reset)


begin
if (reset == 0) q <= 0; // when reset
else q <= d; // when clk
end
endmodule

n In this example: two events can trigger the process:


q A rising edge on clk

q A falling edge on reset

76
D Flip-Flop with Asynchronous Reset
module flop_ar (input clk,
input reset,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk, negedge reset)


begin
if (reset == 0) q <= 0; // when reset
else q <= d; // when clk
end
endmodule

n For longer statements, a begin-end pair can be used


q To improve readability
q In this example, it was not necessary, but it is a good idea

77
D Flip-Flop with Asynchronous Reset
module flop_ar (input clk,
input reset,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk, negedge reset)


begin
if (reset == 0) q <= 0; // when reset
else q <= d; // when clk
end
endmodule

n First reset is checked: if reset is 0, q is set to 0.


q This is an asynchronous reset as the reset can happen
independently of the clock (on the negative edge of reset signal)
n If there is no reset, then regular assignment takes effect

78
D Flip-Flop with Synchronous Reset
module flop_sr (input clk,
input reset,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk)


begin
if (reset == ‘0’) q <= 0; // when reset
else q <= d; // when clk
end
endmodule

n The process is sensitive to only clock


q Reset happens only when the clock rises. This is a
synchronous reset

79
D Flip-Flop with Enable and Reset
module flop_en_ar (input clk,
input reset,
input en,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk, negedge reset)


begin
if (reset == ‘0’) q <= 0; // when reset
else if (en) q <= d; // when en AND clk
end
endmodule

n A flip-flop with enable and reset


q Note that the en signal is not in the sensitivity list

n q gets d only when clk is rising and en is 1

80
Example: D Latch

module latch (input clk,


input [3:0] d,
output reg [3:0] q);

always @ (clk, d)
if (clk) q <= d; // latch is transparent when
// clock is 1
endmodule

81
Summary: Sequential Statements So Far
n Sequential statements are within an always block

n The sequential block is triggered with a change in the


sensitivity list

n Signals assigned within an always must be declared as reg

n We use <= for (non-blocking) assignments and do not use


assign within the always block.

82
Basics of always Blocks
module example (input clk,
input [3:0] d,
output reg [3:0] q);

wire [3:0] normal; // standard wire


reg [3:0] special; // assigned in always

always @ (posedge clk)


special <= d; // first FF array

assign normal = ~ special; // simple assignment

always @ (posedge clk)


q <= normal; // second FF array
endmodule

You can have as many always blocks as needed


Assignment to the same signal in different always blocks is not allowed!

83
Why Does an always Block Remember?
module flop (input clk,
input [3:0] d,
output reg [3:0] q);

always @ (posedge clk)


begin
q <= d; // when clk rises copy d to q
end
endmodule

n This statement describes what happens to signal q


n … but what happens when the clock is not rising?
n The value of q is preserved (remembered)

84
An always Block Does NOT Always Remember
module comb (input inv,
input [3:0] data,
output reg [3:0] result);

always @ (inv, data) // trigger with inv, data


if (inv) result <= ~data;// result is inverted data
else result <= data; // result is data

endmodule

n This statement describes what happens to signal result


q When inv is 1, result is ~data
q When inv is not 1, result is data
n The circuit is combinational (no memory)
q result is assigned a value in all cases of the if .. else block, always

85
always Blocks for Combinational Circuits
n An always block defines combinational logic if:
q All outputs are always (continuously) updated
1. All right-hand side signals are in the sensitivity list
n You can use always @* for short
2. All left-hand side signals get assigned in every possible condition
of if .. else and case blocks

n It is easy to make mistakes and unintentionally describe


memorizing elements (latches)
q Vivado will most likely warn you. Make sure you check the
warning messages

n Always blocks allow powerful combinational logic statements


q if .. else
q case
86
Sequential or Combinational?

wire enable, data; wire enable, data;


reg out_a, out_b; reg out_a, out_b;

always @ (*) begin always @ (data) begin


out_a = 1’b0; out_a = 1’b0;
if(enable) begin out_b = 1’b0;
out_a = data; if(enable) begin
out_b = data; out_a = data;
end out_b = data;
end end
No assignment for ~enable
end Not in the sensitivity list

Sequential Sequential

87
The always Block is NOT Always Practical/Nice
reg [31:0] result;
wire [31:0] a, b, comb;
wire sel,

always @ (a, b, sel) // trigger with a, b, sel


if (sel) result <= a; // result is a
else result <= b; // result is b

assign comb = sel ? a : b;

n Both statements describe the same multiplexer

n In this case, the always block is more work

88
always Block for Case Statements (Handy!)
module sevensegment (input [3:0] data,
output reg [6:0] segments);

always @ ( * ) // * is short for all signals


case (data) // case statement
4'd0: segments = 7'b111_1110; // when data is 0
4'd1: segments = 7'b011_0000; // when data is 1
4'd2: segments = 7'b110_1101;
4'd3: segments = 7'b111_1001;
4'd4: segments = 7'b011_0011;
4'd5: segments = 7'b101_1011;
// etc etc
default: segments = 7'b000_0000; // required
endcase

endmodule

89
Summary: always Block
n if .. else can only be used in always blocks

n The always block is combinational only if all regs within the


block are always assigned to a signal
q Use the default case to make sure you do not forget an
unimplemented case, which may otherwise result in a latch

n Use casex statement to be able to check for don’t cares

90
Non-Blocking and Blocking Assignments
Non-blocking (<=) Blocking (=)
always @ (a) always @ (a)
begin begin
a <= 2’b01; a = 2’b01;
b <= a; // a is 2’b01
// all assignments are made here b = a;
// b is not (yet) 2’b01 // b is now 2’b01 as well
end end

n All assignments are made n Each assignment is made


at the end of the block immediately
n All assignments are made n Process waits until the first
in parallel, process flow is assignment is complete, it
not-blocked blocks progress

91
Example: Blocking Assignment

n Assume all inputs are initially ‘0’

always @ ( * )
begin
p = a ^ b ; // p = 0 1
g = a & b ; // g = 0 0
s = p ^ cin ; // s = 0 1
cout = g | (p & cin) ; // cout = 0 0
end

n If a changes to ‘1’
q All values are updated in order

93
The Same Example: Non-Blocking Assignment

n Assume all inputs are initially ‘0’

always @ ( * )
begin
p <= a ^ b ; // p = 0 1
g <= a & b ; // g = 0 0
s <= p ^ cin ; // s = 0 0
cout <= g | (p & cin) ; // cout = 0 0
end

n If a changes to ‘1’
q All assignments are concurrent
q When s is being assigned, p is still 0

94
The Same Example: Non-Blocking Assignment

n After the first iteration, p has changed to ‘1’ as well

always @ ( * )
begin
p <= a ^ b ; // p = 1 1
g <= a & b ; // g = 0 0
s <= p ^ cin ; // s = 0 1
cout <= g | (p & cin) ; // cout = 0 0
end

n Since there is a change in p, the process triggers again


n This time s is calculated with p=1

95
Rules for Signal Assignment
n Use always @(posedge clk) and non-blocking
assignments (<=) to model synchronous sequential logic

always @ (posedge clk)


q <= d; // non-blocking

n Use continuous assignments (assign) to model simple


combinational logic.

assign y = a & b;

96
Rules for Signal Assignment (Cont.)

n Use always @ (*) and blocking assignments (=) to model


more complicated combinational logic.

n You cannot make assignments to the same signal in more


than one always block or in a continuous assignment
always @ (*) always @ (*)
a = b; a = b;

always @ (*) assign a = c;


a = c;

97
Recall: Finite State Machines (FSMs)
n Each FSM consists of three separate parts:
q next state logic
q state register
q output logic

CLK
M next
next k state k output N
inputs state
state
outputs
logic
logic

state register

98
Recall: Finite State Machines (FSMs) Comprise
n Sequential circuits CLK

q State register(s)
n Store the current state and S’ S
Next Current
n Load the next state at the clock edge State State

n Combinational Circuits Next State


Logic
q Next state logic
n Determines what the next state will be CL Next
State

Output
q Output logic Logic
n Generates the outputs
CL Outputs

99
FSM Example 1: Divide the Clock Frequency by 3

The output Y is HIGH for one clock cycle out of every 3. In other
words, the output divides the frequency of the clock by 3.

100
Implementing FSM Example 1: Definitions
module divideby3FSM (input clk,
input reset,
output q);

reg [1:0] state, nextstate;

parameter S0 = 2'b00;
parameter S1 = 2'b01;
parameter S2 = 2'b10;

n We define state and nextstate as 2-bit reg


n The parameter descriptions are optional, it makes reading
easier

101
Implementing FSM Example 1: State Register
CLK

S’ S
Next Current
State State

// state register
always @ (posedge clk, posedge reset)
if (reset) state <= S0;
else state <= nextstate;

n This part defines the state register (memorizing process)


n Sensitive to only clk, reset
n In this example, reset is active when it is ‘1’ (active-high)

102
Implementing FSM Example 1: Next State Logic

CLK
M next
next k state k output N
inputs state
state
outputs
logic
logic

// next state logic


always @ (*)
case (state)
S0: nextstate = S1;
S1: nextstate = S2;
S2: nextstate = S0;
default: nextstate = S0;
endcase

103
Implementing FSM Example 1: Output Logic

CLK
M next
next k state k output N
inputs state
state
outputs
logic
logic

// output logic
assign q = (state == S0);

n In this example, output depends only on state


q Moore type FSM
104
Implementation of FSM Example 1
module divideby3FSM (input clk, input reset, output q);
reg [1:0] state, nextstate;

parameter S0 = 2'b00; parameter S1 = 2'b01; parameter S2 = 2'b10;

always @ (posedge clk, posedge reset) // state register


if (reset) state <= S0;
else state <= nextstate;

always @ (*) // next state logic


case (state)
S0: nextstate = S1;
S1: nextstate = S2;
S2: nextstate = S0;
default: nextstate = S0;
endcase
assign q = (state == S0); // output logic
endmodule

105
Design of Digital Circuits
Lecture 7.2: Hardware Description
Languages and Verilog
Prof. Onur Mutlu
ETH Zurich
Spring 2019
14 March 2019
We did not cover the following.
They are for your preparation.

107
FSM Example 2: Smiling Snail
n Alyssa P. Hacker has a snail that crawls down a paper tape
with 1’s and 0’s on it.
n The snail smiles whenever the last four digits it has crawled
over are 1101.
n Design Moore and Mealy FSMs of the snail’s brain.

Moore

Mealy

108
Implementing FSM Example 2: Definitions
module SmilingSnail (input clk,
input reset,
input number,
output smile);

reg [1:0] state, nextstate;

parameter S0 = 2'b00;
parameter S1 = 2'b01;
parameter S2 = 2'b10;
parameter S3 = 2’b11;

number/smile

109
Implementing FSM Example 2: State Register

// state register
always @ (posedge clk, posedge reset)
if (reset) state <= S0;
else state <= nextstate;

n This part defines the state register (memorizing process)

n Sensitive to only clk, reset

n In this example reset is active when ‘1’ (active-high)

110
Implementing FSM Example 2: Next State Logic
// next state logic
always @ (*)
case (state)
S0: if (number) nextstate = S1;
else nextstate = S0;
S1: if (number) nextstate = S2;
else nextstate = S0;
S2: if (number) nextstate = S2;
else nextstate = S3;
S3: if (number) nextstate = S1;
else nextstate = S0;
default: nextstate = S0;
endcase

111
Implementing FSM Example 2: Output Logic

// output logic
assign smile = (number & state == S3);

n In this example, output depends on state and input


q Mealy type FSM

n We used a simple combinational assignment

112
Implementation of FSM Example 2
module SmilingSnail (input clk, always @ (*) // next state logic
input reset, case (state)
input number, S0: if (number)
output smile); nextstate = S1;
else nextstate = S0;
reg [1:0] state, nextstate; S1: if (number)
nextstate = S2;
parameter S0 = 2'b00; else nextstate = S0;
parameter S1 = 2'b01; S2: if (number)
parameter S2 = 2'b10; nextstate = S2;
parameter S3 = 2’b11; else nextstate = S3;
S3: if (number)
// state register nextstate = S1;
always @ (posedge clk, posedge else nextstate = S0;
reset) default: nextstate = S0;
if (reset) state <= S0; endcase
else state <= nextstate; // output logic
assign smile = (number & state==S3);

endmodule

113
What Did We Learn?
n Basics of defining sequential circuits in Verilog

n The always statement


q Needed for defining memorizing elements (flip-flops, latches)
q Can also be used to define combinational circuits

n Blocking vs Non-blocking statements


q = assigns the value immediately
q <= assigns the value at the end of the block

n Writing FSMs
q Next state logic
q State assignment
q Output logic
114
Next Lecture:
Timing and Verification

115

You might also like