0% found this document useful (0 votes)
2 views99 pages

03_systemverilog

The document covers the fundamentals of digital logic and SystemVerilog as part of the CIS 5710 course on Computer Organization and Design. It discusses key concepts such as transistors, fabrication, digital logic basics, and hardware design methods, including the use of FPGAs and hardware description languages like SystemVerilog. The document also emphasizes the importance of logic gates, Boolean functions, and the design flow for hardware implementation.

Uploaded by

qyx
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)
2 views99 pages

03_systemverilog

The document covers the fundamentals of digital logic and SystemVerilog as part of the CIS 5710 course on Computer Organization and Design. It discusses key concepts such as transistors, fabrication, digital logic basics, and hardware design methods, including the use of FPGAs and hardware description languages like SystemVerilog. The document also emphasizes the importance of logic gates, Boolean functions, and the design flow for hardware implementation.

Uploaded by

qyx
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/ 99

Digital Logic &

SystemVerilog
CIS 5710
Computer Organization & Design
This Unit: Digital Logic & Verilog
App App App • Transistors & fabrication
System software
• Digital logic basics
Mem CPU I/O • Focus on useful components
• Hardware design methods
• Introduction to Verilog

CIS 5710 | Prof Joseph Devietti 2


Readings
• Digital logic
• P&H, Appendix C
• Manufacturing
• P&H, Section 1.7
• Introduction to Logic Synthesis using Verilog
HDL, Reese & Thornton

CIS 5710 | Prof Joseph Devietti 3


Motivation: Implementing a Datapath
datapath

fetch

Insn Register Data


PC
memory File Memory

control
• Fetch: get insn, translate opcode into control
• Datapath: performs computation
• registers, ALUs, etc.
• Control: which computation to perform
• Routes data through datapath (which regs, which ALU op)
• Fetch ® Decode ® Execute “cycle” 4
Two Types of Components
datapath

fetch

Insn Register Data


PC
memory File Memory

control
• combinational/combinatorial
• stateless computation
• ALUs, muxes, control logic, arbitrary Boolean functions
• sequential
• storage: PC, insn/data memories, register file
• internally contain some combinational components
CIS 5710 | Prof Joseph Devietti 5
Example LC4 Datapath

CIS 5710 | Prof Joseph Devietti 6


Transistors & Fabrication

CIS 5710 | Prof Joseph Devietti 7


Intel
Pentium M
Wafer

CIS 5710 | Prof Joseph Devietti 8


Semiconductor Technology
gate gate
insulator
source drain source drain
substrate channel
channel
• Basic technology element: MOSFET
• Solid-state component acts like electrical switch
• MOS: metal-oxide-semiconductor
• FET: field-effect transistor
• Connects source®drain only when voltage applied to gate
• Channel length: key parameter (short ® fast)
• Aka “feature size” or “technology node”
• Currently: “5 nanometers (nm)”
• Continued miniaturization (scaling) known as Moore’s Law

CIS 5710 | Prof Joseph Devietti 9


Transistors and Wires

©IBM
From slides © Krste Asanović, MIT
CIS 5710 | Prof Joseph Devietti 10
Complementary MOS (CMOS)
• Voltages as values
• Power (VDD) = “1”, Ground = “0” power (1)

• Two kinds of MOSFETs p-transistor

• N-transistors input output


• Conduct when gate voltage is 1 (“node”)

• Good at passing 0s n-transistor


• P-transistors
ground (0)
• Conduct when gate voltage is 0
• Good at passing 1s
• CMOS
• Complementary n-/p- networks form boolean logic gates
• And some non-gate elements too (e.g., RAMs)
CIS 5710 | Prof Joseph Devietti 11
Basic CMOS Logic Gate
• Inverter: NOT gate
• One p-transistor, one n-transistor
• Basic operation 0
1
• Input = 0
• P-transistor closed, n-transistor
open
• Power charges output (1)
• Input = 1
• P-transistor open, n-transistor
closed 1 0
• Output discharges to ground (0)

12
Digital Building Blocks: Logic Gates
• Logic gates implement Boolean functions
• Basic gates: NOT, NAND, NOR
• Underlying CMOS transistors are naturally inverting ( = NOT)
NOT (Inverter) NAND NOR
A A
A A’ (AB)’ (A | B)’
B B

• NAND, NOR are “Boolean complete”


AND OR XOR
A
A A A|B AB’ | A’B
AB B
B B (A^B)

CIS 5710 | Prof Joseph Devietti 16


Digital Logic Review

CIS 5710 | Prof Joseph Devietti 17


