sandeepani verilog

354
Sandeepa ni www.sandeepani- vlsi.com Verilog HDL Coding for Simulation & Synthesis

Upload: pavithra-patil

Post on 22-Oct-2014

324 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog HDL Coding for Simulation &

Synthesis

Page 2: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What’s Coming

• Objectives– Introduce Verilog language concepts– Use of language features to capture hardware design

specification and Verify– Explore gate level modeling capabilities – Understand PLI capability

• Format– Morning – Presentations– Afternoon – Lab Exercises

• Timing– Coffee…..10.30 to 10.45 & 3.30 to 3..45– Lunch……1.00 to 2.00

Page 3: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Part-I Designing using Verilog ( RTL Coding )

Page 4: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE

- Session I  • Introduction to Verilog-HDL, Data Types, Operators.• Verilog Language Concept, Hierarchy, Concurrency,

Timing • Continuos and Procedural Assignments

- Session II • Lab 1- Use of Simulation and synthesis Tools• Multiplexer, Comparator ,Decoder  • Using Hierarchy • Assignments

Page 5: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE - Session I 

• Verilog Coding styles – RTL , Behavioural.• Sequential statements - if else, case, for loop, while loop,

statements• Blocking and Non-blocking statements,Simulation cycle

- Session II • Lab 2• Sequential Logic exercises- Registered logic, timing logic, Counting logic..• Assignments

Page 6: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE - Session I 

• Synthesis Process• Structural RTL coding

- Session II • Lab 3• Coding for Finite State Machines• Assignments

Page 7: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE - Session I 

• Sample complete design• RTL coding Guidelines

- Session II • Lab 4• Use of External IP in design• Structural coding• Assignments

Page 8: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Part-II Verification using Verilog ( Behavioral Coding )

Page 9: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE

- Session I  • Verification Overview, Writing Simple Test benches• System Tasks & Compiler directives• Use of input and output files• Creating self checking test benches

- Session II • Lab 1- Use of Simulation and synthesis Tools• Writing Simple Test benches for Multiplexer,

comparator,Decoder..   • Writing Test bench for Clocked logic

Page 10: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE - Session I 

• Tasks & Functions• PLI Overview• Creating PLI applications

- Session II • Lab 2• Writing test benches using Tasks • Writing test benches for FSM’s

Page 11: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SCHEDULE - Session I 

• Sum up

- Session II Lab 3• Writing structured test benches using I/O files• Complete verification of structured model• Design Debugging

Page 12: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Application

Page 13: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Application

Objectives Identify the advantages of designing with an HDL. Applications of Verilog Define what is meant by “levels of abstraction” with

respect to: Verilog modeling

Page 14: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What is Verilog• Verilog is not a software

language• Verilog is a Hardware

Description Language (HDL)– Programming language with

special constructs for modeling hardware

Verilog Supports:-• Structure

– Physical (netlist & hierarchy)– Software (subprogram)

• Hardware behavior– Serial (sequential)– Concurrent (parallel)

• Timing• Abstraction levels

Structure

a

b

c

q

r

s

Behavior

Timing

Tclk-q

Tnetclk

Tpd Tsetup

TholdD Q

Page 15: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Levels of Abstraction

Behavioralalgorithmic

RegisterTransfer Level

Gate level-structural

-netlist

Physical -silicon-Switch

Verilog

f

Layout / place& Route

Logic synthesis

Page 16: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Abstraction Level Example:Divide by 2

always @ (data) op <= data/2;

always @ (posedge clk) op <= data >> 1;

FD1 opreg2 ( .D(data[3]), .CP(clk), .Q(op[2] ) );FD1 opreg1 (.D(data[2]), .CP(clk), .Q(op[1] ) );FD1 opreg0 (.D(data[1]), .CP(clk), .Q(op[0] ) );FD1 opreg3 ( .D(1’b0), .CP(clk), .Q(op[3] ) );

Gate Level Netlist

Behavioral

2data op

4 4

SLI

data opD Q

4 4

clk

RTL

Page 17: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Benefits of Using an HDL Design at a higher level.

Find problems earlier in the design cycle Explore design alternatives

Description is implementation independent. Functional and technology changes are easier to make Decisions on implementation can be delayed longer

Flexibility Re-use of design Choice of tools,vendors

Text language based Faster design capture Easier to manage

Page 18: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Applications

Verilog language is used by:

ASIC and FPGA designers writing RTL code for synthesis System architects doing high level system simulations Verification engineers writing advanced tests for all level of

simulation Model developers describing ASIC or FPGA cells, or higher level

components

Page 19: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Based Simulation

• High level testbench in Verilog

• Interacts with design• Portable• Possibility of automatic

checking of function• Testbench written in

behavioral style• Design written in RTL

style

Testbenchbehavioral

DesignRTL

Compare

Results Expected results

waveforms

Page 20: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Page 21: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Language Introduction

Page 22: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

• Objective– Examine fundamental language objects– Introduce the main language concepts

• Contents– Verilog objects– Verilog connection model– Hierarchy– Rules and regulations

Aims and Topics

Page 23: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

module• Describes interface and

behavior • Module’s communicate

through ports– Port names listed in

parentheses after the module name.

• Ports can be defined as input, or inout (bidirectional)

• ^is the exclusive or operator• & is an logical and operator

Important to Remember :Verilog is case sensitive for

identifiers keywords must be in lowercase

module halfadd (a, b, sum, carry); output sum, carry; input a, b;

assign sum = a ^ b assign carry = a & b

endmodule

+

halfadd

sum

carry

a

b

Page 24: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Representing Hierarchy

Create hierarchy by Instantiating module Connecting module ports to

local ports or nets Local nets need to be

declared The or construct is a “built

in” gate primitive

U1 U2

a

b

cin halfadd halfadd

n_sum

n_carry1

n_carry2

carry

sum

fulladd

module fulladd (a, b, cin, sum, carry); input a, b, cin; output sum, carry; wire n_sum, n_carry1, n_carry2; halfadd U1 (.a(a), .b(b), .sum(n_sum), .carry(n_carry1) ); halfadd U2 (.a(n_sum), .b(cin), .sum(sum), .carry(in_carry2) ); or U3 (carry1, n_carry2, n_carry1) ; endmodule

Local nets of typewire

Page 25: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Connecting Hierarchy-Named Port Connection

Explicitly specifies which module port is mapped to which local port/wire

instantiation

a

b

U1

n_carry1

n_sum a b

sum

carry

module

halfadd module fulladd (a, b, cin, sum, carry); input a, b, cin; output sum, carry ; wire n_sum, n_carry1, n_carry2 ; ….. halfadd U1 (.a(a), .b(b), .sum(n_sum), .carry(n_carry1) ); …..

…mapped to wire n_carry1 of fulladd module

module halfadd (a, b, sum, carry); output sum, carry; input a, b; … endmodule

Output carry of halfadd module

TipUse named port connection

For linking hierarchy

Page 26: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Connecting Hierarchy-Ordered Port Connection Port mapping in order:-

•1st instantiation port mapped to 1st module port• 2nd instantiation port mapped to 2nd module port• etc

instantiation

n_sum

n_carry1

module

halfaddU1

a

b a sum

b carry

module fulladd (a, b, cin, sum, carry) ; input a, b, cin; output sum, carry; wire n_sum, n_carry1, n_carry2; ….. halfadd U1 (a, b, n_sum, n_carry1) ; …..

input a of fulladd mapped to input a of halfadd

input b of fulladd mapped to input b of halfadd

module halfadd (a, b, sum, carry) ; output sum, carry ; input a, b ;…… endmodule

CautionLess readable and more error-prone than named port connection

Page 27: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Blocks (Procedures)• Section containing procedural

statements• Multiple procedures interact

concurrently• always procedure

– Executes when any variable in event list changes value

– Runs throughout simulation

• initial procedure– Executes once at start of

simulation– Used for initialisation,

testbenches…

always @ (a or b or sel) if (sel = = 1)

y = a ;else y = b ;

event list

a 1 y b 0

sel initial begin a = 1; b = 0; end

Synthesis initial blocks are not synthesisable

Page 28: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Event List

• always procedure executes when one or more variables in the event list change value

• An event is a change in logic value

always @ (a or b or sel) begin if (sel = = 1) y = a ; else y = b ; end

“or” is a keyword used in event lists

event list

Page 29: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

The Verilog Connectivity Model

• Multiple procedures interacting concurrently– Executing statements in

sequence, like conventional “software”

– Communicating concurrently through variables

• Procedures contained in a module– Or separated into several

modules for a hierarchical design

Procedure

Procedure

Procedure

Procedure

Page 30: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Compilation LibrarySome Verilog tools use

compilation libraries:- A collection of compiled

modules or primitives Physical exists as a directory Referred to by library name Simulator startup file

specifies mapping Library name ->directory

name

Compile into “WORK” WORK mapped to specific

library name

a_clk.v

WORK

PRIMS MY_WORK PROJ

Page 31: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Design Compilation• Design compiled from a list

of Verilog files• Normally compile the

testbench first– Usually contains

compiler directives– Provides additional

information for the compiler/simulator

• Order of other files generally not important

• Hierarchical connections are automatically made

• Verilog allows different levels of abstraction anywhere in the hierarchy

read_frame netlist

tb_one testbench

design structural

cpu pnet_read pnet_write behavioral RTL/structural behavioral

write_frame primitives

Page 32: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comComments and Spacing

// This is a ‘line’ comment. Each line must begin with // // Comments end with a new line module halfadd (a, b, sum, carry) ; output sum, carry ; input a, b ; // End of line comment … /* This is a ‘block’ comment. Text in a block comment can span many lines.*/ // Verilog is a free-format language // Additional spaces can be used to enhance readability assign sum =a ^ b; assign carry = a & b; // use indentation to aid readability and debugging always @ (a or b or sel) if (sel = =1) y = a; else y = b;

Page 33: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Identifier Naming Rules• Names may consist of any

alphnumeric character, including dollar sign ($) and underscore(_)

• Names must start with a letter or an underscore

• Verilog identifiers are case sensitive– Keywords must be

lowercase

• These names do not refer to the same object– ABC,Abc,abc

• Names can be of any length– Tool or methodology may

restrict name lengths.

unit_32 structural bus_16_bite a$b

unit@32 unit - 32 16_bit_bus

Page 34: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Page 35: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Logic System andData

Types

Page 36: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Aims and Topics• Aims

– To introduce the Verilog logic value system and to understand the different data types and the rules covering their use.

• Topics– Logic value system– Data type classes– Vectors and literal values– Net data types and their use– Choosing the correct data type– Parameters– Memory arrays

Page 37: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

4-Value Logic System in Verilog

Zero, Low,False, Logic Low, Ground, VSS, Negative Assertion

One,High,True,Logic High, Power, VDD, VCC, Positive Assertion

X,Unknown (bus contention), Uninitialized

Hiz, High Impedance, Tri-State, Undriven, Unconnected, Disabled Driver (Unknown)

0

1

X

Z

buf

buf

buf

bufifI

ImportantThe “unknown” logic value x is not the same as “don’t care.”

Page 38: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Data Types• Verilog objects communicate using variables• All variables have a type• There are three different classes of data type

– Nets• Represent physical connection between structures and

objects e.g. wire

– Registers• Represent abstract storage elements e.g.reg

– Parameters• Run-time constants

Page 39: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Net Types• A Net type behaves like a wire driven by a logic gate

• Various net types are available – Wire is the most commonly used– Nets not explicitly declared default to type wire

• Net values changed with assign in continuous assignments and by modules or primitives in the design

wire sel; // Scalar wire wire [31:0] w1, w2 ; // Two 32-bit wires with msb = bit 31 wand c; // Scalar wired-AND net tri [15:0] busa ; // A 16-bit tri-state bus, msb = bit 15

module halfadd (a, b, sum, carry) ; input a, b; // default to wire output sum, carry ; // default to wire // change with assign assign sum = a ^ b; assign carry= a & b; endmodule

Net types:- wire, tri supply1, supply0 wor, trior wand, triand trireg, tri0, tri1

Page 40: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Wire and assign wire declaration and assignment can be merged. Remember – ports default to wire types Note:~ is an inversion operator

a

sel

b

module mux (a, sel, b, out); input sel, b, a; output out ; wire nsela, selb, nsel ; assign nsel = ~sel; assign selb = sel & b ; assign nsela = nsel & a; assign out = nsela | selb ; endmodule

module mux (a, sel, b, out ); input sel, b, a ; output out ; wire nsel = ~sel; wire selb = sel & b; wire nsela = nsel & a ; assign out = nsela | selb; endmodule

nsel

nsela

selb

out

Nets

Page 41: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Logic Conflict Resolution with Nets If the same net is driven from multiple sources a conflict occurs Net types have a resolution function to determine final value of target

assign y = a ; assign y = b ;

?

y declared as y declared as y declared as wire y ; wand y ; wor y ; tri y ; triand y ; trior y ;

0 1 x z 0 0 x x 0 0 1 x 1 x 1 1 x x x x x x z 0 1 x z z

0 0 0 0 0 0 1 x 00 1 x 1 1 1 1 1 10 x x x x x 1 x x0 1 x z z 0 1 x x

0 1 x zab

ab a

b 0 1 x z

Synthesis wire and tri are synthesisable, some synthesis tools support wor and wand

a

b

y

Page 42: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Register Types Register types stores value until a new value is assigned Various register types are available

reg is the most commonly used Register values changes with procedural assignment

Synthesis reg and integer are synthesisable, but do not have to synthesis to a flip-flop in hardware

Register types:- reg integer real time

module mux (a, b, c, sel, op) ; input a, b, c, ; input sel ; output op ; reg op ; always @ (a or b or sel) begin if (sel = = 1) op = a; else op = b; end endmodule

reg [3:0] vect ; // 4-bit unsigned vector reg [2:0] p, q ; // two 3-bit unsigned vector integer i ; // 32-bit signed integer reg s ; // unsized reg defaults to 1-bit time delay ; // time value

Page 43: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Register Assignment Register types can only be updated from within a procedure Procedures can only update register types Registers and nets can be mixed on the right-hand-side of an assignment

