Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Verilog Coding PDF

This document discusses Verilog, a hardware description language used for designing digital circuits. It summarizes: 1) Verilog was originally developed as a modeling language for digital logic simulation but is now commonly used as a specification language for logic synthesis. 2) Verilog combines structural and behavioral modeling styles. Modules can contain instances of other modules and primitives, as well as behavioral descriptions using always blocks. 3) Verilog is used to design virtually all FPGAs, ASICs, and other digital chips. Behavioral modeling is easier for writing testbenches while structural modeling reflects the actual circuit.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Verilog Coding PDF

This document discusses Verilog, a hardware description language used for designing digital circuits. It summarizes: 1) Verilog was originally developed as a modeling language for digital logic simulation but is now commonly used as a specification language for logic synthesis. 2) Verilog combines structural and behavioral modeling styles. Modules can contain instances of other modules and primitives, as well as behavioral descriptions using always blocks. 3) Verilog is used to design virtually all FPGAs, ASICs, and other digital chips. Behavioral modeling is easier for writing testbenches while structural modeling reflects the actual circuit.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

The Verilog Language Multiplexer Built From Primitives

module mux(f, a, b, sel); Verilog programs


Originally a modeling language for a very efficient output f;
input a, b, sel; built from modules
event-driven digital logic simulator
The Verilog Language Each module has
Later pushed into use as a specification language for logic and g1(f1, a, nsel),
COMS W4995-02 g2(f2, b, sel); an interface
synthesis or g3(f, f1, f2);
not g4(nsel, sel); Module may contain
Prof. Stephen A. Edwards Now, one of the two most commonly-used languages in structure: instances of
Fall 2002 digital hardware design (VHDL is the other) endmodule primitives and other
Columbia University f1
Virtually every chip (FPGA, ASIC, etc.) is designed in part a modules
Department of Computer Science g1
using one of these two languages g4
nsel
g3 f
Combines structural and behavioral modeling styles
b
g2
sel f2

Multiplexer Built with Always Multiplexer Built with Always Mux with Continuous Assignment
module mux(f, a, b, sel); module mux(f, a, b, sel); module mux(f, a, b, sel);
output f; Modules may output f; output f;
input a, b, sel; contain one or more input a, b, sel; A reg behaves like input a, b, sel;
reg f; always blocks reg f; memory: holds its value
until imperatively assign f = sel ? a : b;
always @(a or b or sel) Sensitivity list always @(a or b or sel) LHS is always set to
if (sel) f = a; if (sel) f = a; assigned otherwise endmodule the value on the RHS
else f = b; contains signals else f = b;
whose change Body of an always block Any change on the right
endmodule endmodule
makes the block contains traditional causes reevaluation
a a a
execute imperative code

f f f
b b b
sel sel sel

Mux with User-Defined Primitive How Are Simulators Used? Structural Modeling
primitive mux(f, a, b, sel);
output f; Testbench generates stimulus and checks response When Verilog was first developed (1984) most logic
input a, b, sel; Behavior defined using simulators operated on netlists
Coupled to model of the system
table a truth table that
Pair is run simultaneously Netlist: list of gates and how they’re connected
1?0 : 1; includes “don’t cares”
0?0 : 0; This is a less pessimistic than A natural representation of a digital logic circuit
?11 : 1;
?01 : 0; others: when a & b match, sel is Stimulus Not the most convenient way to express test benches
11? : 1; ignored; others produce X
00? : 0; Testbench System Model
endtable a
endprimitive
Response
Result checker
f
b
sel
Behavioral Modeling How Verilog Is Used Two Main Components of Verilog:
Behavioral
A much easier way to write testbenches Virtually every ASIC is designed using either Verilog or
VHDL (a similar language) Concurrent, event-triggered processes (behavioral)
Also good for more abstract models of circuits
Behavioral modeling with some structural elements Initial and Always blocks
• Easier to write
“Synthesis subset” can be translated using Synopsys’ Imperative code that can perform standard data
• Simulates faster
Design Compiler or others into a netlist manipulation tasks (assignment, if-then, case)
More flexible Design written in Verilog Processes run until they delay for a period of time or wait
Provides sequencing Simulated to death to check functionality for a triggering event
Verilog succeeded in part because it allowed both the Synthesized (netlist generated)
model and the testbench to be described together
Static timing analysis to check timing