Boolean Functions and Truth Tables
• Any Boolean function can be represented as a
truth table
• Truth table: point-wise input ® output mapping
• Function is disjunction of all rows in which “Out” is 1
A,B,C ® Out
0,0,0 ® 0
0,0,1 ® 0
0,1,0 ® 0
0,1,1 ® 0
1,0,0 ® 0
1,0,1 ® 1
1,1,0 ® 1
1,1,1 ® 1
• Example above: Out = AB’C | ABC’ | ABC
CIS 5710 | Prof Joseph Devietti 18
Truth Tables and PLAs
• Implement Boolean function by implementing its
truth table
• Takes two levels of logic
• Assumes inputs and inverses of inputs are available
(usually are)
• First level: ANDs (product terms)
• Second level: ORs (sums of product terms)

• PLA (Programmable Logic Array)


• Flexible circuit for doing this

CIS 5710 | Prof Joseph Devietti 19


PLA Example
• PLA with 3 inputs, 2 outputs, and 4 product terms
• Out0 = AB’C | ABC’ | ABC
A Permanent
B connections

Programmable
connections

Out0

Out1

CIS 5710 | Prof Joseph Devietti 20


Boolean Algebra
• rules for rewriting Boolean functions
• Useful for simplifying Boolean functions
• reduce gate count, reduce gate levels/depth
• Identity: A1 = A, A | 0 = A
• 0/1: A0 = 0, A | 1 = 1
• Inverses: (A’)’ = A
• Idempotency: AA = A, A | A = A
• Tautology: AA’ = 0, A | A’ = 1
• Commutativity: AB = BA, A | B = B | A
• Associativity: A(BC) = (AB)C, A | (B | C) = (A | B) | C
• Distributivity: A(B | C) = AB | AC, A | (BC) = (A | B)(A | C)
• DeMorgan’s: (AB)’ = A’ | B’, (A | B)’ = A’B’

CIS 5710 | Prof Joseph Devietti 21


Logic Minimization
• Logic minimization
• Repeatedly apply rules to reduce function to simplest form
• Design tools do this automatically

Out = AB’C | ABC’ | ABC


Out = A(B’C | BC’ | BC) // distributivity
Out = A(B’C | (BC’ | BC)) // associativity
Out = A(B’C | B(C’ | C)) // distributivity (on B)
Out = A(B’C | B1) // tautology
Out = A(B’C | B) // 0/1
Out = A((B’ | B)(C | B)) // distributivity (on | B)
Out = A(1(B | C)) // tautology
Out = A(B | C) // 0/1

CIS 5710 | Prof Joseph Devietti 22


Non-Arbitrary Boolean Functions
• PLAs implement Boolean functions point-wise
• E.g., represent f(X) = X+5 as [0®5, 1®6, 2®7, 3®8, …]
• Mainly useful for “arbitrary” functions, no compact
representation

• Many useful Boolean functions are not arbitrary


• Have lots of internal structure we can exploit
• Examples
• Multiplexer
• Adder

CIS 5710 | Prof Joseph Devietti 23


Multiplexer (Mux)
• selects one output from N inputs
• Example: 1-bit 4-to-1 mux
• wider inputs: N-bit 4-to-1 mux = N 1-bit 4-to-1 muxes
S (binary)
S (1-hot)
S (binary)
A
A
B
O
B C
O D

D
CIS 5710 | Prof Joseph Devietti 24
Adder
• Adder: adds/subtracts two binary integers in
two’s complement format
• Half adder: adds two 1-bit “integers”, no carry-in
• Full adder: adds three 1-bit “integers”, includes carry-in
• Ripple-carry adder: N chained full adders add 2 N-bit
integers
• To subtract: negate B input, set bit 0 carry-in to 1

25
Full Adder
• What is the logic for a full adder?
• Look at truth table CI

CI A B ® C0 S
® S
0 0 0 0 0 CI
0 0 1 ® 0 1 A
A S
0 1 0 ® 0 1 B FA
0 1 1 ® 1 0 B
1 0 0 ® 0 1 CO
1 0 1 ® 1 0
1 1 0 ® 1 0
1 1 1 ® 1 1 CO

• S = C’A’B | C’AB’ | CA’B’ | CAB = C ^ A ^ B


• CO = C’AB | CA’B | CAB’ | CAB = CA | CB | AB

CIS 5710 | Prof Joseph Devietti 26


N-bit Ripple-carry adder/subtracter
0
1
A0 S0
FA
B0

A1 S1 A
FA +/- S
B1 B
+/–

AN-1 SN-1
FA
BN-1

+/–
• More later when we cover arithmetic!
CIS 5710 | Prof Joseph Devietti 27
FPGAs

CIS 5710 | Prof Joseph Devietti 28