module mux ( a, b, c, sel, mux ) ; input a, b, c ; input sel ; output mux ; wire aandb, nmux ; reg mux, nota ; always @ (a or b or sel) if (sel = = 1) begin mux = a ; nmux = b ; end else begin mux = a ; nmux = b ; end assign nota = ~a; assign aandb = a & b ; …

Error Net type assigned in procedure

Error Register type assigned outside procedure

Page 44: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comChoosing the Correct Data Type

Input Port Output Port net net/register a b net y Inout Port

net

net/register atop btop

net ytop

module top; wire ytop; reg atop, btop; initial begin atop = 1’b0; btop = 1’b0; end dut U1 (.a(atop), .y(ytop), . b(btop)); endmodule

module dut (y, a, b) ; output y; input a, b;

assign y = a&b;endmodule

Page 45: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Parameters• Parameters are used to declare run-time constants.• Can be used anywhere that you can use a literal.

•Make code more readable

• Parameters are local to the module in which they are defined.• Can be used to size local variable declarations

• Including module ports• Must be declared before used

// parameter list parameter pl = 8, REAL_p = 2.039, X_WORD = 16’bx ;

module mux (a, b, sel, out) ;

parameter WIDTH = 2;

input [WIDTH –1:0] a; input [WIDTH – 1:0] b; input sel ; output [WIDTH – 1:0] out ; reg [WIDTH –1:0] out ; always @ (a or b or sel) if (sel) out = a; else out = b; endmodule

Page 46: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comOverriding the Values of

Parameters• Constant values can be changed for each

instantiation of module module muxs (abus, bbus, anib, bnib, opbus, opnib, opnib1, sel );

parameter NIB = 4: input [NIB-1:0] anib, bnib; input [7:0] abus, bbus; input sel;

output [NIB-1:0] opnib, opnib1; output [7:0] opbus ; // module instantiations for different sized muxes mux # (8) mux8 (.a(abus), .b(bbus), . Sel(sel), .out”(opbus) ); mux # (NIB) mux4 (.a(anib), .b(bnib), .sel(sel), .out(opnib) ); mux mux4a (.a(anib), .b(bnib), .sel(sel), .out(opnib1) );defparam mux4a.width=4;endmoduleExample follows…..

module mux (a, b, sel, out); parameter WIDTH = 2; ….

Page 47: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

module gen_dec (en,a,y);

parameter sizein=3, sizeout=8; input en;input [sizein-1:0]a;output [sizeout-1:0]y; reg [sizeout-1:0]y; integer i;always @(en or a) begin if(!en) y=0; else if(a > sizeout-1 ) for (i=0;i<= sizeout-1;i=i+1) y[i]=1'bx; else for (i=0;i<= sizeout-1;i=i+1) if(a==i) y[i]=1; else y[i]=0; end endmodule

module gen_dec_call (ena,enab,adda,addb,decadda,decaddb); input ena;

input enb;

input [1:0]adda;input [1:0]addb;

output [3:0]decadda; output [3:0]decaddb;

gen_dec#(2,4) dec2_4(ena,adda,decadda);gen_dec #(3,8) dec3_8(enb,addb,decaddb);

endmodule

Generic Decoder

Page 48: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Two Dimensional Arrays• Verilog supports two-dimensional array of registers

• A array element is addressed by an index to the 2-d array

-You can only reference one element of memory at a time

– Multiple words accesses require multiple statements– Single bit accesses require an intermediate variable

reg [7:0] mem_array [0:255]; // memory array reg [7:0] mem_word; reg membit;

mem_word = mem_array [5]; // access address 5 mem_word = mem_array [10]; // access address 10 membit = mem_word [7] ; // access bit 7 of address 10

reg [15:0 ] mem [0 : 1023] ; // 1K x 16-bit 2-d array integer int_arr [99 :0] ; // Array of integers 100 deep

Synthesis: Two-dimensional arrays generally not synthesisable

Page 49: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSummary

• A net type behaves like a real wire driven by a logic gate– Nets not explicitly declared default to type wire– Net values changed with assign statement or when driven by

a module/primitive• Register types stores value until a new value is assigned

– Register types do not have to synthesise to a register hardware element

– Procedural assignment can only be updated with a procedural assignment

– When assigning integer to reg, sign information is disregarded• Registers and nets can be mixed on the right-hand-side of an

assignment• Module ports are defined as wire by default

– Inputs must be net types, but can be driven by nets or registers– Inouts must be net types and can only be driven by a net– Outputs can be net or a register types, but can only drive a net

Page 50: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Operators

Page 51: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Aims and Topics Aims

-Introduce the operators available in the Verilog language Topics

Operator Type

arithmetic bit-wise logical reduction shift relational equality conditional concatenation replication

Symbol

+ - * / %~ & ^ ~ ^! & & & ^ ~ & ~ ~ ^< < > >< > < = > == = ! = = = = ! = =? :{ }{ { } }

Page 52: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com Arithmetic Operators

+ add - substract * multiply / divide % modulus

• Binary arithmetic is unsigned• Integer arithmetic is signed

Synthesis % not synthesisable / only synthesisable if dividend is a power of 2

module arithops ( ) ; integer ans, int ; parameter FIVE = 5 ; reg [3:0] rega, regb, regc, num ;

initial begin rega = 3 ; // 0011 regb = 4’b1010 ; regc = 2; // 00010 int = -3 ;

ans = FIVE * int; // ans = -15 ans = (int + 5) /2; // ans = 1 ans = FIVE / int ; // ans = -1 num = rega + regb; // num= 1101 num = regc + regb; // num= 1100 num = int; // num = 1101 num = regc % rega; // num = 0010 end endmodule

Page 53: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Bit-Wise Operators ~ not & and or ^ xor ~ ^ xnor ^ ~ xnor

• Bit-wise operators operate on vectors.• Operations are performed bit by bit on individual bits.

Note: Unknown bits in an operand do not necessarily lead to unknown bits in the result

module bitwise ( ) ; reg [3:0] rega, regb, regc ; reg [3:0] num ; initial begin rega = 4’ b1001 ; regb = 4’ b1010 ; regc = 4’ b11x0 ;

num = ~rega; // num = 0110 num = rega & 0 ; // num = 0000 num = rega &regb; // num = 1000 num = rega | regb; // num = 1011 num = regb & regc; // num = 10x0 num = regb | regc; // num = 1110 end endmodule

Page 54: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Logical Operators ! not && and or

• Logical operators are an operand reduction, followed by single bit operation

- Vectors containing any 1 reduce to 1’b1 - Vectors containing all 0 reduce to 1’b0 - Vectors containing any x or z with only 0 reduce to 1’bx

module logical ( ); parameter FIVE = 5; reg ans ; reg [3:0] rega, regb, regc ; initial begin rega = 4’b0011; // reduces to 1 regb = 4’b10xz; // reduces to 1 regc = 4’b0z0x; // reduces to x

ans = ! rega; // ans = 0 ans = rega && 0; // ans = 0 ans = rega | | 0; // ans = 1 ans = rega && FIVE; // ans = 1 ans = regb && rega ; // ans = 1 ans = regc | | 0; // ans = x end endmodule

Page 55: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comUnary Reduction Operators

& and or ^ xor ~& nand ~ nor ~ ^ xnor ^ ~ xnor

• Reduction operators perform a bit-wise operation on all the bits of a single operand.• The result is always 1’b1, 1’b0 or 1bx.

module reduction ( ) ; reg val ; reg [3:0] rega, regb;

initial begin rega = 4’b0100; regb = 4’b1111;

val = & rega ; // val = 0 val = | rega ; // val = 1 val = & regb ; // val = 1 val = | regb ; // val = 1 val = ^ rega ; // val = 1 val = ^ regb ; // val = 0 val = ~ | rega ; // val = 0 val = ~ &rega; // val = 1 val = ^rega && regb; // val = 1 end endmodule

Page 56: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comShift Operators

> > shift right < < shift left

• Shift operators perform left or right bit shifts on the operand.• Shift is logical

•0 is used for extra bits• Shifts can be used to implement division or multiplication by powers of two

module shift ( ) ; reg [9:0] num ; reg [7:0] rega ; initial begin rega = 8’b00001100;

num =rega >> 1; // num = 0000000110 num = rega >> 3; // num = 0000000001 num = rega << 5; // num = 0110000000

end endmodule zeros added first, then shift by 5 to the left

Page 57: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Relational Operators

> greater than < less than >= greater than or equal <= less than or equal

• The result is:-• 1’b1 if the condition is true• 1’b0 if the condition is false• 1’bx if the condition cannot be resolved

module relationals; reg [3:0] rega, regb, regc; reg val ;

initial begin rega = 4’b0011; regb = 4’b1010; regc = 4’b0x10;

val = regc > rega ; // val = x val = regb < rega ; // val = 0 val = regb >= rega ; // val = 1 val = regb > regc ; // val = x end endmodule

Page 58: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comConditional Operator

module tribuf (in, enable, out); input in, enable; output out; reg out;

always @ (enable or in) out = enable ? In : 1’bz; endmodule

… wire out3; reg out1, out2; always @ (a or b or sel) out1 = sel ? a : b ;

always @ (a or b or sel) if (sel) out2 = a; else out2 = b; assign out3 = sel ? a : b; …

? : conditional

in out

enable

a

b

sel

out

Note: sometimes the if else construct may be more readable

Page 59: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Concatenation{ } concatenation• Allows you to select bits from different vectors and join them into a new vector.• Used for bit reorganization and vector construction

•e.g.rotates• Can used on either side of assignment

ImportantLiterals used in concatenation must be sized