Two Main Components of Verilog: Two Main Data Types: Nets Two Main Data Types: Regs
Structural
Nets represent connections between things Regs represent data storage
Structure (Plumbing) Do not hold their value Behave exactly like memory in a computer
Verilog program build from modules with I/O interfaces Take their value from a driver such as a gate or other Hold their value until explicitly assigned in an initial or
Modules may contain instances of other modules module always block

Modules contain local signals, etc. Cannot be assigned in an initial or always block Never connected to something

Module configuration is static and all run concurrently Can be used to model latches, flip-flops, etc., but do not
correspond exactly
Actually shared variables with all their attendant problems

Discrete-event Simulation Four-valued Data Four-valued Logic


Basic idea: only do work when something changes Verilog’s nets and registers hold four-valued data Logical operators work on three-valued logic
Centered around an event queue that contains events 0, 1: Obvious
labeled with the simulated time at which they are to be
Z: Output of an undriven tri-state driver. Models case
executed
where nothing is setting a wire’s value 0 1 X Z
Basic simulation paradigm Outputs 0 if either
X: Models when the simulator can’t decide the value 0 0 0 0 0
• Execute every event for the current simulated time input is 0
• Initial state of registers 1 0 1 X X
• Doing this changes system state and may schedule
X 0 X X X Outputs X if both
events in the future • When a wire is being driven to 0 and 1 simultaneously
Z 0 X X X inputs are gibberish
• When there are no events left at the current time • Output of a gate with Z inputs
instance, advance simulated time soonest event in the
queue
Nets and Registers Modules and Instances
Wires and registers can be bits, vectors, and arrays Basic structure of a Verilog module:

wire a; // Simple wire module mymod(out1, out2, in1, in2);


tri [15:0] dbus; // 16-bit tristate bus output out1;
Verilog convention
tri #(5,4,8) b; // Wire with delay
Structural Modeling output [3:0] out2; lists outputs first
reg [-1:4] vec; // Six-bit register
input in1;
trireg (small) q; // Wire stores a small charge
input [2:0] in2;
integer imem[0:1023]; // Array of 1024 integers
reg [31:0] dcache[0:63]; // A 32-bit memory
endmodule

Instantiating a Module Gate-level Primitives Delays on Primitive Instances


Instances of Verilog provides the following: Instances of primitives may include delays
module mymod(y, a, b); and nand logical AND/NAND buf b1(a, b); // Zero delay
look like or nor logical OR/NOR buf #3 b2(c, d); // Delay of 3
mymod mm1(y1, a1, b1); // Connect-by-position xor xnor logical XOR/XNOR buf #(4,5) b3(e, f); // Rise=4, fall=5
mymod (y2, a1, b1), buf not buffer/inverter buf #(3:4:5) b4(g, h); // Min-typ-max
(y3, a2, b2); // Instance names omitted bufif0 notif0 Tristate with low enable
bifif1 notif1 Tristate with high enable
// Connect-by-name
mymod mm2(.a(a2), .b(b2), .y(c2));

Switch-level Primitives User-Defined Primitives A Carry Primitive


Verilog also provides mechanisms for modeling CMOS primitive carry(out, a, b, c);
Way to define gates and sequential elements using a truth
transistors that behave like switches table output out;
Always has exactly
input a, b, c;
A more detailed modeling scheme that can catch some Often simulate faster than using expressions, collections one output
table
additional electrical problems when transistors are used in of primitive gates, etc.
this way 00? : 0;
Gives more control over behavior with X inputs Truth table may include
0?0 : 0;
Now, little-used because circuits generally aren’t built this don’t-care (?) entries
Most often used for specifying custom gate libraries ?00 : 0;
way
11? : 1;
More seriously, model is not detailed enough to catch 1?1 : 1;
many of the problems ?11 : 1;
These circuits are usually simulated using SPICE-like endtable
simulators based on nonlinear differential equation solvers endprimitive
A Sequential Primitive Continuous Assignment
Primitive dff( q, clk, data);
Another way to describe combinational function
output q; reg q;
input clk, data; Convenient for logical or datapath specifications
table wire [8:0] sum; Define bus widths
// clk data q new-q
(01) 0 : ? : 0; // Latch a 0 wire [7:0] a, b; Continuous Behavioral Modeling
(01) 1 : ? : 1; // Latch a 1 wire carryin; assignment:
(0x) 1 : 1 : 1; // Hold when d and q both 1 permanently
(0x) 0 : 0 : 0; // Hold when d and q both 0 sets the value of
(?0) ? : ? : -; // Hold when clk falls assign sum = a + b + carryin; sum to be
? (??) : ? : -; // Hold when clk stable a+b+carryin.
endtable Recomputed
endprimitive when a, b, or
carryin changes