Alternative to fabrication: FPGA
• FPGAs (Field Programmable Gate Array)
• Also called Programmable Logic Devices (PLDs)
• An FPGA is a special type of programmable chip
• Conceptually, contains a grid of gates
• The wires connecting them can be reconfigured electrically
• Using more transistors as switches
• Once configured, an FPGA can emulate any digital design
• Tool converts gate-level design to configuration
• Uses
• Hardware prototyping (what we’re doing)
• Low-volume special-purpose hardware
• Network processing
• Cloud FPGAs in AWS & Azure
CIS 5710 | Prof Joseph Devietti 29
FPGA
• A Field Programmable Gate Array contains a collection of configurable logic
elements and a programmable interconnect that can be set up to perform the
desired logical operations.
Configurable Logic Blocks (CLBs)

Programmable Interconnect

30
Configurable Logic Blocks
• Each of the configurable logic blocks (or logic cells) contains some lookup
tables and one or more flip-flops.
• By setting the entries in the lookup tables (LUTs) these units can be
programmed to implement arbitrary logical functions on their inputs.
• http://en.wikipedia.org/wiki/Field-programmable_gate_array
• ZedBoard has 85K logic cells

CIS 5710 | Prof Joseph Devietti 31


Configuring FPGAs
• By configuring the CLBs and the interconnect the FPGA can be
‘programmed’ to implement the desired operation.
Configurable Logic Blocks (CLBs)

AND

AND

XOR XOR

NAND

NAND

Programmable Interconnect

CIS 5710 | Prof Joseph Devietti 32


FPGA “Design Flow”

a tic is
st lys
a
an
netlist
SystemVerilog (wires, implementation
synthesis bitstream
code gates, (place & route)
FFs)

sim
ula
tio
n

• Hardware compilers are generally much slower


than their software counterparts
• solving harder problems: many more choices, optimizing for
area, power, picosecond-level timing

CIS 5710 | Prof Joseph Devietti 33


Simulation
• Common way to test and debug designs
• Need a testbench to drive the hardware
• View system behavior via waveforms

CIS 5710 | Prof Joseph Devietti 34


Hardware Design Methods

CIS 5710 | Prof Joseph Devietti 35


Hardware Design Methods
• Fabricating a chip requires a detailed layout
• All transistors & wires
• Use Computer-Aided Design (CAD) tools
• Hand optimization still done for important parts
• Different levels of abstraction
• Transistor-level design – specify transistors (not layout)
• Gate-level design – gates & wires (not transistors)
• Higher-level design – Adders, memories, etc.
• tools translate into gates

CIS 5710 | Prof Joseph Devietti 36


Describing Hardware
• Schematics
• Pictures of gates & wires
• Hardware description languages
• Use textual descriptions to specify hardware

• Translation process called synthesis


• Textual description -> gates -> full layout
• Tries to minimizes the delay and/or number of gates
• Much like process of compilation of software
• Much slower!

CIS 5710 | Prof Joseph Devietti 37


Schematics

S
A
O
B

• Draw pictures
• Use a program to draw wires, logic blocks, gates
• Supports hierarchical design (arbitrary nesting)
+ Good match for hardware which is inherently spatial
– Not scalable (except at very high levels of abstraction)

CIS 5710 | Prof Joseph Devietti 38


Hardware description language (HDL)
• Write code to describe hardware
• HDL vs. “SDL”
• Specify wires, gates, modules (also hierarchical)
+ Easier to create, edit, modify, scales well
– Misleading “sequential” representation: must still “think”
spatially (gets easier with practice)
S
module mux2to1(input wire S,
input wire A,
input wire B, A Out
output wire Out);
wire useA = ~S & A; B
wire useB = S & B;
assign Out = useA | useB;
endmodule

CIS 5710 | Prof Joseph Devietti 39


SystemVerilog HDL
• the HDL we will be using
• Syntactically similar to C (by design)
± Ease of syntax hides fact that this isn’t C (or software!)
• We will learn SystemVerilog throughout the semester
this is not a function

module mux2to1(input wire S,


input wire A,
input wire B,
output wire Out);
wire useA = ~S & A; these aren’t variables
wire useB = S & B;
assign Out = useA | useB;
endmodule

CIS 5710 | Prof Joseph Devietti 40


HDLs are not software
• Similar in some (intentional) ways
• Syntax
• Named entities, constants, scoping, etc.
• Tool chain: synthesis tool analogous to compiler
• Multiple levels of representation
• lots of compiler optimizations
• Software engineering principles apply
• Modular structure and parameterization
• Libraries and code repositories
• But different in many others!
• One of the most difficult conceptual leaps of this course

CIS 5710 | Prof Joseph Devietti 41


Hardware is not software
• Software is sequential
• Hardware is inherently parallel and “always on”
• Have to work to get hardware to not do things in parallel
• Software is digital
• Hardware has many analog properties
• Including analog correctness properties!
• Software is mostly about functionality
• Performance, power, area (PPA) and functionality matter in
hardware
• Software can be changed
• Hardware is etched in stone (well, silicon)

CIS 5710 | Prof Joseph Devietti 42