module concatenation; reg [7:0] rega, regb, regc, regd, new; reg [3:0] nib1, nib2; initial begin rega = 8’ b00000011; regb = 8’ b00000100; regc = 8’ b00011000; regd = 8’ b11100000; new = { regd [6:5], regc [4:3], regb[3:0]; // new = 8’ b11_11_0100 new = {2’ b11, regb[7:5], rega[4:3], 1’ b1}; // new = 8’ b11_000_00_1 new = {regd [4:0], regd[7:5]}; // rotate regd right 3 places // new = 8’b00000_111

{nib1, nib2} = rega; // nib1 = 4’ 0000, nib2 = 4’ 0011 end endmodule

Page 60: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comReplication

{ { } } replication Replication allows you to reproduce a sized variable a set number of times

•Can be nested and used with concatenation

• Syntax is:-{ <repetitions> {<variable>} }

ImportantLiterals used in replication must be sized

4x rega concatenated with 2x regc [1:0]

regc concatenated with 2x regb

regc concatenated with 2x 1’b1 and replicated 2 times

module replicate ( ) ; reg rega; reg [1:0] regb; reg [3:0] regc; reg [7:0] bus; initial single bit rega begin replicated 8 times rega = 1’ b1; regb = 2’b11; regc = 4’ b1001; bus = {8{rega}}; // bus = 11111111 bus = { {4{rega}}, {2{regc[1:0] }} }; // bus = 1111_01_01 bus = { regc, {2{regb}} }; // bus = 1001_11_11 bus = {2 {regc[2:1], {2{1’b1}}} }; // bus = 00_1_1_00_1_1 end endmodule

Page 61: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Operator Precedence• Do not rely on Operator Precedence – use parentheses

Type of Operators Symbols Concatenation / Replication { } { { } } Inversion (Logical / Bitwise) ! ~ Arithmetic * / % + - Logical Shift << >> Relational < <= > >= Equality == != === !== Bit-wise / Reduction & ~& ^ ^~ ~ Logical &&

Conditional ? :

Highest

Precedence

Lowest

Page 62: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Statements

Page 63: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Aims and Topics

• Aim– To introduce some of the most commonly

used procedural statements

• Topics– Procedures– Procedural statements

• if then else• case• loops

Page 64: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com initial versus always

Procedures• There are 2 types of procedural block

• always procedure executes repeatedly throughout the simulation• it is triggered by a change of value for any variable in the event list• initial procedure executes once at start of simulation

• begin …end must be used for multiple statements within a block

Synthesis Initial procedures cannot be synthesized

… reg a, b, zor, zand;

initial begin a = 1’b1; b = 1’b0; end

always @ (a or b) begin if (a | b) event list zor = 1’b1; else zor = 1’b0; if (a & b) zand = 1’b1; else zand = 1’b0; end …

Page 65: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Assignments

• Assignments made inside procedural blocks are called procedural assignments• All variables on the left-hand side must be register data-types, e.g. reg• Here carry is not declared, and defaults to a 1-bit wire.

Error carry is a net type-should be declared reg carry;

module fulladder (out, a, b, cin); input a, b, cin; output [1:0] out;

reg sum; reg [1:0] out;

always @ (a or b or cin) begin sum = a ^ b ^ cin; carry = ((a & b) | ( cin & (a ^ b))); out = {carry, sum};

end endmodule

Page 66: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Event Control• always procedure executes when one or more variables in the event list change value

Synthesis Include all signals read by the block in the event list for the generation of combinational logic

• Can also use negedge or posedge•Execute procedure on a specific edge of a variable• Used for modeling synchronous logic

Synthesis: cannot mix edge and level triggers in event list

always @ (a or b or sel) begin if (sel = = 1) y = a; else y = b; end

always @ (posedge clk) // procedural statements

always @ (negedge clk) // procedural statements

always @ (negedge clk or rst) // not synthesisable …

event list

Page 67: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Blocks within Verilog module design; wire nsela;

wire nsel = !sel; wire selb = sel & b;

assign nsela = nsel & a;

// continuous statements … endmodule

always @ (a or b or sel) begin // procedural statements end

always @ (nsel or selb) out = nsel | selb; Procedure

Procedure

Procedure

Procedure

Page 68: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

if Statement Example• if is a conditional statement• Each if condition is tested in sequence

-Condition is boolean expression•The first valid test executes that branch•Conditions can overlap

Synthesis if synthesis to mux structures

module if_example (a, b, c, d, y); input [3:0] a, b, c, d; output [3:0] y; reg [3:0] y;

always @ (a or b or c or d) if (d = = 4’ b0000) y = a; else if (d <= 4’b0101) y = b; else y = c; endmodule

c 0 b 1 a mux

0 1

mux

y

<= =

d 0000 d 0101

Page 69: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com if Statement Syntax

• Signal if statement execute procedural statements only if the condition is true..• .. add an unconditional else to execute procedural statements when the if condition is false..• …add else if to test further conditions if the first is false

-Final else is optional and can be used to indicate default operation

• Use begin and end to bound multiple procedural statements

if (CONDITION) begin / / procedural statements end

if (CONDITION) begin / / procedural statements end else begin / / procedural statements end

if (CONDITION) begin / / procedural statements end else if (CONDITION) begin / / procedural statements end else begin / / procedural statements end

Page 70: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com case Statement Example

• case is a multiway conditional statement• case expression is evaluated and compared against each item in turn

-Branch items can overlap-The first item match executes that branch

• The optional default captures unspecified values

•In this example, values containing x or z

module case_example (a, b, c, d, y); input [3:0] a, b, c, d; output[3:0] y; reg [3:0] y;

always @ (a or b or c or d) case (d) 0 : y = a; 1,2,3,4,5 : y = b; 6 : y = c; 7 : y = c: default : y = 4’ b0000; endcase endmodule

Page 71: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

for Loop• Iterates around loop for a specified number of times• Loop variable must be declared• When loop executed:

-Loop variable initialized-Loop statement(s) executed-Loop operation performed-When condition false, loop exits

// for loop expansion tmp = 0 ^ a[0]; // =a[0] tmp = tmp ^ a[1]; tmp = tmp ^ a[2]; tmp = tmp ^ a[3];

Synthesis for loop with fixed limits is synthesisable

module parity (a, odd); input [3:0] a; output odd; reg odd, tmp; integer i; always @ (a) begin tmp = 0; for (i = 0; i <= 3; i = i + 1) tmp = tmp ^ a[i]; odd = tmp; end endmodule

a[0] a[1] a[2] a[3]

tmp

Page 72: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

repeat and while Loops module multiplier (result, op_a, op_b); input [3:0] op_a, op_b; output [7:0] results; reg [7:0] results; reg [7:0] shift_opa; reg [3:0] shift_opb;

always @ (op_a or op_b) begin result = 0; shift_opa = op_a; // zero extend left shift_opb = op_b; repeat (4) begin if (shift_opb[0] ) result = result + shift_opa; shift_opa = shift_opa << 1; // shift left shift_opb = shift_opb >> 1; // shift right endendmodule

• repeat loops iterate by the number specified

-Number can be literal, variable or expression

• while loop iterates while the expression is true, or non-zero

… while (count < 10) begin // statements count = count + 1; end …

Page 73: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Loop Statement Syntax• for loop requires a loop variable declaration• while loop continues while the condition is true• repeat iterates the number of times defined by the expression• forever loops forever

Synthesis-for loop synthesizable for fixed range.- repeat synthesizable for fixed repetitions- while generally not synthesizable- forever generally not synthesisable

Unsynthesizable loops used in testbenches and simulation models

// loop variable must be declared for (initial, condition, inc_dec) begin // statements end

while (condition) begin // statements end

repeat (expression) begin / / statements end

forever begin // statements end

Page 74: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Continuous and procedural statements

Objective: To explain difference between continuous and procedural statements

Page 75: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Continuous Assignments

They are:continuously drivenorder independent

They:operate on net data type only & reside outside procedures

Example: wire a; wire out; ……….. assign a=x+y; assign out=a+z;

+

+

x

y

z

a

out

Page 76: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comMultiple Continuous

Assignments

Example: wire z;….…..assign z=a+b;assign z=c+d; …

What would be value on signal z ?

+

+?

z

ab

cd

Page 77: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comMultiple Continuous

Assignments

• Multiple assignments to single variable are “wired together”• If z is wire type ,then following table resolves value

wire/tri | 0 1 x z ----------------------- 0 | 0 x x 0 1 | x 1 x 1 x | x x x x z | 0 1 x z

• As per need one can use wand or wor types for resolution|

Page 78: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Assignments

•Procedure statements execute in sequence or triggered by event occurring on variable in event list

• Variables are updated immediately

•Procedures execute concurrently

Page 79: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedural Assignments

Example:module andor(a,b,z_or,z_and); input a,b;output z_or,z_and;reg z_or,z_and;always @(a or b) begin if(a | b) z_or=1; else procedural assignments z_and=0; if(a & b) z_and=1; else z_and=0; endendmodule

Page 80: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple Assignments in Procedure

What happens when same variable is assigned in procedure?Ex: ……. reg z; ….. always @(a or b or c or d)

begin z=a+b; z=c+d;end

Last statement overrides previous assignment.

c

dz

Page 81: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Example..

Code the following block:

za

b

sel

Page 82: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Example..

1) always@ (a or b or sel) 2) always@ (a or b or sel) begin begin

z=b;//default assig. if(sel) if(sel) z=a; z=a;

else end z=b; end

• Last statement takes effect

Page 83: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Conditional Assignments

•This can be used in either procedural or continuous assignments•Procedure containing single if can be replaced by continuous assignmentsExample:

always @(a or b or c or sel) if (sel==0)

z=a; else if(sel<= 4’b1010)

z=b; else z=c; endmodule

alternate to above procedure is to use conditional operator

Page 84: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Conditional Assignment..

always @(a or b or c or sel) z=(sel==0) ? a:((sel<=4’b1010) ?b:c); …………

Using continuous assignment:…..assign z=(sel==0) ? a:((sel<=4’b1010) ?b:c);

Page 85: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Avoid feedback loops

What would happen if you use following code ?

assign z=z+x;Oralways @(z or x) z=z+x;

Page 86: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Avoid feedback loops

•Creates feedback loop with zero-delay.•Program shall go in infinite loop in simulation and simulation will lock.

zx

Page 87: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Review

1.What happens if multiple procedural assignment are made to the same variable?2. Is a conditional assignment statement continuous, procedural or both ?3. Why should you not create combinational feedback loops?4. Code the following hardware using i) a continuous assignment and ii) using a procedure

+a[3:0]

b[3:0]

c[4:0]

add

01 d[4:0]

Page 88: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Page 89: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comProcedural Statements and the

Simulation Cycle

Objective: To explain capabilities of procedures and blocking non-blocking assignments

Simulation cycle

Page 90: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Contents

Blocking Procedural AssignmentNon-blocking procedural assignmentSimulation cycleTiming controlReview

Page 91: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Procedure and Event Control

Example: 1. …… 2. …… always @(a or b or c) always @(posedge clk) begin:adding if(clr)

y=a+b; q <= 0; z=a+c; else end q <= d;

•Procedures executes whenever any event occurs on variable•Procedures can be named

Page 92: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comBlocking Procedural

Assignment

Blocking assignment:=

Variable assignment is immediate-before the next statement is executed

Can create problems with some code structures

Example..

Page 93: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comExample

Will this segment of code Swap the upper and lower byte contents?

……..initialbegin byte=8’b00001111;#20;byte[3:0]=byte[7:4]; byte[7:4]=byte[3:0];#20;……

Page 94: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Contents

Blocking Procedural AssignmentNon-blocking procedural assignmentSimulation cycleTiming controlReview

Page 95: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Non-Blocking Assignment

Non-blocking assignment:<= Variable update is scheduled

-value is calculated and stored-Variable is updated at the end of time slice

Page 96: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

ExampleWill this segment of code Swap the upper and lower byte contents?……..initialbegin byte<=8’b00001111;#20;byte[3:0]<=byte[7:4];//byte[3:0] scheduled to receive 4’b0000 byte[7:4]<=byte[3:0];// byte[7:4] scheduled to receive 4’b1111 #20; // procedure suspends, scheduled assignments updated

and nibbles successfully swapped……

Yes !!!

Page 97: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Contents

Blocking Procedural AssignmentNon-blocking procedural assignmentSimulation cycle Timing controlReview

Page 98: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle(1)

___ ___ ___ ___

Variable procedureEvent list schedule a<=1

• Assume a,w,m,y all zero• a changes from zero to one

module sim_ex(a,m,y,w);Input a;Output m,y,w;Reg m,y,w;

Always@ (a or m)begin:p1

m<=a;y<=m;

End variable at start

Always@ ( m) a:m:y:w=0begin:p2

w<=m;Endendmodule

Page 99: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle(2)

___ _______ ____

Variable procedureEvent list schedule m<=1 p1a updated from 1’b0 to 1’b1Procedure p1 executesUpdate to m scheduledNo change in the value of y

module sim_ex(a,m,y,w);Input a;Output m,y,w;Reg m,y,w;

always@ (a or m)begin:p1

m<=a;y<=m;

End variable at start

a:1,m:y:w:0Always@ ( m)begin:p2

w<=m;Endendmodule

Page 100: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle(3)

____ _____ ____ _____Variable procedureEvent list schedule m<=1 p1m changes value to 1’b1 p2Procedure p1 placed on scheduler listProcedure p2 placed on scheduler list

module sim_ex(a,m,y,w);Input a;Output m,y,w;Reg m,y,w;

always@ (a or m)begin:p1

m<=a;y<=m;

End variable at start

a:1,m:1y:w:0always@ ( m)begin:p2

w<=m;Endendmodule

Page 101: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle(4)

____ ____ ____ ____

Variable procedureEvent list schedule y<=1W<=1

Procedure p1 and p2 execute(random)Update to y and w scheduledNo change in value for m

module sim_ex(a,m,y,w);input a;output m,y,w;Reg m,y,w;

always@ (a or m)begin:p1

m<=a;y<=m;

end

always@ ( m) variable values after one delta

a:1,m:1y:w:0begin:p2

w<=m;endendmodule

Page 102: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle(5)

____ ____

____ ____

Variable procedure

Event list schedule

y and w are updated to 1’b1;

no more procedures to be executed

module sim_ex(a,m,y,w);Input a;Output m,y,w;Reg m,y,w;

always@ (a or m)begin:p1

m<=a;y<=m;

End

always@ ( m) variable values after

two deltas

a:1,m:1y:1w:1

begin:p2w<=m;

Endendmodule

Page 103: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation cycle:summaryVariable procedure variableEvent list schedule values a<=1 p1 a:1,m:0

y:0,w:0

m<=1 p1 a:1,m:1p2 y:0,w:0

Y<=1 a:1,m:1W<=1

y:1,w:1

module sim_ex(a,m,y,w);Input a;Output m,y,w;Reg m,y,w;

always@ (a or m)begin:p1

m<=a;y<=m;

Endalways@ ( m)begin:p2

w<=m;Endendmodule

Page 104: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comDelta cycle and simulation

Time

Multiple delta cycles at each point of simulation time

One can specify timing inside procedural blocks Following are three types of timing controls

Edge-sensitive timing control:@regular delay: #level sensitive :wait

Simulation time

Page 105: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Page 106: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comMore on blocking and non-blocking

assignments

Objectives: Guidelines on usage of blocking and non-blocking assignments

Page 107: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review Usage in clocked proceduresUsage in combinational proceduresMix usage

Page 108: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Blocking assignment review

Blocking assignment:=

Variable update is immediate -before other statements are executed

always @(posedge clk) if(sel) z=a; else z=b;

Page 109: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comNon-blocking assignment

review

Non-blocking assignment:<= Variable update is scheduled

-after the procedure suspends

…..reg q;always @(posedge clk)

q<=d;..

Page 110: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review Usage in clocked proceduresUsage in combinational proceduresMix usage

Page 111: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comBlocking assignment in clocked

procedures

What is value of cvar in following segment of code?

initialbegin avar=1’b1; bvar=1’b1; endalways @(posedge clk) bvar=avar+1’b1;

always @(posedge clk) cvar=bvar;

Page 112: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comBlocking assignment in clocked

procedures

Blocking assignment can lead to “race conditions”Specifically when:- -variable written in one procedure and read in another -both procedures have same event list

In example shown above: -both procedures execute on positive edge of clock -assignments to bvar and cvar are immediate -final value of cvar depends on which procedure is executed first

Page 113: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comNon-Blocking assignment in clocked

procedures• Non=blocking

assignment avoids race conditions

• Example:- both procedures execute on positive on positive edge of clock

assignments to bvar and cvar are scheduled

initialbegin avar=1’b1; bvar=1’b1; endalways @(posedge clk) bvar<=avar+1’b1;

always @(posedge clk) cvar<=bvar;Use non-blocking

assignment for synchronous logic

Page 114: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Position dependent code

always @(posedge clk)

begin

b=a;

c=b;

d=c;

endUsing blocking signal assignment

in clocked procedures can also result in position dependent code

always @(posedge clk)

begin

d=c;

c=b;

b=a;

end

Page 115: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review Usage in clocked proceduresUsage in combinational proceduresMix usage

Page 116: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Combinational logic

always @ (a or b) begin m=a; n=b; p=m+n; end

Use blocking assignment for combinational procedures

Page 117: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Combinational logic

always @(a or b or m or n)

begin:p1

m<=a;

n<=b;

p<=m+n;

endVariable event procedure

event list scheduler

a<=1 p1

b<=2

m<=1 p1

n<=2

p<=3

• Non-blocking assignment can be inefficient for combinational logic

• Specifically when logic contains serial serial behavior or intermediate variables

-intermediate variables must be added to event list

-procedure will take several delta cycles to reach “steady state”

Page 118: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple assignments

always @(a or b or c)

begin

m=a;

n=b;

p=m+n;

m=c;

q=m+n;

endMultiple assignments should be either

blocking or non-blocking

always @(a or b or c or m or n)begin m<=a; n<=b; p<=m+n; m<=c; q<=m+n;endMultiple assignments can be made to

a variable within one procedure-last assignment wins for non-

blocking

Page 119: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

contents

Blocking and non-blocking assignment-Review Usage in clocked proceduresUsage in combinational proceduresMix usage

Page 120: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Mixed assignments

always @(posedge clk) begin tempa=ip1; …… tempb=f(tempa); …… op1<= tempb; ……end

always @(posedge clk)

begin

temp=a+b;

q<=temp+c;

end

Page 121: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Mixed assignments