Initial and Always Blocks Initial and Always Procedural Assignment


initial always Run until they encounter a delay Inside an initial or always block:
begin begin initial begin sum = a + b + cin;
// imperative statements // imperative statements #10 a = 1; b = 0;
end end #10 a = 0; b = 1; Just like in C: RHS evaluated and assigned to LHS before
end
next statement executes
or a wait for an event
Runs when simulation starts Runs when simulation starts RHS may contain wires and/or regs
always @(posedge clk) q = d;
Terminates when control Restarts when control LHS must be a reg
reaches the end reaches the end always begin
wait(i); (only primitives or continuous assignment may set wire
Good for providing stimulus Good for modeling or a = 0; values)
specifying hardware wait(˜i);
a = 1;
end

Imperative Statements For Loops While Loops


if (select == 1) y = a; Example generates an increasing sequence of values on A increasing sequence of values on an output
else y = b; an output
reg [3:0] i, output;
reg [3:0] i, output;
case (op)
i = 0;
2’b00: y = a + b;
for ( i = 0 ; i <= 15 ; i = i + 1 ) begin while (i <= 15) begin
2’b01: y = a - b;
output = i; output = i;
2’b10: y = a ˆ b;
#10; #10 i = i + 1;
default: y = ’hxxxx;
end end
endcase
Modeling A Flip-Flop With Always Blocking vs. Nonblocking A Flawed Shift Register
Very basic: an edge-sensitive flip-flop Verilog has two types of procedural assignment This does not work as you would expect:

reg q; Fundamental problem: reg d1, d2, d3, d4;


• In a synchronous system, all flip-flops sample
always @(posedge clk) always @(posedge clk) d2 = d1;
simultaneously
q = d; always @(posedge clk) d3 = d2;
• In Verilog, always @(posedge clk) blocks run in always @(posedge clk) d4 = d3;
q = d assignment runs when clock rises: exactly the
some undefined sequence
behavior you expect These run in some order, but you don’t know which

Non-blocking Assignments Nonblocking Can Behave Oddly Nonblocking Looks Like Latches
This version does work: Nonblocking rule: A sequence of nonblocking assignments don’t RHS of nonblocking taken from latches
RHS evaluated communicate
reg d1, d2, d3, d4; RHS of blocking taken from wires
when assignment a = 1; a <= 1; a = 1;
runs
always @(posedge clk) d2 <= d1;
b = a;
c = b;
b <= a;
c <= b;
b = a;
c = b;
“ 1
a b
c ”
always @(posedge clk) d3 <= d2;
Blocking assignment: Nonblocking assignment: 1
always @(posedge clk) d4 <= d3; a=b=c=1 a=1 a
a <= 1;

LHS updated only


b = old value of a
c = old value of b
b <= a;
c <= b;
“ b

after all events for
the current instant c
have run

Modeling FSMs Behaviorally FSM with Combinational Logic


module FSM(o, a, b, reset);
output o; Output o is declared a reg
There are many ways to do it: reg o; because it is assigned
input a, b, reset;
• Define the next-state logic combinationally and define reg [1:0] state, nextState; procedurally, not because it
always @(a or b or state) holds state
the state-holding latches explicitly
case (state)
2’b00: begin
Define the behavior in a single always @(posedge o = a & b;
Building Behavioral Models

nextState = a ? 2’b00 : 2’b01;
clk) block end
2’b01: begin
o = 0; nextState = 2’b10;
• Variations on these themes end
endcase
always @(posedge clk or reset)
if (reset)
state <= 2’b00;
else
state <= nextState;
endmodule
FSM with Combinational Logic FSM from a Single Always Block Writing Testbenches
Inputs to device
module FSM(o, a, b, reset); module FSM(o, a, b); module test;
output o;
output o; reg o; Expresses Moore under test
reg o; Combinational block must be reg a, b, sel;
input a, b, reset; sensitive to any change on any input a, b; machine behavior: Device under test
reg [1:0] state, nextState; reg [1:0] state;
of its inputs (Implies Outputs are latched. mux m(y, a, b, sel);
always @(a or b or state) state-holding elements
case (state) always @(posedge clk or reset) Inputs only sampled $monitor is a built-in even-driven “printf”
2’b00: begin otherwise) if (reset) state <= 2’b00; initial begin
o = a & b; at clock edges $monitor($time,,"a=%b b=%b sel=%b y=%b",
nextState = a ? 2’b00 : 2’b01; else case (state)
end 2’b00: begin a, b, sel, y);
2’b01: begin
o = 0; nextState = 2’b10; state <= a ? 2’b00 : 2’b01; a = 0; b= 0; sel = 0; Stimulus generated by
end o <= a & b; #10 a = 1;
endcase end sequence of
Nonblocking assignments #10 sel = 1;
always @(posedge clk or reset) 2’b01: begin #10 b = 1; assignments and
if (reset) state <= 2’b10; used throughout to ensure delays
state <= 2’b00; Latch implied by o <= 0; coherency. RHS refers to end
else
state <= nextState; sensitivity to the clock end values calculated in
endmodule or reset only endcase
previous clock cycle