Synthesizable constructs
• Code that can be translated into hw via synthesis
• low-level structural constructs
• Specify hardware structures directly
• Transistors, gates, wires, hierarchical modules
• higher-level behavioral constructs
• Specify operations, not hardware to perform them
• simple (&, |) and not-so-simple (+,*) operators
• if/then/else, case

CIS 5710 | Prof Joseph Devietti 43


Non-synthesizable constructs
• Code that cannot be translated into hardware
• Used for writing simulation testbenches
• if/then/else, loops, file I/O
• integers, floating-point numbers
• we will sidestep this and use Python instead
• An HDL is both a high- and low-level language!
• The boundary is sometimes unclear

CIS 5710 | Prof Joseph Devietti 44


Side note: High-Level Synthesis
• “C to gates”
• write hardware at a higher level of abstraction
than conventional HDLs
• greater programmer productivity
• need to write stylized C that will synthesize well
• tools are still slow
• take ESE 5320 & 5390 to learn much more!

CIS 5710 | Prof Joseph Devietti 45


SystemVerilog

CIS 5710 | Prof Joseph Devietti 46


HDL History
• 1970s: first HDLs
• Late 1970s: VHDL
• VHDL = Very High speed integrated circuit hDL
• VHDL inspired by programming languages of the day (Ada)
• 1980s:
• Verilog first introduced, inspired by C
• VHDL standardized
• 1990s:
• Verilog standardized (Verilog-1995 standard)
• 2000s:
• SystemVerilog standardized (2005)
• VHDL and Verilog/SV still dominant today
CIS 5710 | Prof Joseph Devietti 47
Other Notable HDLs
• BlueSpec
• MIT startup from 2003
• more functional style, richer types
• inspired by Haskell
• Chisel
• from Berkeley in 2012
• embedded DSL in Scala

48
SystemVerilog HDL
• Verilog is a huge language
• Structural constructs at both gate and transistor level
• Precise timing specification and simulation
• Lots of behavioral constructs
• Object-oriented features
• A pre-processor
• VPI: Verilog Procedural Interface provides a C API for
simulators
• SystemVerilog Assertions for verification
• …

CIS 5710 | Prof Joseph Devietti 49


Our SystemVerilog
• We’ll learn a focused subset of SystemVerilog
• Mostly synthesizable constructs
• Focus on avoiding subtle errors
• Use as an educational tool
• Some testing and debugging features

Rule 1: if you haven’t seen it in lecture, you probably


shouldn’t use it!

Rule 1a: when in doubt, ask on Ed!

CIS 5710 | Prof Joseph Devietti 50


Basic Verilog Syntax
• Have already seen basic syntax, looks like C
• C/C++/Java style comments
• Names are case sensitive, and can use _ (underscore)
• Avoid: clock, clk, power, pwr, ground, gnd, vdd, vcc, init,
reset, rst
•/*Some
this of
isthese are “special”
a module */ and will silently cause errors
module mux2to1(input wire S,
input wire A,
input wire B,
output wire Out);
wire S_, AnS_, BnS;
// these are gates
not (S_, S);
and (AnS_, A, S_);
and (BnS, B, S);
or (Out, AnS_, BnS);
endmodule
51
(Gate-Level) Structural Verilog
• Primitive “data type”: wire
• Have to declare it

Structural
module mux2to1(input wire S,
input wire A, S
input wire B, A
output wire Out); Out
wire S_, AnS_, BnS;
not (S_, S); B
and (AnS_, A, S_);
and (BnS, B, S);
or (Out, AnS_, BnS);
endmodule

52
(Gate-Level) Structural Verilog
• Primitive “operators”: gates
• Specifically: and, or, xor, nand, nor, xnor, not, buf
• Can be multi-input: e.g., or (C, A, B, D) (C= A | B | D)
• “Operator” buf just repeats input signal (may amplify it)

Structural
module mux2to1(input wire S, S
input wire A,
input wire B, A
output wire Out); Out
wire S_, AnS_, BnS;
B
not (S_, S);
and (AnS_, A, S_);
and (BnS, B, S);
or (Out, AnS_, BnS);
endmodule
53
(Gate-Level) Behavioral Verilog
• Primitive “operators”: boolean operators
• Specifically: &, |, ^, ~
• Can be combined into expressions
• Can be mixed with structural Verilog

“Behavioral” (Synthesizable)
module mux2to1(input wire S, S
input wire A,
input wire B, A
output wire Out); Out
wire S_, AnS_, BnS;
B
assign S_ = ~S;
assign AnS_ = A & S_;
assign BnS = B & S;
assign Out = AnS_ | BnS;
endmodule
54
Wire Assignment
• Wire assignment:
• Connect combinational logic block or other wire to wire
input
• Order of statements not important, executed totally in
parallel
• When right-hand-side
“Behavioral” (Synthesizable) changes, it is re-evaluated and re-
assigned
module mux2to1(input wire S, S
input wire A,
• Designated by the keyword assign
input wire B, A
output wire Out); Out
wire S_, AnS_, BnS;
B
assign S_ = ~S;
assign AnS_ = A & S_;
assign BnS = B & S;
assign Out = AnS_ | BnS;
endmodule
55
Wire Assignment
• Assignment can be combined with declaration
wire c = a | b;