•Blocking assignments can be used within clocked procedures for temporary variables• usage: - assign inputs to temporary variables with blocking assignment -perform algorithm with temporary variables and blocking assignment -assign temporary variables to outputs with non- blocking assignment

Page 122: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Definition of RTL Code

Page 123: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

AIMS and Topics

• AIM

- To define that rule and coding guidelines for RTL code, and to give an overview of portability issues

Topics

-Combinational Procedures

-Clocked procedures

Page 124: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

RTL StyleCombinational Procedure

always @ (a or b or c)

begin

. . .

end

Tip

blocking assignment

(=) should be used

Clocked Procedure

always @ (posedge clock)

Begin

. . .

. . .

end

Tip

Non-blocking assignment (<=) should be used

Page 125: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Complete Event List

• Even List for combinational logic must contain all variables read within procedure

What would the behavior be if sel was missing ?

always @ (a or b or sel) begin if (sel = = 1) y = a; else y = b; end

Page 126: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comIncomplete Event List

always @ (a or b or sel) begin if (sel = = 1) y = a; else y = b; end

Synthesis For combinational logic, include all variables read in event list,

always @ (a or b) … a

b

sel

y

always @ (a or b or sel) …

a

b

sel

y

Page 127: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Incomplete Assignments in Combinational Logic

• What is the value of b if ctrl = 0 ?

• What hardware would be built it this is synthesized ?

• How can you avoid this type of hardware ?

module incomplete (ctrl, a, b); input a, ctrl; output b; reg b;

always @ (ctrl or a) if (ctrl) b = a; endmodule

Page 128: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com Avoiding Latches

• Two ways to avoid latches:-

•Use default statement•Add else clause

Question which do you think would be best for a procedure with complex nested if statements?

module completel (ctrl, a, b); input a, ctrl; output b; reg b;

always @ (ctrl or a) begin b = 0; // default if (ctrl) b = a; end endmodule

module complete2 (ctrl, a, b); input a, ctrl; output b; reg b; always @ (ctrl or a) begin if (ctrl) b = a ; else b = 0; / / default end endmodule

Page 129: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Continuous Assignments

• Continuous assignments drive values onto nets-Outputs update simultaneously with any input change

-Combinational logic is implied

module orand (out, a, b, c, d, e); input a, b, c, d, e; output out;

assign out = e & (a b) & (c d) ; endmodule

out

a b e

c d

Page 130: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comRules for the Synthesis of

Combinational Logic

• Complete event list• Default assignments to prevent latches• Use blocking assignments• Continuous assignment synthesizes to

combinational logic• Avoid combinational feedback loops• (Functions synthesize to combinational logic)

– Functions will be described later

Page 131: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comRegister Inference in Clocked

Procedures module counter (count, clk); output [3:0] count; input clk; reg [3:0] count;

always @ (posedge clk) if (count > = 9) count < = 0 ; else count < = count + 1; endmodule

• Clocked procedures triggered on clock edge

•Use only posedge/negedge in event list

• Registers are inferred on all non-blocking assignments in synchronous procedures

+

<

1

9

0

clk

count

sel

0 1

4

4 4

4

Question What is the issue with this counter description?

Page 132: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comResetting Clocked Logic

Synchronous Reset Asynchronous Reset module counter (count, clk, rst); output [3:0] count ; input clk, rst; reg [3:0] count ;

always @ (posedge clk) if (rst) / / active high reset else if (count > = 9) count < = 4’ b0 ; else count < = + 4’ b1 ; endmodule

module counter (count, clk, rst); output [3:0] count; input clk, rst; rst [3:0] count;

always @ (posedge clk or posedge rst) if (rst) // active high reset count < = 4 ‘ b0; else if (count < 9) count < = 4 ‘ b0; else count < = count + 4 ‘ b1; endmodule

• if-else used to add reset to clocked procedure

• if defines reset behavior• First else defines clocked behavior• For asynchronous resets, active edge of reset added to event list

Page 133: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Clocked Procedure Templates always @ (posedge clk or negedge rst) if (!rst) begin // asynchronous reset behavior end else begin // all synchronous actions end

always @ (posedge clk) if (!rst) begin // synchronous reset behavior end else begin // all synchronous actions end always @ (posedge clk) begin // all synchronous actions end

• always procedure• Event list only contains:-

• posedge/negedge reset• posedge/negedge reset for asynchronous reset

• Code must follow these templates

TIP Keep procedures with asynchronous resets separate from procedures with synchronous resets.

Page 134: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSynchronous Feedback Inferrence

• Incomplete assignment in clocked procedure implies synchronous feedback

module dffn (q, d, clk, en); input d, clk, en; output q; reg q;

always @ (posedge clk) if (en) q < = d;

endmodule

0

1 d en

clk

mux q

Page 135: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comClocked Procedure Assignment

a b c

clk

QuestionHow would you code this design in Verilog?

Page 136: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comBlocking and Non-blocking

Assignment always @ (posedge clk) begin c < = b; b < = a; end

always @ (posedge clk) begin c = b; b = a; end

always @ (posedge clk) begin b < = a; a < = b; end

always @ (posedge clk) begin b = a; c = b; end

• Easier to use non-blocking assignment to infer registers in synchronous procedures

• Order independent• Register inferred for each assignment

1

3

2

4

Page 137: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

The Synthesis Process

Page 138: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

AIMS ANDS TOPICS

* AIMS- To introduce synthesis process and look at its strenths and weaknesses

* TOPICS- How a synthesis tool works- Synthesis based methodology- Synthesis strengths and weakness- Programmable Logic device synthesis issues- Language subsets

Page 139: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

clk

WHAT DOES SYNTHESIS DO?* Infers registers from cloked procedures* Builds optimized combinational logic* A new engineer task:

- How much of it?- How well?- Do you trust it?

Page 140: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Constraints File

Verilog code

Technology library

SynthesisEngine

Gate Level Netlist

Schematic

area/Speed Curve

Area

I/S

peed

* Verilog code is the important input - the quality of results depends mainly on the code* Technology Libraryis used to build the circuit from the verilog description* Constraints File drives the synthesis engine

Synthesis flow

Page 141: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

How Synthesis worksConstrains file Verilog code

Gate Level Netlist

Technology Library

Schematic

Boolean

Gates

Mapping

Optimization

Parsing

Page 142: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

clk

Coding Styles Affect Results* Number of registers

- Combinational logic optimised only, not register numbers or placement* Amount of combinational logic inbetween registers - Pipelining and logic timing mut be considered when code written* structure of .logic

Page 143: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Translation Can Be Literal!* Synthesis tools generate logic directly from the structure of your code-Here == operator is redundant but may still appear in the synthesized netlist

always @ (posedge clk) if (d < 3) y <= a;else if (d > 3) y <=b; else if (d == 3) y <= c;

? QuestionWhat would be the input at “?“

mux mux mux

clk

a

b

c

?

01

1 1

0 0

> <

=

dd

d

011011 011

y

Inferred hardware structure

Page 144: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What Synthesis Sometimes Can’t Do Well..

* Clock trees - Usually require detailed, accurate net delay information* Complex clocking schemes - Synthesis tools prefer simple single clock synchronous designs* Memmory, IO pads, technology -specific cells - You will probably need to instantiate these by hand* Specific macro -cells* Always as well as you can - Although it can analyze hundreds of implementations in the time taken for designer to analyze one

Page 145: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comProgrammable Logic Device Specific Issues

* Different architectures for different technologies* Fixed architecture within a specific technology* Architecture specific ‘tricks‘ for good utilization and speed* Code becomes technology specific* How your synthesis tool handles your technology

Page 146: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

A Synthesis Methodology

synthesis

rtlsimulation

gatesimulation

Change constraints file

change code

constraints tech library

verilog

testbench

n

y

y

n

comparegolden results results

change code

functional?

netlist

meets area/speed?

Page 147: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Language Support

Full Verilog LanguageSynthesis Subset

Tool1

Tool3

Tool2

Tool4

Tool5

* Synthesizeable Verilog is a subset of the full language* There is no standard for synthesizeable code* Diferent tool vendors have slightly different interpretations of what is synthesizeable

Page 148: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSummary

* RTL for synthesis* Logic and gate optimization* Coding style affects results* Synthesis tools support subsets of language style

Page 149: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Coding Guidelines

Page 150: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Blocking and nonblocking statementsCoding guidelinesCoding for Performanance(Examples)

Page 151: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comBlocking and non-blocking

assignments• Guidelines

– Use blocking assignments in always blocks that are written to generate combinational logic

– Use nonblocking assignments in always blocks that are written to generate sequential logic

• Ignoring these guidelines can result in a mismatch between behavior of synthesized circuit and the pre-synthesis simulation results

Page 152: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Comparison

• Evaluation of blocking statements requires less simulator memory

• Evaluation of Non blocking statements requires more simulator time

Page 153: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Coding Guidelines

Page 154: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Guideline 1

• To model combinational logic within an always block, use blocking statements

a

b

c

out

always @(a or b or c)

temp = a & b;out = c & temp;

endmodule

temp

Page 155: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Guideline 2

• In order to model sequential logic, use non-blocking assignment statements

Page 156: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Guideline 3

• In order to model latches, use non-blocking statements

Page 157: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What’s wrong with this block?

always @(test or PC or AluOut) begin if (select) begin

output = PC; end else begin

output = AluOut; end

end

Hint: Look at the sensitivity list.

Page 158: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Sensitivity List

• A signal that appears on the right-hand side of a combinational always block must appear in the sensitivity list of the always block.

• The only exceptions here are signals that are also generated in the always block (are on the left-hand side). – Verilog only evaluates always blocks only when a signal in the

sensitivity list changes. always @(a or b or c)

temp = a & b;out = c & temp;

endmodule

Page 159: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What’s wrong with this block?