Simulation Behavior Two Types of Events


Scheduled using an event queue Evaluation events compute functions of inputs
Non-preemptive, no priorities Update events change outputs
A process must explicitly request a context switch Split necessary for delays, nonblocking assignments, etc.

Simulating Verilog Events at a particular time unordered


Update event writes
Scheduler runs each event at the current time, possibly Evaluation event
new value of a and
scheduling more as a result a <= b + c reads values of b
schedules any
and c, adds them,
evaluation events
and schedules an
that are sensitive to
update event
a change on a

Simulation Behavior Simulation Behavior Simulation Behavior


Concurrent processes (initial, always) run until they stop Infinite loops are possible and the simulator does not Race conditions abound in Verilog
at one of the following check for them This runs forever: no context switch
These can execute in either order: final value of a
#42 allowed, so ready can never change
• undefined:
Schedule process to resume 42 time units from now while (˜ready)
always @(posedge clk) a = 0;
wait(cf & of) count = count + 1;
• always @(posedge clk) a = 1;
Resume when expression “cf & of” becomes true Instead, use
• @(a or b or y) wait(ready);
Resume when a, b, or y changes
• @(posedge clk)
Resume when clk changes from 0 to 1
Simulation Behavior Compiled-Code Discrete-Event Sim.
Semantics of the language closely tied to simulator Most modern simulators use this approach
implementation
Verilog program compiled into C
Context switching behavior convenient for simulation, not
Each concurrent process (e.g., continuous assignment,
always best way to model
always block) becomes one or more C functions
Undefined execution order convenient for implementing
Verilog and Logic Synthesis
Initial and always blocks split into multiple functions, one
event queue
per segment of code between a delay, a wait, or event
control (@)
Central, dynamic event queue invokes these functions and
advances simulation time

Logic Synthesis Logic Synthesis Tools Logic Synthesis


Mostly commercial tools
Verilog is used in two ways Takes place in two stages:
• Very difficult, complicated programs to write well
Model for discrete-event simulation 1. Translation of Verilog (or VHDL) source to a netlist
• Limited market
Specification for a logic synthesis system Register inference performed here
• Commercial products in $10k – $100k price range
Logic synthesis converts a subset of the Verilog language Major vendors 2. Optimization of the resulting netlist to improve speed
into an efficient netlist and area
• Synopsys Design Compiler, FPGA Express
One of the major breakthroughs in designing logic chips in Most critical part of the process
• Cadence BuildGates
the last 20 years Algorithms very complicated and beyond the scope of
• Synplicity (FPGAs)
Most chips are designed using at least some logic this class: Take Prof. Nowick’s class for details
• Exemplar (FPGAs)
synthesis
Academic tools
• SIS (UC Berkeley)

Logic Optimization Translating Verilog into Gates What Can Be Translated


Netlist optimization the critical enabling technology Parts of the language easy to translate Every structural definition
Behavioral blocks
Takes a slow or large netlist and transforms it into one that Structural descriptions with primitives is already a netlist
implements the same function more cheaply
• Depends on sensitivity list
Continuous assignment expressions turn into little
• Only when they have reasonable interpretation as
Typical operations: datapaths combinational logic, edge, or level-sensitive latches
• Constant propagation Behavioral statements the bigger challenge • Blocks sensitive to both edges of the clock, changes on
unrelated signals, changing sensitivity lists, etc. cannot be
• Common subexpression elimination synthesized
• Function factoring User-defined primitives
• Primitives defined with truth tables
Time-consuming operation. Can take hours for large chips
• Some sequential UDPs can’t be translated (not latches or
flip-flops)
What Is Not Translated Register Inference Register Inference
Initial blocks The main trick Combinational:
Sensitive to
Used to set up initial state or describe finite testbench stimuli reg y;