“Behavioral” (Synthesizable)
S
module mux2to1(input wire S,
input wire A, A
input wire B, Out
output wire Out);
wire S_ = ~S; B
wire AnS_ = A & S_;
wire BnS = B & S;
assign Out = AnS_ | BnS;
endmodule

56
(Gate-Level) Behavioral Verilog
• Primitive “operators”: boolean operators
• Specifically: &, |, ^, ~
• Can be combined into expressions
• Can be mixed with structural Verilog

“Behavioral” (Synthesizable)
module mux2to1(input wire S, S
input wire A,
A
input wire B, Out
output wire Out);
assign Out = (~S & A) | (S & B);B
endmodule

57
Best Way to do a Mux
• Verilog supports ?: conditional assignment
operator
• Much more useful (and common) in Verilog than in C/Java

“Behavioral” (Synthesizable)
module mux2to1(input wire SS,
input wire A,
A
input wire B, Out
output wire Out);
assign Out = S ? B B: A;
endmodule

58
Wires Are Not C-like Variables!
• Order of assignment doesn’t matter
• This works fine
module mux2to1(input wire S,
input wire A,
input wire B,
output wire Out);
assign Out = AnS_ | BnS;
assign BnS = B & S;
assign AnS_ = A & S_;
assign S_ = ~S;
endmodule

• Can’t “reuse” a wire


assign temp = a & b;
assign temp = a | b;
• Actually, you can; but doesn’t do what you think it does
59
Wire Vectors
• Wire vectors: also called “arrays” or “buses”
wire [7:0] w1; // 8 bits, w1[7] is most significant bit
wire [0:7] w2; // 8 bits, w2[0] is most significant bit

• Example:
module mux2to1(input wire S,
input wire [7:0] A,
Unlike C, array range is part
input wire [7:0] B,
of type, not variable!
output wire [7:0] Out);
assign Out = S ? B : A;
endmodule

• Operations
• Bit select: vec[3]
• Range select: vec[3:2]
60
• Concatenate: assign vec = {w, x, y, z};
Wire and Wire Vector Constants
wire [3:0] w = 4’b0101;
• The “4” is the number of bits
• The “b” means “binary” - “h” for hex, “o” for octal, “d” for
decimal
• The “0101” are the digits (in binary in this case)
wire [3:0] w = 4’d5; // same thing, effectively
• Here is a single wire constant
wire w = 1’b0;

• A useful example of wire-vector constants:


module mux4to1(input [1:0] Sel, input A, input
B, input C, input D, output Out);
assign Out = (Sel == 2’d0) ? A :
(Sel == 2’d1) ? B :
(Sel == 2’d2) ? C : D;
61
endmodule
Repeated Signals
• Concatenation
wire [2:0] vec = {x, y, z};

• Can also repeat a signal n times


wire [15:0] vec = {16{x}}; // 16 copies of x

• Example uses (what does this do?):


wire [7:0] out;
wire [3:0] A;
assign out = {{4{1’d0}}, A[3:0]};

• What about this?


assign out = {{4{A[3]}}, A[3:0]};

62
Gate-Level Vector Operators
• Verilog also supports behavioral vector operators

• Logical bitwise and reduction: ~,&,|,^


wire [7:0] vec1, vec2;
wire [7:0] vec3 = vec1 & vec2; // bitwise AND
wire w1 = |vec1; // OR reduction

• Integer arithmetic comparison: +,–


,*,/,%,==,!=,<,>
wire [7:0] vec4 = vec1 + vec2; // vec1 + vec2
• Important: all arithmetic is unsigned by default
• Good: in signed/unsigned integers: +, –, * produces same
output
• Just a matter of interpretation
• Bad: in signed/unsigned integers: / % is not the same 63
Signed types
• All wires are unsigned by default
• Verilog supports signed types as well
• changes the semantics of comparison operators < > <=
>=
• permits use of >>> arithmetic shift operator
• useful for implementing CMP,SRA insns
• Vivado
wirelets you intermix
signed [3:0] s; signed and
// signed unsigned
wire
types assign s = …;
• usewire out
signed = (s >to1)
sparingly ? 1’b0
avoid : 1’b1 ;
confusion
wire [3:0] sra = s >>> amt[1:0];
// $signed() operator on an unsigned wire
wire [3:0] u;
wire out2 = ($signed(u) > 2) ? 1’b0 : 1’b1;
64
Why Use a High-Level Operator?
• Abstraction
• Why write assembly, when you can write C? (yay?)