always @(select or PC or AluOut or IR1 or add3) begin if (select == 2'h0) begin

output1 = PC; output2 = add3

end else if (select == 2'h3) begin output1 = AluOut; output2= IR1;

end end

Selector

PC add3 AluOutIR1

output1 output2

select

2

Page 160: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comIf/Case construct in

Combinational always block• Each left-hand side signal must be assigned in

every possible case. • If it is not assigned to in one of the cases, then

you have "implied a latch" -- there is some set of inputs for which this gate does not take on a new value and therefore "holds" its old value.

• No longer a combinational logic element!

Page 161: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Correct implementationalways @ (select or PC or AluOut or IR1 or add3 or output1 or

output2) begin

if (select == 2'h0) begin output1 = PC;output2 = add3

end else if (select == 2'h3) begin output1 = AluOut; output2= IR1;

end else begin output1 = output1; output2 = output2;

end end

Page 162: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

What’s not good here?

always @(posedge CLK) begin Q <= `TICK D; Z <= `TICK (a ^ b) & (sig1 | sig2);

end

absig1sig2

D Q

Z

Page 163: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

More readable code

wire nextZ; assign nextZ = (a ^ b) & (sig1 | sig2); always @(posedge CLK)

begin Q <= `TICK D; Z <= `TICK nextZ;

end

bsig1sig2 nextz

Q

Z

Da

Page 164: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Add comments in your code

• Others can read and understand your design• You can understand your design after 3 months

when you may have to debug the design!• Make sure that you modify the comments if you

are modifying the design!• If you are modifying someone else’s code, add

comments regarding what modification you made and the date of modification.

• Do not delete old code; comment it.• Learn to write simple and helpful comments.

Page 165: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Indentation

• Indent your code.

• Proper indentation makes your code easier to read and debug.

• Indentation also forces you to write better code: levels of nesting will be in kept in check!

Page 166: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

`define statements

• Do not use hardwired constants all over the place; instead, use meaningful names.

if (opcode == 6b`000010) then beginend else if (opcode = 6b`000011) then beginend

`define ADD 6b`000010`define SUB 6b`000011

if (opcode == `ADD) then beginend else if (opcode = `SUB) then beginend

Page 167: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Examples of coding style

Page 168: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Priority Encodermodule my_if (c, d, e, f, s, pout); input c, d, e, f; input [1:0] s; output pout; reg pout; always @ (s or c or d or e or f) begin : myif_pro

if (s == 2'b 00) begin pout <= c;

end else if (s == 2'b 01 ) begin pout <= d;

end else if (s == 2'b 10 ) begin pout <= e;

end else begin pout <= f;

end end endmodule // module my_if

Page 169: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiplexer

module mux (c, d, e, f, s, muxout); input c, d, e, f; input [1:0] s; output muxout; reg muxout; always @ (s or c or d or e or f) begin : mux1 case (s)

2'b 00: begin muxout <= c; end 2'b 01: begin muxout <=d; end 2'b 10: begin muxout <= e; end default: begin muxout <= f;

end endcase end endmodule // module mux

c

d

e

f

s

Page 170: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiplexer vs Latch

if (select) y = a;

else y = b;

a

b

y

if (select) y = a;

a y

select

Page 171: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comRegister with Asynchronous

Reset

module dff_async_reset (data, clk, reset, q); input data, clk, reset; output q; reg q; always @ (posedge clk or negedge reset)

if (~reset) q = 1’ b0

else q = data;

endmodule

data q

reset

clk

Page 172: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comClock-triggered Flip-flop with

Enable control

module ff_clk (d, en, clk, clr, q); input d, en, clk, clr; output q; reg q; always @ (clk or clr) begin

if (clr == 1'b 0) begin q <= 1'b 0; end else if (clr & clk == 1'b 1 ) begin if (en == 1'b 1) begin q <= d; end end

end endmodule / / module ff_clk

q

clr

d

clk

en

Page 173: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Resource Sharing:I

A

B

C

D

+

+

Mux

select

if (select) sum <= A + B;

else sum <= C + D;

We are sharing the multiplexer.

sum

Page 174: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Resource Sharing:II

A

B

C

D

mux

mux

+select

select

if (select) begintemp1 <= A; temp2 <= B;

endelse begin

temp1 <= C; temp2 <= D;

endsum <= temp1 + temp2;

sum

We are sharing the adder.

Page 175: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Resource Sharing:III

vsum = sum; for (i=0;i<3;i++)begin

if (req[i]=1‘b1) begin vsum <= vsum + offset[i];

end; end loop;

Offset[0]

Offset[1]

+0 mux

vsum

0 mux +

Offset[2]

0 mux +

Page 176: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Resource Sharing:IV

Offset[0]

Offset[1]

+

mux

vsum

Offset[2]

R

mux

0

Can we rewrite to code to generatehardware that looks like this?

Page 177: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Code that forgets performance

sum := start; for (i=0;i<2;i++)begin

sum <= sum + inc[i]; end; +

start

inc[0]

+

inc[1] +

inc[2]sum

Page 178: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Performance-oriented coding

sum = ((inc[2] + inc[1]) + ((inc[0] + start));

+

start

inc[0]

+

inc[2]

inc[1]

+sum

Loop Unrolling performed by designer!

Page 179: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comOverchecking for conditions can

increase hardware

always @ (posedge clk) begin if (req == 4'b1000)

data_out <= data_in; end

end

data_outdata_in

clken

req

Page 180: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simplifying the code

always @ (posedge clk) begin if (req(3) == 1'b1)

data_out <= data_in; end

end

data_outdata_in

clken

req[3]

Page 181: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Optimization in case statements

always @ (posedge clk) begin if (req) begin case (r)

5'b00001: c <= a(0); 5'b00011: c <= a(1); 5'b00101: c <= a(2); 5'b00111: c <= a(3); 5'b01001: c <= b(0); 5'b01011: c <= b(1); 5'b01101: c <= b(2); 5'b01111: c <= b(3); default: c <= 1'bx;

end case end

Page 182: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comHow can we obtain this

hardware instead?

8-to-1 mux

a[3:0]

b[3:0]

r [3:1]

r[4]

r[0]

DFF

clk

c

Page 183: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Summary

• Synthesis is still an evolving art– Unless you describe exactly what you want,

the synthesizer will misunderstand you!

• Following a set of guidelines will help

• Good coding styles will help you and the synthesis tool

Page 184: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Finite State Machines

Page 185: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Topics

• FSM Basics

• Steps for FSM design

• Example design

• HDL code for FSM

Page 186: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Any Sequential Logic Circuit is a State Machine

• Single flip-flop has two states - `0`, `1`

• A circuit with 2 flip-flops can have a maximum of 4 states.

• n flip-flops can have 2n states.

Page 187: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

D Q

CLK

Flip Flip as an FSM

Page 188: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simple Transition Sequence

• Sequential circuits like counters and shift registers have a fixed transition sequence

• Counters - 00000, 00001, 00010, 00011… each count is a state, total 25

• Shift Registers - 00001, 00010, 00100, each shift position is a state, total 5

Page 189: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

TO

00p25p Possible50p Possible Possible75p Possible Possible

100p Possible Possible Possible Possible00p 25p 50p 75p 100p

FROM

Complex trasitionsCoin collection FSM

Page 190: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comWhat is an FSM?

Design Specification Point of View

• State machines are a means of specifying sequential circuits which are generally – complex in their transition sequence – and depend on several control inputs.

Page 191: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comWhat is an FSM?

Digital Circuit Point of View

• State machines are a group of flip-flops, whose group-state transition pattern (from one set of values to another ) is– generally unconventional– and depends on several control inputs

Page 192: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

CLOCK

ASYNCCONTROL

CURRENTSTATE

CONTROLINPUTS

NEXTSTATE

CURRENTSTATE

COMB.LOGICforNEXTSTATE STATE

REGISTERFLIP-FLOPS

PORTS

CO

MB

INA

TO

RIA

LA

CT

ION

PO

RT

SR

EG

IST

ER

ED

AC

TIO

N P

OR

TS

FSM Structure

Page 193: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

FSM Design Steps

• Define the ports

• Define the states

• Define transitions and conditions

• Define the actions

• Write code for synthesis

Page 194: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comState Machine: State Diagram

A3’b000

E3’b110

C3’b011B

3’b001

D3’b010

01 = 1’bo01 =1 ’bo

b=1 ’ b 1

b= 1’b o

a= 1’b1

01 =1’b002 =1’b0

{a, b} = 2’b11

a= 1’b0

a =1’b1

01= 1’b002= 1’b1

01 = 1’b002 = 1’b0

01 = 1’b102 = 1’b1

State Names(A,B,C,D,E,)State encoding:A=3’ b000,B=3’b001…Transition Conditions:{a ,b}=2’b01Output values:01=1’b0

{a ,b}=2’b01

Page 195: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comState Machine: Declarations and Clocked

Procedure• Use parameters for state encoding• Reset strategy for state register• Partition into clocked procedure and combinational procedures

module fsm (a, b, clock, reset, 01, 02); input a, b, clock, reset; output 01, 02 ; // parameter declarations (state encoding) parameter A = 3’b000, B = 3’b001, C = 3’b011, D = 3’b010, E = 3’b110; // wire and reg declarations reg [2:0] state, next_state ; reg 01, 02 ; // clocked procedure always @(posedge clock or posedge reset) begin: STATEREGISTER if (reset) state < = A; else state < = next_state ; end …

State registerOutput Logic 01

02

a bNext State Logic

Next_state

state

Page 196: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comState Machine: Declarations and Clocked

Procedure• Use parameters for state encoding• Reset strategy for state register• Partition into clocked procedure and combinational procedures

module fsm (a, b, clock, reset, 01, 02); input a, b, clock, reset; output 01, 02 ; // parameter declarations (state encoding) parameter A = 3’b000, B = 3’b001, C = 3’b011, D = 3’b010, E = 3’b110; // wire and reg declarations reg [2:0] state, next_state ; reg 01, 02 ; // clocked procedure always @(posedge clock or posedge reset) begin: STATEREGISTER if (reset) state < = A; else state < = next_state ; end …

State registerOutput Logic 01

02

a bNext State Logic

Next_state

state

Page 197: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comState Machine: Combinational

Procedures always @ (a or b or state) begin: NEXTSTATE next_state = state ; case (state) A : begin if (a) next_state = C; else if (b) next_state = B; end B: begin if (~b) next_state = A; else if ( { a,b} = = 2’b01) next_state = D; end C: begin if (a) next_state = E; else if ( {a,b} = = 2’b11) next_state = D; end D:next_state = A; E: if (~a) next_state = C; end // end next state logic

always @ (state) begin: OUTPUTDECODE // DEFAULT ASSIGNMENTS 01 = 1’b0 ; 02 = 1’b0 ; case (state) B: begin 01 = 1’b1; 02 = 1’b1; end E: 02 = 1’b1; end end // end output decode logic

Next state and output decode combinational procedures could be merged Next state and state register procedures could be merged

Page 198: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

If Synthesis

module if_example (a, b, c, ctrl, op); input a, b, c; input [3:0] ctrl ; output op; reg op;

always @ (a or b or c or ctrl) if (ctrl) = = 4’b0000) op = a; else if (ctrl < = 4’b0100) op = b ; else op = c ;

endmodule

Question Draw the architecture of hardware that this represents.

Page 199: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

If and Case Architectures if (ctrl = = 4’b0) op = a ; else if (ctrl < = 4’d4 ) op = b ; else op = c ;

case (ctrl) 0 : op = a; 0,1,2,3,4 : op = b; default: op = c; endcase

if synthesis

ctrl

4

ctrl0 1

o 1

c b a

0 op

<=

=

Question What hardware structure is created for a case statement?

Depends if case statement is parallel or not!

Page 200: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Case Synthesis• Case statement allowed to have overlapping choices

– Choices prioritized in order of appearance

• Some synthesis tools infer priority encoder structure– Even for cases with no choice overlap

• Case with mutually exclusive choices can be built with non-prioritized logic

case (ctrl) 0; op = a ; 0, 1, 2, 3, 4 : op = b ; default op = c ; endmodule

case (ctrl) 0: op = a ; 1, 2, 3, 4 : op = b ; default : op = c ; endcase

Prioritized case synthesis

<= 0 1

0 1

ctrl c b a

4 ctrl

0

=

op

Page 201: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comParallel Case Statement

• Case with mutually exclusive choices known as parallel case– Can be implemented with

non-prioritized logic• Most synthesis tools can

recognize parallel case– Others may need to be told

case is parallel• Directives can be used to control

synthesis– Embedded comments which

are recognized by synthesisImportantNever apply directive to a non-

parallel caseTip: If your synthesis tool supports

it, create parallel case by design not by directive

case (ctrl) 0 : op = a ; 1, 2, 3, 4 : op = b ; default : op = c ; endcase case (ctrl)

// rtl_synthesis parallel_case 0 : op = a ; 1, 2, 3, 4 : op = b ; default op = c ; endcase

<ctrl

5 ctrl

5

>

c b a

op

parallel case synthesis

Page 202: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSynthesis Directives

• Most synthesis tools handle directives or programs• Directives are verilog comments, ignored by simulation but

meaningful to synthesis– Aim is to control synthesis optimization from within the RTL code.

case (test) // rtl_synthesis parallel_case 2’b00: op = 1 ; 2’b01, 2’b10: op = 2 ; 2’b11: op = 3 ; default : // rtl_synthesis off $ display (“unknown test!”); // rtl_synthesis on endcase

$display writes a message to the simulator transcript window

CautionCan lead to different RTL/Gate level functionality from Same design – use With caution!

Page 203: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comCasez Synthesis

• casez is treated similar to case by the synthesis tool

• casez can be parallel or non-parallel– Parallel casez will synthesis

to parallel logic– Non-parallel casez will

synthesize to prioritized logic

• Synthesis tool may need to be told casez is parallel

ImportantMake sure casez actually is parallel

before using directives

QuestionAre these casez statements parallel

or not?

always @ (pri_in) begin casez (pri_in) 4’ b1??? : op = 3 ; 4’ b01?? : op = 2 ; 4’ b001? : op = 1 ; 4’ b0001 : op = 0 ; default : op = 0 ; endcase end

always @ (ctrl) begin {int0, int1, int2 } = 3’ b000 casez (ctrl) 3’ b?/1 : int0 = 1’ b1 ; 3’ b?1?: int1 = 1’ b1 ; 3’b1?? : int2 = 1’ b1 ; endcase end

Page 204: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Full Case • Case branches do not need to cover all values for case expression– Can cause incomplete

assignments in combinational code.

-Will synthesze latches

• Full case (for synthesis) covers all binary values of case expression.– Ignoring x and z value

combinations

always @ (ctrl or b or c) case (ctrl) 0, 1: op = b ; 2: op = c ; default : op = 0 ; endcase

// declarations for examples module case_1 (b, c, ctrl, op) ; input [3:0] b, c ; input [1:0] ctrl ; output [3:0] op ; reg [3:0] op

always @ (ctrl or b or c) case (ctrl) 0, 1 : op = b ; 2 : op = c ; endcase

always @ c(ctrl or b or c) case (ctrl) 0, 1 : op = b ; 2 : op = c ; 3 : op = 0 ; endcase

Full case for synthesis

case not full- latches inferred

default makes full case for synthesis and simulation

Page 205: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Full Case Directive• Most synthesis tools can

recognize full case– Others may need to be told

case is full• Can use synthesis directive to

force full case• What happens if directive

applied to case description which is not full?– Assumes missing case

values can be implemented as “don’t care”

– Can cause RTL to gate level simulation mismatches

• Full case issue avoided if default assignments used

always @ (ctrl or b or c) //rtl_synthesis full_case case (ctrl) 0, 1 : op = b ; 2, 3 : op = c ; endcase

Caution Make sure case actually is full before using directives

always @ (ctrl or b or c) begin op = c ; case (ctrl) 0, 1 : op = b ; 2 : op = c ; endcase end

Page 206: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comCase Directive Exceptions

• A full case statement can still synthesize latches– Even if the full_case directive and default option are used

• Incomplete assignments can occur for any variable assigned to in a combinational procedure.– Default statements can prevent problems

module select (a, b, sl ) ; input [1:0] sl ; output a, b ; req a, b ; always @ (sl) case (sl) // rtl_synthesis full_case 2’ b00 : begin a = 0 ; b = 0 ; end 2’ b01 : begin a = 1 ; b = 1 ; end 2’ b10 : begin a = 0 ; b = 1 ; end 2’ b11 : b = 1 ; default : begin a = ‘bx; b = ‘bx; end endcase endmodule

QuestionThere is latch inferred from this code. What is the name of the latches variable and how can it be prevented?

Page 207: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Initial Statements module counter (clk, q ) ; input clk ; output [ 3 : 0 ] q ; reg [ 3 : 0 ] q :

initial q = 0 ; always @ (posedge clk) if (q > = 9) q < = 4 ‘ b0 ; else q < = q + 1 ; endmodule

module counter (clk, rst, q ) ; input clk, rat ; output [3 : 0] q ; reg [3 :0] q ; always @ (posedge clk) if (rst) q < = 4’ b0; // synchronous reset else if (q >= 9) q < = 4’ b0; else q < = q + 1 ; endmodule

QuestionWhat does this initial statement mean:1.For simulation?2.For synthesis?

Synthesis Synthesizable equivalent-add reset

Page 208: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Summary

• FSM is a systematic way of specifying any sequential logic

• Ideally suited for complex sequential logic

• Translating the problem in terms of discrete states is the “difficult” part

• Define the FSM and generate the code

Page 209: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Structural Modeling

Page 210: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comAims and Topics

* Aims - Learn about the full capabilities of verilog for structural ,gate level modeling and modeling memories* Topics - Built in primitives - Modeling memories

Page 211: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comStructural Modeling

* Pure structural model only contains instantiated modules, primitives and wire connections* Used for block diagrams, schematics, post synthesis netlist and ASIC/FPGA

a

sel

b

out

selb

nsela

nsel

module mux (a, sel, b, out);input a, sel, b;output out;wire nsela, selb, nsel;OR2 U32(.A(nsela), .B(selb), .Z(out) );IV U33 (.A(sel), Z(nsel) );AN2 U34 (.A(a), .B(nsel), .Z(nsela) );AN2 U35 (.A(b), .B(sel), .z(selb) );endmodule

Page 212: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Conditional Primitives

* Four different types of conditional primitives* Conditional primitives only have three pins: output, input and enable* Enabled and disabled by the enable pin - When disabled outputs are at high impedance

Primitive Name Functionality

Conditional buffer with logic 1 as enabling inputConditional buffer with logic 0 as enabling inputConditional inverter with logic 1 as enabling inputConditional inverter with logic 0 as enabling input

bufif1bufif0notif1notif0

Page 213: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Conditional Buffersbufif1

data out

enable

bufif1(out, data, enable)

bufif1

out

enable

bufif1(out, data, enable)

data

enable

bufif1

data

0 1 x z 0 z 0 L L 1 z 1 H H x z x x x z z x x x

bufif0 0 1 x z 0 0 z L L 1 1 z H H x x z x x z x z x x

enable

note : Verilog uses the symbols L and H to represent partially unknown logic values

Page 214: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Modeling a Memory Device

A memory device must do two things : * Declare a memory of appropriate size* Provide some level of access to its contents, such as :

- Read only- Read and Write- Write and Simultaneous read- Multiple reads , simultaneous to a single write- Multiple simultaneous reads and writes, with some method of ensuring consistency

Page 215: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simple ROM Model

ROM data is stored in a separate file

‘timescale 1ns / 10psmodule myrom (read_data, addr, read_en_);input read_en_;input [3:0] addr;output [3:0] read_data;reg [3:0] read_data;reg [3:0] mem [0:15];

initial$readmemb (“my_rom_data“, mem);

always @ (addr or read_en_) if (! read_en_) read_data = mem[addr];endmodule

my_rom_data

0000010111000011110100100011111110001001100000011101101000011101

Page 216: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simple RAM Model

Note :Simultaneous models for internal RAM/ROM usually supplied by technology vendor

module mymem (data, addr, read, write);inout [3:0] data;input [3:0] addr;input read , write;reg [3:0] memory [0:15];// read

assign data = (read ? memory [addr] : 4’bz);// write always @ (posedge write)

memory[addr] = data;endmodule

4 bit , 16 word array formemory contents

tr i- state controllerenabled by read

rising edge triggered RAM write

Page 217: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Scalable Memory device

* Parameters can be used to scale memory models

module scalable _ROM (mem_word, address);parameter addr_bits = 8;parameter wordsize = 8;parameter words = (1 << addr_bits);

output [wordsize : 1] mem_word;input [addr_bits : 1] address;

reg [wordsize : 1] mem [0 : words - 1];// output one word of memorywire [wordsize : 1] mem_word = mem[address];

endmodule

size of address buswidth of memory word

size of memory

output word

address bus

memory declaration

continuousassignmentto output

Page 218: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Loading a Memory

* ROM will need to be loaded with data* RAM may need to be initialzed* Memory can be pre - loaded via loops or from an external file

// initialize memory via loopfor (i = 0 ; i< memsize ; i = i+1) mema [i] = {wodsize {1 ‘b0}};

// load memory from a file$ readmemb (“mem_file . txt“, mema);

Page 219: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Using inout Ports

module mymem (data , addr , read , write);inout [3 : 0] data;input [3 : 0] addr;input read, write;.............

assign data = (read ? memory[addr] : 4’ bz);...................

* Bi - directional ports are declared with the inout keyword* You can not directly connect an inout port to a register* Your design should drive an inout port from only one direction at a time

- To avoid bus contention- You must design logic around the inout port to ensure

proper operation

Page 220: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Bidirectional Ports Using Primitivesen_a_b

b1

b2

bus_a bus_b

en_b_a

module bus_xcvr(bus_a , bus_b, en_a_b, en_b_a);input bus_a, bus_b;input en_a_b , en_b_a;bufif1 b1 (bus_b , bus_a , en_a_b);bufif1 b2 (bus_a , bus_b , en_b_a);//structural module logicendmodule

When en_a_b = 1,primitive b1 is enabledand the value on bus_a is transferred to bus_b

When en_b_a = 1,primitive b2 is enabledand the value on bus_b is transferred to bus_a

Page 221: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Bidirectional Ports Using Continuos Assignment

en_a_bb1

b2

bus_a bus_b

en_b_a

module bus_xcvr(bus_a , bus_b, en_a_b, en_b_a);input bus_a, bus_b;input en_a_b , en_b_a;assign bus_b = en_a_b ? bus_a : ’bz;assign bus_a = en_b_a ? bus_b : ’bz;//structural module logicendmodule

When en_b_a = 1,this assignment drivesthe value of bus_b on to bus_a

When en_a_b = 1,this assignment drivesthe value of bus_a on to bus_b

Page 222: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Modeling Memory PortsTest Bench

rd

RAM cell

data reg

databus

wr

module ram_cell (databus, rd, wr);input databus;input rd, wr;reg datareg;

assign databus = rd ? datareg : ‘bz;always @ (negedge wr); datareg <= databus;endmodule

when rd = 1 the valueof datareg is assignedto databus

When wr deassertsthe value of databusis writteb to datareg

Page 223: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Gate level Modeling

Page 224: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comAims and Topics

* Aims- Understand how to model simple delays for simulations and gate level models

* Topics- Lumped delays- Distributed delays- Path delays- Specify timing blocks

Page 225: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Delay Modeling Types

Delays can be modeled in three ways :Typical delay specificationdelay from a to out =2delay from b to out = 3delay from c to out = 1

out

net1n1

o1

a

b

c

1

32

distribute thedelay across each gate

Use a specify block to specify pin-to-pindelays for each path

Lump the entire delayat the last gate

noror ASIC cell

Page 226: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

out#3

a

b

c

Lumped Delay* Lumped delays place entire delay on the last gate

-Simple to implement- Does not allow for different path delays

path delay as modeled a -> out is 3 b -> out is 3 c -> out is 3

‘timescale 1ns / 1nsmodule noror (out, a, b, c);output out;input a, b, c;nor n1 (net1, a, b);or #3 o1 (out, c, net1);endmodule

Page 227: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

out

#2

#1

a

b

c

Distributed Delays* distributed delays divide delay over more than one gate

- Allows different delays for different paths- Delays accumulate along the path

path delay as modeled a -> out is 3 b -> out is 3 c -> out is 1

‘timescale 1ns / 1nsmodule noror (out, a, b, c);output out;input a, b, c;nor #2 n1 (net1, a, b);or #1 o1 (out, c, net1);endmodule

Page 228: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

out

net1n1

o1

a

b

c

Module Path Delays* Specify block allows individual path delay to be defined

- Paths from the inputs to outputs of a module

path delays a -> out is 2 b -> out is 3 c -> out is 1

Page 229: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

The Specify Block

* Specify block defines module timing data - Separates timing information from functionality* Typical tasks for specify block: - Define module timing paths - Assign delays to those paths - Perform timing checks * Module parameters can not be used in a specify block - Specify blocks use a special “specify parameter“ (specparam) - See later .............

module noror (out, a, b, c);output out;input a, b, c;nor n1 (net1, a, b);or o1 (out, c, net1);

specify(a => out) = 2;(b => out) = 3;(c => out) = 1;

endspecify

endmodule

Page 230: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Specify Block Parameters

* Specparam declares parameters for specify block* Must be declared inside specify block - Only visible inside block* Cannot be over-ridden like parameters* Parameters cannot be used inside a specify block - Must use specparam

Module noror (op. a, b, c);output op;input a, b, c;nor n1 (net1, a, b);or o1 (op, c, net1);

specifyspecparam aop = 2;

bop = 3; cop = 1;

(a => op) = aop;(b => op) = bop;(c => op) = cop;

endspecifyendmodule

Page 231: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Accurate Delay Control

*Rise, fall and turn-off delays can be specified for gates and module paths- Rise is transition to 1- Fall is transition to 0- Turn-off is transition to z

and # (2, 3) (out, in1, in2, in3); // rise, fallbufif0 #(3, 3, 7) (out, in, ctrl); // rise, fall. turn-offspacify

(in => out) = (1, 2); // rise, fall(a = > b) = (5, 4, 7); // rise, fall, turn-offs

endspecify

* Minimum , typical and maximum values can be specified for each delay- Syntax - (minimum : typical : maximum)

or # (3 . 2 : 4 . 0 : 6 . 3) o1 (out, in1, in2); // min : typ : maxnot # (1 : 2 : 3, 2 : 3 : 5) (o, in); // min : typ : max for rise, fallspecify// min:typ:max for rise, fall and turn-off(b => y) = (2 : 3 : 4, 3 : 4 : 6, 4 : 5 : 8);endspecify

Page 232: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Parallel and Full Connection Module Paths

* => represents parallel connection- Must be between ports must be of the same size

* * > represents full connection- All listed inputs connect to all listed outputs

Parallel module patha

b

q

qb

inputbits

outputbits

2 paths

Bit - to - bit connectionsUse => to define path

(a, b => q, qb) =15; is equivalent to (a => q ) = 15; (b => qb ) =15;

Full module path

inputbits

a

b

q

qb

outputbits

4 pathsBit - to - vector connections Use *> to define path

(a, b *> q, qb) = 15; is equivalent to(a => q ) = 15;(b => q ) = 15;(a => qb ) = 15;(b => qb ) = 15;

Page 233: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

State Dependent Path Delays

* State dependent path delay are assigned to module path only if a specific condition is true

- Note : not an if statement - no else is allowed....

a

bop

module jexor (op, a, b);input a, b;output op;

xor (op, a, b);

specifyif (a) (b => op) = (5 : 6 : 7);if (!a) (b => op) = (5 : 7 : 8);if (b) (a => op) = (4 : 5 : 7);if (!b) (a => op) = (5 : 7 : 9);

endspecifyendmodule

Page 234: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

User Defined Primitives

Page 235: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comAIMS AND TOPICS

Aims

* Learn how to build logic using user defined primitives

Topics

* Understand verilog composite libraries* Understand functional modeling of ASIC libraries* Learn about the use of UDPs in ASIC library models

Page 236: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

WHAT IS A UDP ?Verilog has over two dozen gate level primitives for modelingstructural logic . In addition to these primitives Verilog has user defined primitives (UDPs) that extend the built in primitives by allowing you to define logic in tabular format.

UDPs are useful for ASIC library cell design as well as small scale chip and medium scale chip design * You can use UDPs to augment the set of predefined primitive element s * UDPs are self contained , they do not instantiate other modules * UDPs can represent sequential as well as combinational elements * UDP behavior is described in a truth table * To use a UDP you instantiate like a built in primitive

Page 237: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

FEATURES

* UDPs can have only one output* UDPs can have 1 to 10 inputs* All ports must be scalar and no bi-directional ports are allowed* The Z logic value is not supported* The output port must be listed first in the port list * The UDP output terminal can be initialized to a known value at the start of simulation* UDP can not be synthesized

Page 238: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

COMBINATIONAL EXAMPLE : 2 - 1 MULTIPLEXER

This is thename of the primitive

The output port must be the first port

primitive multiplexer (o, a, b, s);output o;

input a, b, s; table

// a b s : o 0 ? 1 : 0; 1 ? 1 : 1; ? 0 0 : 0; ? 1 0 : 1;

0 0 x : 0; 1 1 x : 1;

endtable endprimitive

These entries reduce pessimism

* UDP definitions occur outside of a module* The output becomes x for any input combination not specified in table

Page 239: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

COMBINATIONAL EXAMPLE : FULL ADDER

CinAB

G1

G3

G2

G4G5

Sum

Cout

U_ADDR2_S

U_ADDR2_C

CinAB

Sum

Cout

You can implement the full adder with only two combinational UDPs cont........next...

Page 240: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

//FULL ADDER CARRY- OUT TERM

primitive u_addr2_c (co, a, b, ci);output co;

input a, b, ci; table

a b ci : co 1 1 ? : 1; 1 ? 1 : 1; ? 1 1 : 1; 0 0 ? : 0;

0 ? 0 : 0; ? 0 0 : 0;

endtable endprimitive

//FULL ADDER SUM TERM

primitive u_addr2_s (s, a, b, ci);output s;

input a, b, ci;

table // a b ci : s 0 0 0 : 0; 0 0 1 : 1; 0 1 0 : 1; 0 1 1 : 0;

1 0 0 : 1; 1 0 1 : 0;

1 1 0 : 0 1 1 1 : 1endtable endprimitive

Page 241: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comLEVEL - SENSITIVE SEQUENTIAL EXAMPLE : LATCH

primitive latch ( q, clock, data);output q;reg q;input clock, data;initial q = 1’ b1;table// clock data current next// state state

0 1 : ? : 1 ;0 0 : ? : 0 ;1 ? : ? : - ;

endtableendprimitive

The ? is used to represent don’t care conditions inthe inputs and current state

Note the use of a register for storageThe output is initialized to 1’ b1

Notice the additional field used to specifya next state

Page 242: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

EDGE - SENSITIVE SEQUENTIAL EXAMPLE : D FLIP - FLOP

primitive d_edge_ff ( q, clk, data );output q;

input clk, data;reg q

table // clk dat state next :

(01) 0 : ? : 0 ; (01) 1 : ? : 1 ; (0x) 1 : 1 : 1 ; (0x) 0 : 0 : 0 ; (x1) 0 : 0 : 0 ; (x1) 1 : 1 : 1 ;

// ignore negative edge of clock (?0 ) ? : ? : - ;

(1x) ? : ? : - ;// ignore data changes on steady clock

? (??) : ? : - ;endtable endprimitive

Page 243: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SHORTHAND TO IMPROVE READABILITY

Verilog has symbols that can be used in UDP table to improve readability

Symbol Interpretation Explanation

b

r

f

p

n

*

0 or 1

( 01) ( 10 )

( 01) or ( 0x ) or ( x1)

( 10 ) or ( 1x ) or ( x0 )

( ?? )

Any known value

0 -> transition

1 -> 0 transition

Any positive edge,including unknowns

Any negative edge,including unknowns

Any transition

Page 244: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

SUMMARY

* UDPs allow you to create your own primitives to extend those built in to Verilog - Behavior is defined using a table - UDPs are instantiated like built - in primitive* They are a compact, efficient method of describing logic functions - Both combinational and sequential behavior can be described - UDPs are self - contained - Many built - in primitives can be replaced by a single UDP* There are some restrictions on using UDPs, including :- - There must be a separate UDP for every output - The Z value is not supported hence UDP ports can not be bi - directional - UDPs are not synthesisable

Page 245: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verification Overview

Page 246: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Objectives

After completing this module ,you will be able to..

•Understand verification flow

•Testbench structure

•Different ways of generating vectors

Page 247: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

Vector generation

Simulation tips

summary

Page 248: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

RTLTB

System Specifications

Test Pass

Yes

Verification Flow

Page 249: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Purpose of writing testbench:

•Instantiate the hardware model under test

•Generate stimulus waveforms in the form of functional test vectors during simulation

•Generate expected waveforms in the form of reference vector and compare with the output from RTL model

•Pass or fail indication

Introduction

Page 250: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Testbench Structure

Introduction

MODEL UNDER TEST

WAVE FORM

GENERATION COMPARE RESULTS

Test vectors File

Results FilesReference Vectors

Stimulus

Vectors Output

Vectors

Page 251: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

Vector generation

Simulation tips

summary

Page 252: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

•Generate vectors “on-the-fly”

•Read vectors from files

•Writing vectors to a test file

Vector generation

Page 253: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Vector generation

Different ways of generating system waveforms

a) Use continuous loops for repetitive signals

b) Use assignments for signals with few transitions

c) Use relative or absolute time generated signals

d) Use loop constructs for repetitive signal patterns

Page 254: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Vector generation

Reading test vectors from file

Writing vectors to a text file

Page 255: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

Vector generation

Simulation tips

summary

Page 256: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation tips

Simulate Corner Cases only

Use code coverage tools

Use the triple equals

Use the $display and $stop statements

Page 257: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Summary

Verification flow

Testbenches

Simulation tips

Page 258: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Testbenches

Page 259: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Aims and Topics

* Aims Learn coding styles and methods that are

commonly used to create a test bench* Topics

- Simulation behavior - Testbench organization - Stimulus - Clock generation

Page 260: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comDesign Organization

simulator

compilation

simulation

includefiles

designfiles

file input:stimulusexpects patterns

file output:stimulusresults patterns

vendorlibraries

dataclkreadwrite

Page 261: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation of a Verilog Model

procedure

procedure

procedure

procedure

procedure

procedure

procedure

procedure

initialavec =----------

x

l

x

x

x

z

o

compilation

initialization

simulation

Page 262: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comTestbench Organization

Testbench

stimulusDesignto verify

stimulus

verify

results

Designto verify

Testbench

* Simple testbench - Just send data to desgin - No interaction - Few Processes

* Sophisticated testbench - Models environment around designs - Talks to design - Evolves towards system model - self - checking

Page 263: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com“In Line“ Stimulus

module inline_tb;reg (7:0) data_bus, addr;reg reset;// instance of DUTinitial

beginreset = 1’bo;data_bus = 8’hoo;# 5 reset = 1’b1;#15 reset = 1’bo;#10 data_bus = 8’h45;#15 addr = 8’hf0;#40 data_bus = 8’h0f;

endendmodule

* Variables can be listed only when their values change* Complex timing relationships are easy to define* A test bench can become very large forcomplex tests

Page 264: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comStimulus From Loops

module loop_tb;reg clk;reg [7:0] stimulus;integer i;//instance of DUT//clock generationinitial

beginfor(i = 0; i<256; i = i+1)@(negedge clk) stimulus = i;

endendmodule

* The same set of stimulus variables are modified inevery iteration* Easy to enter* Compact Description* Timing relationships regular in nature* Best for stimulus:-- Regular values- Set time period

**Important Do not forget to insert timing control in the loop

Page 265: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simple Delays

initial clk=0; always clk = ~clk;

Will above code generate clk?

Page 266: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simple Delays

always #10 clk = ~clk;

#< value> provides simple time delayThis is useful in providing timing for

- Stimulus in testbenches - propagation delays in gate level simulation models

Page 267: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSummary

* There are several Verilog constructs which are very useful in testbench construction e.g.* Several methods of applying stimulus have been examined:- - In-line stimulus from an initial block - Stimulus from loop - Creating clocks

Page 268: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

System Control

Objective:Describe some of the compiler directives , system tasks and system functions available in Verilog

Topics: Text output Simulation control

Page 269: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$display

• displays specified variables on execution -Example: reg[7:0]in_bus; ……… #10; $display(“At time %d in_bus is %h”,$time,in_bus) ……• Output:

At time 10 in_bus is 1f

Page 270: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$monitor

-displays all values in the list each time any of them changes

-$monitor($time, " A = %b B = %b CIN = %b SUM = %B CARRY = %b", A,B,CIN,SUM,CARRY);

Page 271: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$monitormodule TB_FULL_ADD;

reg A, B, CIN; wire SUM, CARRY;

FULL_ADD U1(A, B, CIN, SUM, CARRY);

initialbegin$monitor($time, " A = %b B = %b CIN = %b SUM = %B CARRY = %b", A,B,CIN,SUM,CARRY);A = 0; B = 0; CIN = 0;#5 A =1;B = 0; CIN = 0;#5 A =0;B = 1; CIN = 0;#5 A =1;B = 1; CIN = 0;#5 A =0;B = 0; CIN = 1;#5 A =1;B = 0; CIN = 1;#5 A =0;B = 1; CIN = 1;#5 A =1;B = 1; CIN = 1;#5 $finish;endendmodule

Page 272: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$monitor

Monitor list for full adder test bench 0 a=0 b=0 CIN=0 SUM =0 CARRY=05 a=1 b=0 CIN=0 SUM =1 CARRY=010 a=0 b=1 CIN=0 SUM =1 CARRY=015 a=1 b=1 CIN=0 SUM =0 CARRY=120 a=0 b=0 CIN=1 SUM =1 CARRY=025 a=1 b=0 CIN=1 SUM =0 CARRY=130 a=0 b=1 CIN=1 SUM =0 CARRY=135 a=1 b=1 CIN=1 SUM =1 CARRY=1 $finish at simulation 40

Page 273: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$monitor

$monitoron //switches monitor on

$monitoroff //switches monitor off

Page 274: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Simulation control

simulation flow

#200 $stop; simulation suspends at time 200

#1000 $finish; simulation terminates at time 1000

Page 275: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Compiler directives

`include <file name>Example:file “global.txt”

//clock and simulator constantsParameter initial_clk=1;Parameter period=20;Parameter max_cycle=5;Parameter end_time=period*max_ cycle

Page 276: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Compiler directives:ExampleUsage:Module clock_gen;`include “global.txt”always begin $monitor( $time,”\t clk=%d”,clk); clk=initial_clk; while ($time<end_time) begin #(period/2) clk=~clk ; end $display($time,”simulation ends”) $finish;Endendmodule

Page 277: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

More compiler directives

`define add16 reg[15:0] add16 can be interpreted as reg[15:0]

`add16 input adress; interpreted as reg[15:0] input address

`timescale 10ns/1ns 10ns is the time unit for the block and these are rounded off to a 1ns precision

#10 clk =~clk 10 time units =100ns

Page 278: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

File outputs

32 channels available

32’h000_0001 channel descriptor for standard output(bit 0 set)

32’h000_0800 channel descriptor for 11th channel (bit 11 set)

Page 279: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$fopen, $fclose

$fopeninteger chan_num1,chan_num2;

declaration of channel descriptors

Chan_num1=$fopen(“file1.out”);Chan_num2=$fopen(“file2.out”);

Chan_num1=32h0000_0002(bit 1 set)Chan_num2=32h0000_0004(bit 2 is set)

Page 280: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Writing into file

integer chan_num1;initialbegin chan_num1=$fopen(“file1.out”); $fmonitor(chan_num1,$time,”add_in=%d,add_out=%b”, add_in,add_out);

monitor results go to file1.out

Page 281: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Writing into multiple file

integer chan_num1,chan_num2,mdesc;initialbegin chan_num1=$fopen(“file1.out”); chan_num2=$fopen(“file2.out”); mdesc= chan_num1 | chan_num2; $fmonitor(mdesc,$time,”add_in=%d,add_out=%b”, add_in,add_out);

monitor results are written to file1.out and file2.outFiles can be closed using $fclose

Page 282: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$readmemb and $readmemh

module mem8x8;reg [0:7] mem8x8 [0:7]; integer chan_num1, i;initialbegin $readmemb("init8x8.dat", mem8x8); chan_num1 = $fopen ("mem8x8.out"); for (i = 0; i < 8; i = i + 1) $fdisplay(chan_num1, "memory [%0d] = %b", i, mem8x8[i]); $fclose(chan_num1);endendmodule

Page 283: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

init8X8.dat@2 start address specified with @ 11111111 consecutive data applies to consecutive 10101010 address00000000@6Xxxxzzzz1x1x1x1x

Page 284: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

mem8x8.outmemory[0]=xxxxxxxx memory[1]=xxxxxxxx address 0,1 and 5 were not memory[2]=11111111 initialized (==x) memory[3]=10101010memory[4]=00000000memory[5]=xxxxxxxxmemory[6]=xxxxzzzzmemory[7]=1x1x1x1x

Page 285: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Tasks and Functions

Page 286: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Tasks and Functions

• Subprograms -Encapsulate portions of repeated code -Sequential statements -Execute in sequence like ‘software’

• Task - Zero or more input/outputs - Is a procedural statements

• Function - Multiple inputs, single return value - Can only be used as part of assignment

Page 287: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task Declaration and call

task zero_count; (Task name) 1.Task call is a procedural statement input [7:0]in_bus; //input arguments output [3:0] count; //output arguments integer i; //Local variable begin count=0; #5; for (i=0;i<8;i=i+1) if(!in_bus[i]) count=count+1; //assign outputs end endtask

Page 288: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task Declaration and call

module zerotask(); reg[7:0] a_bus; reg clk; reg [3:0] a_count; reg a_zero; //task declaration initial begin clk=0; a_bus=8'b00011111; end always # 20 clk =~clk ;

Page 289: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task Declaration and callalways @(posedge clk) begin zero_count (a_bus, a_count); if ( a_count == 4'b0010) a_zero=1'b1; else a_zero=1'b0;end endmodule

Page 290: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple Task calls

• Tasks can be called from more than one location

• Tasks are not duplicated like sub-routines

- only one copy of tasks exists• Avoid simultaneous concurrent calls

-Can cause conflict with task variables abd input/output arguments ,Example……

Page 291: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple Task calls

task neg_edge;

input [31:0] no_of_edges;

begin

repeat(no_of_edges)

@(negedge clk);

end

endtask

Page 292: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple Task callsmodule multiple_task_calls;reg clk;reg p;

initial begin clk=1; p=0; end always #50 clk=~clk; initial begin neg_edge(4); p=1; end

Page 293: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Multiple Task calls

always @(posedge clk)

begin

neg_edge(10);

p=0;

end

endmodule

Page 294: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task Calls from Different Modules

module mytasks;task neg_edge; input [31:0] no_of_edges; begin repeat(no_of_edges) @(negedge clk); endendtaskTask cpu_driver;….…….…endmodule

Page 295: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task Calls from Different Modules

//test benchmodule test_busif;reg clk;//clock generation…….//instantiation of task modulemytask m1 ( ) ;//creating stimulus..Initialbeginm1.neg_clocks(6);m1.cpu_driver(8’h00);……endendmodule

Page 296: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Disabling tasks and named blocks

• Tasks or named blocks can be disabled

- Here in Ex.if CPU interrupt is detected the

cpu_driver task is forced to exit

-The CPU interrupt can then be sreviced

- Does not prevent subsequent task calls

• Named blocks are disabled in the same way

• Example follows…..

Page 297: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comDisabling tasks and named

blocksmodule test_busif;…always #20 clk=~clk;…..initialbegin: stimulus neg_clock(5); cpu_driver(8’h00); cpu_driver(8’hff);……always @(posedge interrupt) begin disable cpu_driver; service_interupt;endendmodule

Page 298: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task without timing controls

• A Task normally contains timing……• But without timing controls it executes in zero

time• A task without timing control can be always

be expressed as a function

Example follows…..

Page 299: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Task without timing controls

task zero_count

input [7:0]in_bus;

output [3:0] count;

integer i;

begin

count=0;

for (i=0;i<8;i=i+1)

if(!in_bus[i])

count=count+1;

end

endtask

function integer zero_count;input [7:0]in_bus; integer i;begin zero_count=0; for (i=0;i<8;i=i+1) if(!in_bus[i]) zero_count=zero_count+1;

end endfunction

Page 300: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Function Declaration

function integer zero_count;

input [7:0]in_bus;

integer i;

begin

zero_count=0;

for (i=0;i<8;i=i+1)

if(!in_bus[i])

zero_count=zero_count+1;

end

endfunction

Page 301: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

function Callmodule zfunct (a_bus,b_bus,clk,azero,b_count); input[7:0] a_bus,b_bus; input clk; output azero, b_count; reg azero;Wire[3:0] b_count;//function declarationassign b_count=zero_count(b_bus);always @(posedge clk) if(zero_count(a_bus)==32’0) azero=1’b1; else azero=1’b0endmodule

Page 302: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comFunctions

•Function can enable other functions but not another task

•Functions always execute in zero simulation time

•Functions cannot include delays,timing or timing control statements

•Functions must have at least one input argument

•Functions return a single value.they cannot have output or inout arguments

Page 303: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Examples

1.Write a function to add two 4 bit numbers

2.Write task for the waveform specification given below:

3.Write task to count number of clock cycles

4.Write task to load time in alarm clock design

Page 304: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog PLI

Page 305: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary

Page 306: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Introduction

• Verilog Programming Language Interface is

one of the most powerful features of Verilog

• PLI provides both H/S designers to interface their programs to commercial Verilog simulators

Page 307: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Generations of PLI

IEEE 1364 Verilog

– TF / ACC routines. PLI 1.0 1990

– VPI routines PLI 2.0 1993

Introduction

Page 308: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Capabilities of Verilog PLI

• Access to programming language libraries

• Simulation analysis……

Introduction

Page 309: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary

Page 310: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

PLI InterfaceUser Design Representation

And Stimulus

Verilog Compilation

Internal design Representation

(Data Structures)

Simulation

Simulation Output

User-Defined System Task #2

User DefinedSystem Task #1

User-DefinedSystem Task #3

User-DefinedC routine # 1

User-DefinedC routine # 2

User-DefinedC routine #3

PLI Library Routines to do

MiscellaneousOperations

PLI LibraryRoutines

PLI

Lib

rary

Routi

nes

Invokes User-Defined SystemTask

Passdata

Invokes User- defined C routine

AccessInternalstructures

Page 311: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Objects in Verilog

• Module instances, ports, pin-to-pin paths, intermodule paths

• Top-level modules

• Primitive instances, terminals

• Nets, registers, parameters, specparams

• Integer,time and real variables

• Timing checks & Named events

Page 312: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Conceptual Internal Representation a Module

Page 313: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Example: 2-to-1 Multiplexer

Example

Page 314: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Page 315: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Internal Data Representation of 2-to-1 Multiplexer

Page 316: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary

Page 317: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Role of Access and Utility Routine

TF/ACC Routines

Page 318: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Outline

Introduction

PLI Interface

TF/ACC Routines

Creating PLI Applications

Summary

Page 319: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

General steps to create PLI applications

1. Define system task / function

2. Write C language routine

3. Register system task/function name and associate C language routine with Verilog simulator

4. Compile C source file which contains PLI application & link object files into Verilog simulator.

Page 320: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comSome useful tf routines

•int tf_nump()-Returns number of arguments in system task

•int tf_typep(n)- Returns constants that reps.data type

•viod tf_error()-Prints error massage & causes simulation to abort

Page 321: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

•handle acc_handle_tfarg(n)-Returns pointer to system t/f handle

•int acc_fetch_type(object)- Returns constant that identifies type of argument

•char *acc_fetch_fullname(object)-Returns fulltype property of object

•char *acc_fetch_value(object,format_str,value)-Return value of verilog object

Some useful ACC Routines

Page 322: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

• $show_value

Uses PLI to access specific activity within a Verilog simulator, by listing the name and current value of net

• This system task $show_value illustrates

using PLI to allow a C routine to read current logic values within a Verilog simulation

PLI application example

Page 323: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Step I module test;

reg a, b, ci;wire sum, co;. . .initial begin . . .

$show_value (sum);$show_value (sum); end

endmodule

Page 324: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Two user-defined C routines will be associated with $show_value:

• A C routine to verify that $show_value has the correct type of arguments

• A C routine to print the name and logic value of the signal

Step II

Page 325: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

# include “veriuser.h” /* IEEE 1364 PLI TF routine library */

# include “acc_user.h” /* IEEE 1364 PLI ACC routine library */

Int ShowVal_checktf( )

{

int arg_type;

handle arg_handle;

if (tf_nump( ) != 1)

tf_error (“$show_value must have 1 argument.”);

else if (tf_typep(1) == TF_NULLPARAM)

tf_error (“$show_value arg cannot be null.”);

…contd

Writing a checktf routine for $show_value

Page 326: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

else {arg_handle = acc_handle_tfarg(1);arg_type = acc_fetch_type(arg_handle);if (! (arg_type == accNet || arg_type == accReg) )

tf_error (“$show_value arg must be a net or reg.”); } return (0);

}

Writing a checktf routine for $show_value

Page 327: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

# include “veriuser.h”

# include “acc_user.h”

int ShowValCalltf( )

{

handle arg_handle;

arg_handle = acc_handle_tfarg(1);

io_printf (“Signal %s has the value %s \n”, acc_fetch_fullname(arg_handle), acc_fetch_value(arg_handle, “%b”, null) );

return (0);

}

Writing a calltf routine for $show_value

Page 328: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Step III : Registering the system task/function

Interface mechanism

• The type of application which is a system task or system function

• The system task or system function name• The name of the calltf routine and other C

routines associated with the system task/function.• Other information about the system task/function

required by simulator

Page 329: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

s_tfcell veriusertfs [ ] =

{

{ type, user_data, checktf_app, sizetf_app, calltf_app, mistf_app, “tf_name”, 1, 0, 0 },

{ type, user_data, checktf_app, sizetf_app, calltf_app, misctf_app, “tf_name”, 1, 0, 0 },

. . .

{ 0 }, /* first field in final array cell is 0 */

};

The default standard veriusertfs array

Page 330: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

typedef struct t_tfcell {

short type; /* one of the constants: usertask, user function, user real

function */

short data; /* data passed to use routine */

int (*checktf) ( ); /* pointer to the checktf routine */

int (*sizetf) ( ); /* pointer to the sizetf routine */

int (*calltf) ( ); /* pointer to the calltf routine */

int (*misctf) ( ); /* pointer to the misctf routine */

char *tfname; /* name of the system task/function */

int forwref; /* usually set to 1 */

char *tfveritool; /* usually ignored */

char *tferrmessage; /* usually ignored */

} s_tfcell, *p_tfcell;

S-tfcell structure definition is:

Page 331: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

/* prototypes for the PLI application routines */

extern int Showval_checktf( ), pow_sizetf( );extern int Showval_checktf( ), pow_sizetf( );

extern int pow_checktf( ), pow_sizetf( ), pow_calltf( ), pow_misctf( );extern int pow_checktf( ), pow_sizetf( ), pow_calltf( ), pow_misctf( );

/* the veriusertfs array */

s_tfcell veriusertfs [ ] =

{

{ usertask, /* type of PLI routine */

0, /* user_data value */

ShowVal_checktf /* checktf routine */

Example veriusertfs array for registering TF/ACC applications

Page 332: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

0, /* sizetf routine */

ShowVal_calltf, /* calltf routine */

0, /* misctf routine */

“$show_value”, /* system task/function name */

1 /* forward reference = true */

},

{ /* type of PLI routine */

/* user_data value */

/* checktf routine */

/* sizetf routine */

/* calltf routine */

Interfacing PLI ApplicationExample veriusertfs array for registering TF/ACC applications

Page 333: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

/* misctf routine */

/*system task/function name

1 /* forward reference = true

},

{ 0 } /*** final entry must be 0

};

Example veriusertfs array for registering TF/ACC applications

Page 334: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Interfacing PLI Application

Compiling and linking PLI applications

cl –c –I <simulator path>\include <name of c file>

link -dll –export:veriusertfs <name of .obj file> <simulator path>\Win32\mtipli.lib

Page 335: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

`timescale 1ns / 1ns

module test;

reg a, b, ci, clk;

wire sum, co;

addbit i1 (a, b, ci, sum, co);

initial

begin

a = 0;

b = 0;

ci = 0;

#10 a = 1;

…contd

A test case for $show_value

Page 336: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

$show_value(sum);$show_value(co);$show_value(i1.n3);

#10 $stop;$finish;

endEndmodule

Page 337: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Compiling source file “show_value_test.v”

Highest level modules:

Test

Signal test.sum has the value 1

Signal test.co has the value 0

Signal test.11.n3 has the value 0

L32 “show_value_test.v”: $stop at simulation time 20

Output from running the $show_value test case

Page 338: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Thank You

Page 339: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Verilog Sample Design

Page 340: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Aims and Topics

• Aims– To review basic Verilog concepts and code structures– To explore a real life example

• Topics– FIFO (First-in First-out) design specification– Implementation– Module declarations– Functional code– Testbench design and implementation

Page 341: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comFIFO Specification

• FIFO design is a register block at the end of a data path• FIFO is synchronous

– Data is read and written on rising edge of clock– Asynchronously resetable

• When write enable is high, data is written into FIFO and stored • When read enable is high, data is read from FIFO

– In the same order that it was written

• Both enable lines are not allowed to be active in the same clock cycle– If this occurs, both read and write operations are suppressed

• When the FIFO is full, set f_full high and ignore write operations• When the FIFO is empty, set f_empty high and ignore read

operations• FIFO should be parameterisable for data width and FIFO length

Page 342: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

FIFO Implementation Use register array for FIFO contents Array accessed by write and read pointers Status of FIFO derived from pointer addresses

FIFO full FIFO empty

FIFOwidth

0 1 2 3 . . . . . . . n

FIFO length

rd_ptr wr_ptr

Read pointer follows write and accesses data in same order as written

FIFO write: assign data to current write pointer & increment

rd_ptr wr_ptr wr_ptr

one

two

thre

e f

our

wri

te h

ere

<fr

ee>

Page 343: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

FIFO Model Structure

module fifo (data_in, data_out, clock, reset, wr_en, rd_en, f_full, f_empty); // parameter declarations // input declarations // output declarations // register declarations // internal variable declarations// functional code // clocked procedures // combinational procedures endmodule

Page 344: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Design Constants• Parameters used to define data and address width

•Must be declared before input/output ports

• Values can be changed in module instantiation

0 1 2 3 . . . . . . LENGTH-1

rd_ptr[ADDRESS_WIDTH-1 : 0]

0 1 2 . .

WIDTH-1

module fifo (data_in, ……

// parameter declarations parameter WIDTH = 8; parameter ADDRESS_WIDTH = 5; parameter LENGTH = (1 << ADDRESS_WIDTH ); …

// 16 location fifo of 16 bit data fifo #(16,4) fifo16x16. (…

Page 345: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comFIFO I/O

module fifo (data_in, data_out, clock, reset, wr_en, rd_en, f_full, f_empty

// parameter declarations parameter WIDTH = 8; parameter ADDRESS_WIDTH 5; parameter LENGTH = (1 << ADDRESS_WIDTH ); // input declarations data_in data_out input [WIDTH-1:0] data_in; input clock, reset; WIDTH fifo WIDTH input wr_n, rd_en; wr_en f_full// output declarations output f_full; rd_en f_empty output f_empty; output [WIDTH-1:0] data_out; reset // register declarations // internal variable declarations clock // functional code endmodule

Page 346: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comRegister and Internal Variable

Declarations module fifo……. // parameter declarations parameter WIDTH = 8; parameter ADDRESS_WIDTH = 5; parameter LENGTH = (1 << ADDRESS_WIDTH); // input and output declarations

// FIFO array declaration reg [WIDTH – 1:0] fiforeg [LENGTH – 1:0]; // pointer declarations reg [ADDRESS_WIDTH – 1:0] wr_ptr; reg [ADDRESS_WIDTH – 1:0] rd_ptr;

// integer needed with for loops integer I; // functional code. endmodule

wr_ptr rd_ptr fiforeg

0 1 2 3 . . . . . . . LENGTH-1.

.

.

.

.

.

.

.

.

.

.

[WIDTH –1 :0]

Page 347: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.comFIFO Functional Code

• Clocked procedure describes functionally for:-

•Reset•Pointer updates•Writing to FIFO array

Clocked procedureUses non-blocking assignment

read operation: increment read pointer

write operation: write data at current pointer and update pointer

always @ (posedge clock or posedge reset) if (reset) begin rd_ptr < = {ADDRESS_WIDTH {1’b0}}; wr_ptr < = {ADDRESS_WIDTH {1’b0}}; for (I = 0; I < LENGTH; I = I + 1) fiforeg[1] < = {WIDTH {1;B0}}; end else begin if (rd_en && (!wr_en) && (!f_empty)) rd_ptr < = rd_ptr + 1; if ((rd_en) && wr_en && (if_full)) begin fiforeg[wr_ptr] < = data_in; wr_ptr < = wr_ptr + 1 ; end end

Page 348: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

FIFO Outputs

Module fifo ……

/ / declarations

/ / clocked procedure

/ / full and empty pointers

assign and empty pointers

assign f_full = ( ( rd_ptr – wr_ptr) = = 5’b000001);

assign data_out= fiforeg[rd_ptr];

End module

If write pointer cather read pointer FIFO full

If read pointer catchers write pointer, FIFO empty• Outputs are

combinational

Page 349: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Testbench

• Instantiates and connects Design Under Test (DUT)

•Applys stimuli to input data and control ports

•Monitors output ports to check for correct behavior for given stimuli

•Monitors output ports to check for correct behaviour for given stimuli

- may be done via waveform display in simulator

Page 350: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

DUT Instantiation

module fifo_tb;

/ / Data type declaration

/ / FIFO instantiation

fifo # (WIDTH, ADDRESS_WIDTH) dut (

.data_in (data_in)

.data_out (data_out),

.clock (clock)

.reset (reset)

.wr_en (rd_en)

.f_full (f_full),

.f_empty (f_empty)

/ / Apply stimuls

endmodule

• fifo is the reference name of the module under test

•dut is the name of this instance

•FIFO parameters are reassigned in the instantiation

•Named port connection used to link FIFO ports to local variables

-Syntax

.port (variable)

•Local variables and parameters must be defined

Question

Why are there no ports for the test fixture ?

Page 351: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Testbench Declarationsmodule fifo_tb

Parameter WIDTH =8;

Parameter ADDRESS_WIDTH = 5:

Parameter PERIOD = 10;

/ / input declarations

reg [WIDTH-1:0] data;

reg clock, wr_en, rd_en, reset;

/ / output declarations

wire f_full;

Wire f_empty;

wire

endmodule

Page 352: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Describing Stimulus

initial

begain

data = { WIDTH {1’b0}};

{wr_en, rd_en} = 2’b00;

$monitor (data_out,, f_full,,,f_empty

reset=1’b0;

#2;

reset = 1’b1;

#5;

reset =1’b0;

@(negedge clock) ;

rd_en = 1’b0;

wr_en = 1’b1;

for (i = 0, i <35; i = i + 1)

begin

@(negedge clock);

data = 255 – i;

end

Initial clock = 1’b0;

Always # PERIOD clock = - clock,

Any tune these signals change, display their stable values in the standard output

read from an empty fifo to check the empty flag

Fill FIFO and then write to check full flag

read two words to check advancing read pointer

halt simulation

Page 353: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

rd_en = 1’b1;

wr_en = 1’b0;

repeat (2)

@(negedge clock);

$stop;

end

Describing Stimulus

Page 354: Sandeepani verilog

Sandeepani www.sandeepani-vlsi.com

Review

1.How can you change the value of parameter ?

2. What are basic fundamental blocks of

test fixture ?

3.Using a parameter, write code that creates a

clock stimulus.