A reg is not always a latch or flip-flop changes on all the
always @(a or b or sel)
• Don’t have obvious hardware component Rule: Combinational if outputs always depend exclusively variable it reads
if (sel) y = a;
Delays on sensitivity list else y = b; y is always assigned
• May be in the Verilog source, but are simply ignored Sequential if outputs may also depend on previous values
A variety of other obscure language features Sequential:
• In general, things heavily dependent on discrete-event reg q;
simulation semantics always @(d or clk)
q only assigned
if (clk) q = d;
• Certain “disable” statements when clk is 1
• Pure events

Register Inference Register Inference Inferring Latches with Reset


A common mistake is not completely specifying a case The solution is to always have a default case Latches and Flip-flops often have reset inputs
statement always @(a or b) Can be synchronous or asynchronous
This implies a latch: case ({a, b})
Asynchronous positive reset:
always @(a or b) 2’b00 : f = 0;
case ({a, b}) 2’b01 : f = 1; always @(posedge clk or posedge reset)
2’b10 : f = 1; if (reset)
2’b00 : f = 0;
default : f = 0; f is always assigned q <= 0;
2’b01 : f = 1;
else q <= d;
2’b10 : f = 1; endcase
f is not assigned when
endcase
{a,b}= 2’b11

Simulation-synthesis Mismatches Summary of Verilog


Many possible sources of conflict Systems described hierarchically
• Synthesis ignores delays (e.g., #10), but simulation • Modules with interfaces
behavior can be affected by them • Modules contain instances of primitives, other
Simulator models X explicitly, synthesis does not modules
Summary

• Behaviors resulting from shared-variable-like behavior • Modules contain initial and always blocks
of regs is not synthesized:
Based on discrete-event simulation semantics
always @(posedge clk) a = 1;
• Concurrent processes with sensitivity lists
New value of a may be seen by other @(posedge clk)
statements in simulation, never in synthesis • Scheduler runs parts of these processes in response
to changes
Modeling Tools Language Features Language Uses
Nets (wires) for modeling interconnection Event-driven simulation
Switch-level primitives: CMOS transistors as switches that
move around charge • Non state-holding • Event queue containing things to do at particular
• Values set continuously simulated times
Gate-level primitives: Boolean logic gates
Regs for behavioral modeling
User-defined primitives: Gates and sequential elements • Evaluate and update events
• Behave exactly like memory for imperative modeling
defined with truth tables • Compiled-code event-driven simulation for speed
• Do not always correspond to memory elements in
Continuous assignment: Modeling combinational logic Logic synthesis
synthesized netlist
with expressions
Blocking vs. nonblocking assignment • Translating Verilog (structural and behavioral) into
Initial and always blocks: Procedural modeling of behavior netlists
• Blocking behaves like normal “C-like” assignment
• Nonblocking delays update, modeling synchronous
• Register inference: whether output is always updated
behavior • Logic optimization for cleaning up the result

Little-used Language Features Little-used Language Features Compared to VHDL


Switch-level modeling Delays Verilog and VHDL are comparable languages
• Much slower than gate or behavioral-level models • Simulating circuits with delays does not improve VHDL has a slightly wider scope
confidence enough • System-level modeling
• Insufficient detail for modeling most electrical
problems • Hard to get timing models accurate enough • Exposes even more discrete-event machinery
• Delicate electrical problems simulated with a • Never sure you have simulated the worst case VHDL is better-behaved: Fewer sources of
SPICE-like differential equation simulator nondeterminism (e.g., no shared variables)
• Static timing analysis has taken its place
VHDL is harder to simulate quickly
VHDL has fewer built-in facilities for hardware modeling
VHDL is a much more verbose language: Most examples
don’t fit on slides

In Conclusion In Conclusion
Verilog is a deeply flawed language Verilog is widely used because it solves a problem
• Nondeterministic • Good simulation speed that continues to improve
• Often weird behavior due to discrete-event semantics • Designers use a well-behaved subset of the language
• Vaguely defined synthesis subset • Makes a reasonable specification language for logic
synthesis
• Many possible sources of simulation/synthesis
mismatch • Logic synthesis one of the great design automation
success stories

You might also like