• Take advantage of built-in high level


implementation
• Zedboard FPGAs have integer adders/multipliers on them
• Xilinx will use these rather than synthesizing a multiplier from
gates
• Much faster and more efficient
• How hard is it for Xilinx to figure out you were doing a
multiply?
• If you use “*”: easy
• If you “roll your own” using gates: nearly impossible

65
• Why not use high-level operators?
Hierarchical Design using Modules
• Old-style interface specification
module mux2to1(Sel, A, B, Out);
input Sel, A, B;
output Out;
• Can also have inout: bidirectional wire (we will not use this)
• Recommended Alternative: Verilog 2001
interfaces
module mux2to1(input wire Sel, A, B, output
Out);
A and B share same type as Sel. Convenient, but dangerous!
• Declarations
• Internal wires, i.e., “locals”
• Wires also called “nets” or “signals”
66
wire S_, AnS_, BnS;
Verilog Module Example
module mux2to1(input wire Sel,
input wire A,
input wire B, S
output wire Out);
A
wire S_, AnS_, BnS; O
not (S_, Sel); B
and (AnS_, A, S_);
and (BnS, B, Sel);
or (Out, AnS_, BnS);
endmodule

• Instantiation: mux2to1 mux0 (cond, in1, in2, out);


• Non-primitive module instances must be named (helps
debugging)
• Operators and expressions can be used with
67
modules
Hierarchical Verilog Example
• Build up more complex modules using simpler
modules
• Example: 4-bit wide mux from four 1-bit muxes
• Again, just “drawing”
moduleboxes and wires
mux2to1_4(input wire Sel,
input wire [3:0] A,
input wire [3:0] B,
output wire [3:0] Out);

mux2to1 mux0 (Sel, A[0], B[0], Out[0]);


mux2to1 mux1 (Sel, A[1], B[1], Out[1]);
mux2to1 mux2 (Sel, A[2], B[2], Out[2]);
mux2to1 mux3 (Sel, A[3], B[3], Out[3]);
endmodule

68
Connections via Named Association
• ALWAYS specify module connections by name
• Like named parameters/keyword arguments in SDLs
• Helps keep the bugs away
• Bad example
mux2to1 mux0 (res, s, a, b);
• Good example
mux2to1 mux0 (.Sel(s), .A(a), .B(b), .Out(res));
• Also, order becomes irrelevant
mux2to1 mux1 (.A(a), .B(b), .Out(res), .Sel(s));

69
Generate construct
• basic metaprogramming to reduce repetition
• for loop must have a fixed bound
• think of this as “copy-and-paste”, not a SDL for
loopmodule mux2to1_4(input wire Sel,
input wire [3:0] A,
input wire [3:0] B,
output wire [3:0] Out);
genvar i;
for (i = 0; i < 4; i = i+1) begin
mux2to1 m(.Sel(Sel),.A(A[i]),.B(B[i]),
.Out(Out[i]));
end
endmodule

70
Per-Instance Module Parameters
• Module parameters: useful for defining varying bus
widths
module Nbit_mux2to1 (input wire Sel,
input wire [N-1:0] A,
input wire [N-1:0] B,
output wire [N-1:0] Out);
parameter N = 1;
assign Out = Sel ? B : A;
endmodule

• Two ways to instantiate: implicit


Nbit_mux2to1 #(4) mux1 (.Sel(S),.A(in1),.B(in2),.Out(out));
• And explicit
Nbit_mux2to1 mux1 (.Sel(S),.A(in1),.B(in2),.Out(out));
defparam mux1.N = 4;
• Multiple parameters per module allowed 71
Per-Instance Module Parameters
• localparam: a parameter that is only visible within
a module
• a constant, scoped to that module

72
Fancy: Generate and Parameters
module rca
#(parameter N = 4)
(input wire [N-1:0] a,
input wire [N-1:0] b,
output wire [N-1:0] s);
wire [N:0] carry;
assign carry[0] = 1'b0;

genvar i; // skip optional “generate” keyword


for (i=0; i<N; i = i+1) begin
fulladder f(.cin(carry[i]),.a(a[i]),.b(b[i]),
.s(s[i]),.cout(carry[i+1]));
end
endmodule

73
Wire Arrays
• Verilog supports multi-dimensional wire vectors
• Useful with generate loops when you need lots of buses

wire[15:0] y[7:0]; // eight 16-bit buses


y[0]; // first 16-bit bus
y[0][0]; // first bit of the first bus

74
Verilog Pre-Processor
• Like the C pre-processor
• But uses ` (back-tick) instead of #
• Constants: `define
• No parameterized macros
• Use ` before expanding constant macro
`define letter_A 8’h41
wire w[7:0] = `letter_A;
• Conditional compilation: `ifdef, `endif
• File inclusion: `include

• Parameter vs `define
• A parameter is scoped to a module instance
• A `define is scoped to a file (potentially across modules) 75
Verilog Errata
• Wires have binary values: 0 or 1
• except when they don’t: x and z are undefined values
• No particular naming convention for modules and
their files
• Unlike, say, Java public classes
• No “imports” or “libraries”
• There are ways to do this, to integrate 3rd-party Intellectual
Property (IP) into your design. We won’t explore this.

76
Verilog testing constructs
• integer, reg types
• correspond to storage (unlike wire which is stateless)
• DO NOT use these outside of testing!
• we’ll see this later: reg will synthesize into a latch/FF
• delay statement
• #10; means “wait 10 cycles”
• for/while loops
• allow iterating over test inputs
• $display()
• printf-like output
• $display(“wire was %b", a);
• $finish
77
• ends the simulation
Sequential Logic

78
Two Types of Digital Circuits
• Combinational Logic
• Logic without state variables
• Examples: adders, multiplexers, decoders, encoders
• No clock involved

• Sequential Logic
• Logic with state variables
• State variables: latches, flip-flops, registers, memories
• Clocked
• State machines, multi-cycle arithmetic, processors

• Sequential Logic in Verilog


• Special idioms using behavioral constructs that synthesize
into latches, memories
79
Sequential Logic & Synchronous
Systems
Combinational Storage
Logic Element
Clock
• Processors are complex fine state machines
(FSMs)
• Combinational (compute) blocks separated by storage
elements
• State storage: memories, registers, etc.
• Synchronous systems
• Clock: global signal acts as write enable for all storage
elements
• Typically marked as triangle
• All state elements write together, values move forward in
lock-step
+ Simplifies design: design combinational blocks 80
independently
Datapath Storage Elements
datapath

fetch

Insn Register Data


PC
memory File Memory

control

• Three main types of storage elements


• Singleton registers: PC
• Register files: ISA registers
• Memories: insn/data memory

81
S-R Latch
• S-R (set-reset) latch
R Q
• Cross-coupled NOR gates
• Distinct inputs/outputs
Q’
S,R ® Q S
0,0 ® oldQ
0,1 ® 0 R Q
1,0 ® 1 SR
1,1 ® 0 S

• S=0, R=0? circuit degenerates to cross-coupled


INVs
• S=1, R=1? reset has “higher priority”
• Not really used … except as component in 82
D Latch

D
Q

D Q
DL
E

83
Timing Diagrams
• Voltage {0,1} diagrams for different nodes in
system
• “Digitally stylized”: changes are vertical lines
(instantaneous?)
• Reality is analog, changes are continuous and smooth
E
• Timing diagram for a D latch
D

84
Triggering: Level vs. Edge
E

• The D-latch is level-triggered


• The latch is open for writing as long as E is 1
• If D changes continuously, so does Q
– Pretty hard to work with
• Much easier to use an edge-triggered latch
• The latch is open for writing only on E transition (0 ® 1 or 1
® 0) 85
D Flip-Flop
• D Flip-Flop:
• Sequential D-latches D Q
• Enabled by inverse signals DL DL
E
• First latch open when E = 0
• Second latch open when E = 1
• Overall effect? D Q
• D flipflop latches D on 0®1 transition FF
• E is the “clock” signal input
E

Q
86
FFWE: FF with Separate Write Enable
• FFWE: FF with separate write enable
• FF D(ata) input is MUX of D and Q, WE selects

D Q Q
FF D FFWE

WE
WE

• Bad idea: why not just AND the CLK and WE?
+Fewer gates
– Creates timing problems
§ Do not try to do logic on CLK in Verilog
§ No, really. Never do this. 87
N-bit Register
D0 Q0
FFWE

D1 Q1
n n
FFWE
D Q

DN-1 QN-1
FFWE
WE

• Register: one n-bit storage word WE


• Non-multiplexed input/output: data buses write/read same
word
• Implementation: FFWE array with shared write-
enable (WE)
88
• FFs written on CLK edge if WE is 1 (or if there is no WE)
Sequential Logic in Verilog

89
Designing Sequential Logic
• key design rule: separate combinational logic from
sequential state elements
• Not enforced by Verilog, but a very good idea
• Possible exceptions: counters, shift registers
• We’ll give you a flip-flop module (see next slide)
• Edge-triggered, not a transparent latch
• Parameterized to create an n-bit register
• Example
Clock
use: state machine
State Combinational Output
Register Current Logic
State
Next State

90
Sequential Logic In Verilog
• How are state-holding variables specified in
Verilog?
• First instinct: structurally
• After all, real latches and flip-flops are made from gates…

module latch(out, in, we);


output out; input in, we;
wire not_out = ~(out | (we & ~in));
assign out = ~(not_out | (we & in));
in
endmodule
out

• This should work, right? RIGHT?


• Logically, yes… in practice, no
we
• Storage elements are highly analog
• FPGAs have dedicated storage 91
Verilog Flipflop (Behavioral Magic)
• How do we specify state-holding constructs in Verilog?
module dff (output wire out,
input wire in, input wire writeEnable,
input wire reset, input wire clock);

reg out;
always @(posedge clock)
begin • reg: storage bit
if (reset) • always @ (): synthesizable
out = 0; behavioral sequential Verilog
else if (writeEnable) • Tricky: hard to know exactly what
out = in; it will synthesize to
end • We will give this to you,
endmodule don’t write your own
• “Creativity is a poor substitute for
knowing what you’re doing”
92
Verilog Register (Behavioral Magic)
• How do we specify state-holding constructs in Verilog?
module register (output wire [n-1:0] out,
input wire [n-1:0] in, input wire writeEnable,
input wire reset, input wire clock);
parameter n = 1;

reg [n-1:0] out;


always @(posedge clock) • reg: interface-less storage bit
begin • always @ (): synthesizable
if (reset) behavioral sequential Verilog
out = 0; • Tricky: hard to know exactly what
else if (writeEnable) it will synthesize to
out = in; • We will give this to you,
end don’t write your own
endmodule • “Creativity is a poor substitute for
knowing what you’re doing”
93
Clock Signals
• Clocks & reset signals are not normal signals
• Travel on dedicated “clock” wires
• Reach all parts of the chip
• Special “low-skew” routing

• Ramifications:
• Never do logic operations on the clocks
• If you want to add a “write enable” to a flip-flop:
• Use a mux to route the old value back into it
• (or use the flip-flop with write enable we give you!)
• Do not just “and” the write-enable signal with the clock!

• Messing with the clock can cause a errors


• Often can only be found using detail low-level simulation94
What does <…> do in Verilog?
• https://www.edaplayground.com
• web-based Verilog editor+simulator
• recommended simulator: Icarus Verilog 0.10.0
• https://hdlbits.01xz.net/wiki/Main_Page
• online Verilog problem sets

95
Testbenches
• A more effective way to test & debug designs

• In Java?
• Write test code in Java to test Java
• “Test harness”, “unit testing”

• For Verilog?
• Write test code in Verilog to test Verilog
• Verilog has advanced “behavioral” commands to facilitate
this:
• Delay for n units of time
• Full high-level constructs: if, while, sequential
assignment, ints
• Input/output: file I/O, output to display, etc. 96
Common Errors
• Tools are from a less civilized time
• More like C, less like Java
• Assume that you mean what you say
• Common errors:
• Not assigning a wire a value
• Assigning a wire a value more than once
• Implicit wire declarations (default to type “wire” 1-bit wide)
• Mis-matched wire assignment widths
• Combinational loops
• Avoid names such as:
• clock, clk, power, pwr, ground, gnd, vdd, vcc, init, reset, rst
• Some of these are “special” and will silently cause errors
97
Official Vivado Verilog Reference

from Vivado Design


Suite User Guide:
Synthesis UG901
(v2017.4)

98
List of Verilog keywords
always endspecify medium rnmos vectored
and endtable module rpmos wait
assign endtask nand rtran wand
automatic event negedge rtranif0 weak0
begin for nmos rtranif1 weak1
buf force nor scalared while
bufif0 forever noshow-cancelled* show-cancelled* wire
bufif1 fork not signed wor
case function notif0 small xnor from Chapter 7 of
casex generate notif1 specify xor Vivado Design Suite
casez genvar or specpa User Guide: Synthesis
cell* highz0 output strong0 UG901 (v2017.4)
cmos highz1 parameter strong1
config* if pmos supply0
deassign ifnone posedge supply1
default incdir* primitive table
defparam include* pull0 task
design* initial pull1 time
disable inout pullup* tran
edge input pulldown* tranif0
else instance* pulsestyle_ondetect* tranif1
end integer pulsestyle_onevent* tri
endcase join rcmos tri0
endconfig* larger real tri1
endfunction liblist* realtime triand
endgenerate library* reg trior
endmodule localparam release trireg
99
endprimitive macromodule repeat use*
Additional Verilog Resources
• Elements of Logic Design Style by Shing Kong,
2001
• Do’s, do-not’s, other tips
• http://www.cis.upenn.edu/~milom/elements-of-logic-design-
style/

• Verilog HDL Synthesis: A Practical Primer


• By J. Bhasker, 1998
• To the point (<200 pages)

• Advanced Digital Design with the Verilog HDL


• By Michael D. Ciletti, 2003
• Verilog plus lots of digital logic design (~1000 pages) 100
Summary
App App App
• Transistors & fabrication
System software
• Digital logic basics
Mem CPU I/O • Focus on useful components
• Hardware design methods
• Introduction to Verilog

• Next unit: fast arithmetic

101

You might also like