Verilog

226
Verilog HDL

Transcript of Verilog

Page 1: Verilog

Verilog HDL

Page 2: Verilog

Outline

§ HDL Languages and Design Flow

§ Introduction to Verilog HDL

§ Basic Language Concepts

§ Connectivity in Verilog

§ Modeling using Verilog

§ Race conditions

§ UDPs

§ Coding FSMs in Verilog

Page 3: Verilog

Outline

§ Verilog Logic Synthesis

§ Verilog Coding Guidelines

§ Electrical Properties

§ Macros, Conditional Compilation & Naming Conventions

§ Verilog for Logic Simulation

§ Introduction to PLI

Page 4: Verilog

HDL Languages and Design Flow

Page 5: Verilog

HDLs – WHAT-WHY-HOW

§ WHAT is a HDL?

§ HDLs – A class of programming/computer languages used forformal description of electronic circuits.

§ A Hardware Description Language is one that can describecircuit’s operation, conceptual design & organization and cantest it by means of simulation.

§ Usually deal with the design of digital logic circuits andsystems.

Page 6: Verilog

HDLs – WHAT-WHY-HOW

§ WHY were HDLs required?

§ It is impractical to verify large circuits on breadboards orlarge chips after manufacturing.

§ Highly important to find potential functional bugs in theearly stages of design.

§ These needs led to a the use of CAD techniques for digitaldesign.

§ The designers felt need for a flexible language that may helpthe design process by giving a complete framework for design.

Page 7: Verilog

HDLs – WHAT-WHY-HOW

§ WHY were HDLs required? (contd..)

§ Software Programming languages – Sequential in nature. (C,Pascal, FORTRAN, etc.)

§ Digital logic circuits involve Concurrency of operations.

§ Traditional programming languages lack the capability forexplicitly expressing time.

§ Using s/w programming languages to represent hardware is –Inconvenient, Time consuming & Costlier.

Page 8: Verilog

§ HOW are HDLs advantageous?

§ Allows designer to talk about what the hardware should dowithout actually designing the hardware itself.

§ Designers can develop an executable functional specificationthat documents the exact behavior of all the components andtheir interfaces.

§ Designers can make decisions about cost, performance, power,and area earlier in the design process.

§ Designers can create tools which automatically manipulatethe design for verification, synthesis, and optimization.

HDLs – WHAT-WHY-HOW

Page 9: Verilog

§ Design Specification & Requirements

§ Behavioral/Architectural Design

§ Register Transfer Level (RTL) Design

§ Logic Design

§ Circuit Design

§ Physical Design

§ Manufacturing

Design Hierarchy

Page 10: Verilog

Fabrication & Testing

System Specification

Functional (Architectural Design)

Functional Verification

Logic Design

Logic Verification

Circuit Design

Circuit Verification

Physical Design

Layout Verification

Behavioral Representation

Logic (Gate-level)Representation

Circuit Representation

Layout Representation

Page 11: Verilog

Hardware Design FlowSystem

CPU SubSystem

Reg.Arith Mem.

subtradder

Impl

emen

tatio

n

Desig

n

Gate

level

Treansistor

level

RT

L

Behaviorallevel

...

Page 12: Verilog

§ HDLs and CAD tools are used to describe hardware for:

§ Design & Modeling

§ Simulation

§ Synthesis

§ Testing

§ Documentation

Hardware Design Flow

Page 13: Verilog

Verilog HDL Introduction

Page 14: Verilog

Verilog HDL - History§ Invented by Phil Moorby & Prabhu Goel at Gateway Design

Automation Systems in 1983/84.

§ Later , Cadence took full proprietary in 1990.

§ In 1995, Cadence published Verilog for public domain under OVI(Open Verilog International).

§ Verilog-95 – IEEE Standard 1364-1995.

§ Verilog 2001 – IEEE Standard 1364-2001.

§ Verilog 2005 – IEEE Standard 1364-2005.

§ SystemVerilog – Extended from Verilog and C++.

Page 15: Verilog

How Verilog Is Used

§ It is a general purpose HDL with support for .

§ Allows different levels of abstraction to be mixed in the samedesign.

§ “Synthesis subset”§ Can be translated using Synopsys’ Design Compiler or others

into a netlist.

§ Design written in Verilog.

§ Simulated to check functionality.

§ Synthesized (netlist generated).

§ Static timing analysis.

Page 16: Verilog

Levels of Abstraction§ Verilog supports a design at 4

different levels of abstraction.

§ Behavioral Level§ Dataflow Level§ Gate Level§ Switch level

§ Register Transfer Level (RTL)§ A combination of both

Behavioral & Dataflowconstructs.

§ Acceptable to logic synthesistool.

Behavioral

Dataflow

Gate Level

Switch level

Highest AbstractionLevel

Lowest AbstractionLevel

Page 17: Verilog

Levels of Abstraction (Cont..)

§ Behavioral Level :- Used to model the behavior of a designwithout describing its actual hardware structure.

§ Data Flow Level :- Describes the flow of data between registersand how a design processes that data.

§ Gate Level :- Describes the logic gates and the connectionsbetween logic gates in a design.

§ Switch Level :- Describes the transistors and storage nodes in adevice and the connections between :-describes them

Page 18: Verilog

Design Methodologies

§ There are 2 types of design methodologies:§ Top-down design methodology, and§ Bottom-up design methodology.

§ In a top-down design methodology, we define the top-level blockand identify the sub-blocks necessary to build the top-level block.

§ In a bottom-up design methodology, we first identify the buildingblocks that are available to us. We build bigger cells, using thesebuilding blocks.

Page 19: Verilog

Design Methodologies (Cont..)

Top-Level Block

Sub-block3

Sub-block2

Sub-block1

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Top-Down Design Methodology

Page 20: Verilog

Design Methodologies (Cont..)

Bottom-Up Design Methodology

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Leaf Cell

Top-Level Block

Macro Cell 3

Macro Cell 2

Macro Cell1

Page 21: Verilog

Modules

§ A module is the basic building block in Verilog.

§ Elements are grouped into modules to provide the commonfunctionality that is used at many places in the design.

§ A module provides the necessary functionality to the higher-levelblock through its port interface (inputs and outputs).

§ In Verilog a module is declared by the keyword module.

§ A corresponding keyword endmodule must appear at the end ofthe module definition.

Page 22: Verilog

Modules (Contd..)

§ Modules CANNOT be nested.

§ Rather, one module can instantiate another module.

§ Module instantiation is like creating actual objects (Instances)from the common template (module definition).

§ Each instance of module has all the properties of that module.

§ Module instantiations are used for:§ connecting different parts of the designs, and§ connecting test bench to the design.

Page 23: Verilog

Design Hierarchy

§ One top level module§ In which zero or more lower level modules can be

instantiated.§ Each low level module can further instantiate still lower level

modules.

§ Verilog modules are like modules in schematics or classes in C++.

§ Use them to make your design more readable and manageable.

§ Debugging individual module is a lot easier than debugging thewhole system together.

Page 24: Verilog

Structure of module

module <mod name> (<port list>);<declarations>; // input, output, inout

// wire, register, etc.<statements>; // initial, begin, end, always

// dataflow statementsendmodule

Page 25: Verilog

Structure of module (Contd..)

§ The <module name> is an identifier that uniquely names themodule.

§ The <port list> is a list of input, inout and output ports which areused to connect to other modules.

§ The <declares> section specifies data objects as registers,memories and wires as wells as procedural constructs such asfunctions and tasks.

§ The <statements> may be initial constructs, always constructs,continuous assignments or instances of modules.

Page 26: Verilog
Page 27: Verilog

Basic Languages Concepts

Page 28: Verilog

Lexical Conventions§ Keywords§ In lower case§ Case sensitive§ Delimit tokens, space

§ String with double quotes

§ Identifier§ A letter or _ can be followed by letters, digits, $ and _§ Max 1024 characters

§ Numbers§ [<sign>] [<size>] <base> <num>§ e.g.- 549, ‘h8ff, ‘o765, 4’b11,3’b10x, -4’b11

Page 29: Verilog

Verilog CommentsVerilog supports 2 type of comment syntaxes

§ Single line comment start with //, and end with newline.

§ Block comment, start with /*, and end with */. Block commentcannot be nested.

/* Copyright Kacper Technologies Pvt Ltd, 2009No unauthorized copying is allowed.

*/input status; // 0:ready, 1:not ready output data; // sync with clock mClock

Example

Page 30: Verilog

§ Two representations: sized & unsized

§ Format:<number of bits><base><number>

0-9, a-f, A-F, X, Z, ?, _<number>

�b, ‘B, ‘d, ‘D, ‘o, ‘O, ‘h, ‘H. Default is ‘decimal’<base>

Bit length in decimal. This is an optional value & if not specified, default is host machine word size. (usually 32 bits)

<number of bits>

Verilog Number Specifications

Page 31: Verilog

§ Negative numbers: put minus sign before size.§ Format: -<size><base><number>§ <size> field is always +ve.§ Represented by 2’s complement internally.

§ Often _ (Underscore) is used in between digits of the number for readability.

Verilog Numbers Specifications (Contd..)

reg [5:0] Num;Reg [31:0] data;..Num = -6; // Negative numberNum = -8’d4; // 8 bit –ve numberNum = ‘d-12; // Illegal !!data = 32’h_1234_5678; // _ for readability

Page 32: Verilog

§ Verilog numbers may have x or z as part of numbers.

§ x ? unknown value, z ? high impedance value

§ A question mark ‘?’ can also be used as an alternative to ‘z’.

Verilog Numbers Specifications (Contd..)

reg [5:0] Num;Reg [31:0] data;..Num = 6’b_100x; // Num = 6’b00100xdata = 32’bx; // 32 bit no with all x bitsNum = ‘bz01; // Num = 6’bzzzz01Num = ‘b11??1; // Num = 6’b011zz1data = 32‘h_x5f3_2693; // data = 32’hX5f32693

Page 33: Verilog

Verilog Numbers: Example

module Verilog_number;reg [7:0] Num;wire status;…Num = 16; // 8’b0001_0000Num = -8’d4; // two’s complement of 4Num = ‘bx; // 8’bxxxx_xxxxNum = ‘b0x; // 8’b0000_000xNum = ‘b10x; // 8’b0000_010xif (status == 1) // status == 32’h0001

Num = 8’b1010_0101;if (status == 1’b1) // status == 1’b1…endmodule

Page 34: Verilog

Data Types§ reg: Register

§ wire: Wire/net

§ Possible Values: 0, 1, x, z

§ Default: 1-bit (Scalar)reg A, B, C;

§ Vector:Reg[0:7] A;Reg[7:0] B;

§ Integer & Real Data Types§ Declaration

integer i, k;real r;

§ Use as registers (inside procedures)i = 1; r = 2.9;k = r; // k is rounded to 3

§ Integers are not initialized in Verilog!!

§ Reals are initialized to 0.0

Page 35: Verilog

Nets

§ Nets represent the connections between hardware elements.

§ They are always driven by some source.

§ Default value for any net type variable is ‘z’.

§ Usually, declared by the keyword wire.

§ Different types: wire, wand, wor, tri, triand, trior, trireg, etc.

§ wire is the most common of all.

Page 36: Verilog
Page 37: Verilog

Registers

§ These correspond to variables in the C language.

§ Register data types always retain their value until anothervalue is placed on them.

§ DO NOT confuse with hardware registers built with flip-flops.

§ A reg type variable is the one that can hold a value.

§ Unlike nets, registers do not need any drivers.

Page 38: Verilog

Registers (Contd..)

§ In synthesis, the compiler will generate latches or flip-flopsfor them. However, if it can be sure their output does not needto be stored it will synthesize them into wires.

§ It can be sure they do not have to store if their outputs isbased only on their present inputs.

Page 39: Verilog

Rules for reg and wire

§ The common rule in Verilog:

“A variable on the Left Hand Side (LHS) of a procedural blockassignment is always declared as a register data type.”All othervariables are of net type.”

§ Verilog register data types: reg / time / integer / real / realtime/ event (reg is the most common of all.)

§ So, reg is assigned within always or initial blocks.§ A variable is declared of type wire if it appears on the left side

of an continuous assignment statement.§ Structural code continuous assignment statements start with

the keyword assign.

Page 40: Verilog

Integers

§ A general purpose register data type with default valuehaving all x bits.

§ Declared with keyword integer.

§ Usually preferred for arithmetic manipulations over reg.

§ Default width: host machine word size (minimum 32 bits).

§ Differs from reg type as it stores signed quantities as opposedto reg storing unsigned quantities.

Page 41: Verilog

Real Numbers

§ Real number constants declared with a keyword real.

§ Real constants have default value of 0.

§ Real numbers CANNOT have a range declaration.

§ Two notations: Decimal & Scientific notation.

§ When a real value is assigned to an integer, the real numberis rounded off to the nearest integer.

Page 42: Verilog

Time & Realtime Data types

§ time – A special register data type used mainly to storesimulation time.

§ time is an unsigned 64-bit by default. Usually, it is used tostore the simulation time.

§ realtime is similar to time except that it has initial value of 0.

§ Depending upon the timescale specified, realtime provides thesimulation time with the fractional part with given precision.

Page 43: Verilog

Logical Operators

Relational> >= < <=

Logical Inequality!= or !==

Logical Inequality== or ===

Reduction XNOR~^ or ^~

Reduction XOR^

Conditional?:

Reduction NOR~|

Reduction OR|

Reduction NAND~&

OperationOperator

Reduction AND&

Bit-wise Ex- NOR^~ or ~^

Bit-wise Exclusive OR^

Bit-wise OR|

Bit-wise AND&

Bit-wise Negation~

Logical OR||

Logical AND&&

Logical Negation!

OperationOperator

Page 44: Verilog

Logical Operation Example

1 2 3 4 5 6 7 8 A B C D E F G H&&

operand1

True (“1”), False (“0”) or Unknown (“X”)

operand2

X2’b1X && 2’b11

02’b11 && 2’b10

01’b1 && 1’b0

12’b1X || 2’b11

12’b11 || 2’b10

11’b1 || 1’b0

Examples

Page 45: Verilog

Bitwise Operators

§ & → bitwise AND§ | → bitwise OR§ ~ → bitwise NOT

§ ^ → bitwise XOR§ ~^ or ^~ → bitwise

XNOR§ Operation on bit by bit

basis

A B C D E F G H&

1 2 3 4 5 6 7 8

& & & & & & &

1 2 3 4 5 6 7 8 A B C D E F G H&

Page 46: Verilog

Reduction operatorsReduction operators§ Key symbols: &, ~&, |, ~|, ^, ~^, ^~.

§ The reduction operators are and, nand, or, nor, xor, xnor and analternative xnor. They take one operand and perform a bit-by-next-bit operation, starting with the two leftmost bits, giving a 1-bit result.

initial begina = 4'b1111;b = 4'b0101;c = 4'b0011;$displayb(& a); // bitwise and, (same as 1&1&1&1)

// evaluates to 1$displayb(| b); // bitwise or (evaluates to 1)

end

Page 47: Verilog

1 2 3 4 5 6 7 8&

&

1 2 3 4 5 6 7 8

& & && &

&

Reduction operationReduction operation

Page 48: Verilog

Shift operators§ Key symbols: >>, <<.

§ The shift operators are shift left and shift right. The shift operator takes a vector and a number indicating the shift.

§ The empty bits caused by shifting are filled with zeros.

module shiftTest;reg [3:0] a;initial begin

a = 4'b1010;$displayb(a << 1); // shift left by 1, displays 0100$displayb(a >> 2); //shift right by 2, displays 0010

endendmodule // shiftTest

Page 49: Verilog

Conditional Operator

§ cond_expr ? true_expr : false_expr§ A ternary operator§ Acts like a 2-to-1 mux.

A

BY

sel

Y = (sel)? A : B;0

1

Y = A if sel is ‘1’ B if sel is 0

Page 50: Verilog

Concatenation Operator

§ {op1, op2, ..} → concatenates op1, op2, .. to single number.§ Operands must be sized !!

…reg a;reg [2:0] b,c;a = 1’b1,b = 3’b 010, c = 3’b 101;catx = {a, b, c}; // catx = 1_010_101caty = {b, 2’b11, a}; // caty = 010_11_1catz = {b, 1}; // WRONG !!…

Page 51: Verilog

Replication Operator

§ <no> { <variable/sized_number> }§ <no> is an integer.

…reg a;reg [2:0] b,c;a = 1’b1,b = 3’b 010, c = 3’b 101;catr = {4{a}, b, 2{c}}; // catr = 1111_010_101101…

Page 52: Verilog

Relational & Equality Operators

§ > → greater than§ < → less than§ >= → greater or equal than§ <= → less or equal than§ Result is one bit value: 0, 1 or x§ == → logical equality§ != → logical inequality Return 0, 1 or x§ === → case equality§ !== → case inequality Return 0 or 1

e.g. - 4’b1z0x == 4’b1z0x → x4’b1z0x === 4’b1z0x → 1

Page 53: Verilog

Operator precedenceOperators Operator Symbols Precedence

Unary

Multiply, Divide, Modulus

+ - ! ~

* / %

Highest

Lowest

Add, Subtract

Shift

+ -

>> <<

Relational

Equality

< <= >= >

== != === !==

Reduction

Logical

& ~& ̂ ^~| ~|

&& ||

Conditional ? :

Page 54: Verilog

Vectors

§ Vectors have multiple bits and are often used to represent buses.

§ The left most number is an MSB (Most Significant Bit).

§ There are 2 representations for vectors:§ A little-endian notation: [high# : low#]§ A big-endian notation: [low# : high#]

wire [3:0] busA; // little-endian notationreg [0:15] busC; // big-endian notationreg [1:4] busB;

Page 55: Verilog

Vectors (Contd..)

§ Vector Part Select

data[15:8] = 8’h_12; // Accessing only bits 16 to 9 of datainter_carry = carry[1:3];

§ Slice management

reg [63:0] out;reg [3:0] dest_addr;initial begin

dest_addr = out[63:60];end

dest_addr[0] = out[60];dest_addr[1] = out[61];dest_addr[2] = out[62];dest_addr[3] = out[63];

=

Page 56: Verilog

Vectors (Contd..)

§ Vector assignment (by position!!)

…reg [2:0] bus_A;reg [0:2] bus_B;initial begin

bus_A = bus_B;end…

=bus_A[2] = bus_B[0];bus_A[1] = bus_B[1];bus_A[0] = bus_B[2];

Page 57: Verilog

Vectors (Contd..)

§ Variable Vector Part Select§ [<starting_bit>+ : <width>]§ [<starting_bit>- : <width>]

reg [31:0] data1; reg [0:31] data2;reg [7:0] byte1; reg [3:0] nibble1;reg [0:7] byte2; reg [0:3] nibble2;…nibble1 = data1[31-:4]; // selects 4 bits from 31 to down, i.e. [31:28]byte1 = data1[24-:8]; // selects data1[24:17]byte2 = data2[10+:8]; // selects data2[10:17]nibble2 = data2[28+:4]; // selects data2[28:31]

Page 58: Verilog

§ Implemented with regs.

§ Escaped chars:

\n for newline \\ for \ \” for “\t for tab %% for % \ooo characters as octal

…reg [8*13:1] string_val; // can hold up to 13 chars...string_val = “Hello Verilog”;string_val = “hello”; // MS Bytes are filled with 0string_val = “I am overflowed”; // “I ” is truncated…

Strings

Page 59: Verilog

§ Declaration: <type> <vector_size> <ary_name> <ary_size>;

§ <ary_size> is declared as a range.

§ Verilog supports multi-dimensional arrays.§ Elements are accessed by: <ary_name> [<index>].

reg array1 [99:0]; // array1 is an array with 100 elements// each element is of 1 bit.

integer ary1 [19:0]; // array of integers with 20 elementswire [3:0] y [10:1]; // array of busesreg [31:0] payload [34:0]; // array of vectorstime checkpoints [1:50]; // array of check-pointsreal results [39:0]; // array of real numbers

Arrays

Page 60: Verilog

//Multi-dimensional arrays

reg [7:0] sonet_frame [89:0][8:0];// a 2-dimentional array representing the SONET frame.

reg [7:0] matrix3d [9:0] [24:0] [3:0];// 3-dimentional array of integers

Arrays (Contd..)

Page 61: Verilog

§ Declaration:

reg <vector_width> <ary_name> <no_of_locations>;

…reg [7:0] string_val [99:0]; // a memory with 100 elements

// each of 1 bytereg [7:0] ray2d [4:0] [49:0]; // 2-dimentional array

reg [31:0] mem32 [`DEPTH-1:0]; // 32-bit memory…

Memories

Page 62: Verilog

Connectivity in Verilog

Page 63: Verilog
Page 64: Verilog

Port assignments

§ Modules contain functional descriptions and have input, output,and inout (bidirectional ports) for interfaces.

§ The following are true of module interfaces:§ An input or inout port is a wire type within its module.§ An output port must be a wire if it is generated by a

submodule.§ An output port must be a wire if it is generated declaratively.

§ An output port must be§ a reg if it is assigned to procedurally.§ A wire if it is assigned through continuous assignment.

§ Bidirectional ports cannot be assigned to procedurally.

Page 65: Verilog
Page 66: Verilog

Module Instantiations

§ As we saw earlier, module instantiation is used to makeconnections between different parts of the design.

§ There are two methods of making connections between signalsspecified in the modules and their input/output ports.

§ Port ordered instantiation lists signal connections in the sameorder as the port list in the module definition. Unconnected portsare designated by two commas with no signal listed.

§ Port named instantiation lists the port name and signalconnected to it, in any order.

Page 67: Verilog

§ Connections by Ordered List<module_name> <instance_name> [instance_array_range]( signal, signal, ... );

§ Connections by Named List<module_name> <instance_name> [instance_array_range]( .port_name(signal), .port_name(signal), ... );

Module Instantiations (Contd..)

Page 68: Verilog

§ A module can be seen as a template which allows any othermodules to incorporate its functionality without writing the samelogic repeatedly.

§ Modules allow instances & hierarchy.

§ When a module instance is created in higher level module, theinstance will have all the properties of the lower level module.

§ Instantiations are used for connecting different modulestogether.

Module Instantiations (Contd..)

Page 69: Verilog
Page 70: Verilog

§ As modules instantiate one another, there forms a hierarchy ofthem. And them and their internal variables, etc. can beaccessed from higher levels using hierarchical naming.

Hierarchical Naming

TB_TOP

dff

nand1 nand2

Page 71: Verilog

Hierarchical Naming (Contd..)

TB_TOP

dff1

nand1 nand2Q, QBD (Signals)

§ Signals of the dff may be accessed using hierarchical naming asshown below:

TB_TOP TB_TOP.nand1.o1TB_TOP.dff1.Q TB_TOP.dff1.QBTB_TOP.nand1

Page 72: Verilog

Modeling using Verilog

Page 73: Verilog

Gate Level Modeling

§ Verilog has built in primitives like gates, transmission gates, andswitches.

§ These are rarely used for in design work, but are used in postsynthesis world for modeling the ASIC/FPGA cells. These cells arethen used for gate level simulation or what is called as SDFsimulation.

§ Ex:- and, or, nand, nor, xor, xnornot, bufbufif1, notif1, bufif0, notif0

Page 74: Verilog

§ The gates have one scalar output and multiple scalarinputs.

§ The first terminal in the list of gate terminals is an outputand the other terminals are inputs.

§ Gate instance name is optional.

Gate Level Modeling (Contd..)

nand n1(z, a, b); // 2 input NAND gatexor x1(z, a, b, c, d); // 4 input XOR gateand x2(z, a, b, c); // 3 input AND gateor(z, a, b); // Instance name is optionalbuf b1(out, in); // Buffernot n1(out, in); // Inverterbufif0 U1( data_bus, data_drive, data_enable_low );

Page 75: Verilog
Page 76: Verilog
Page 77: Verilog
Page 78: Verilog
Page 79: Verilog
Page 80: Verilog
Page 81: Verilog

Gate Delays

§ Rise Delay: associated with a gate output transition to 1 fromanother value.

§ Fall Delay: associated with a gate output transition to 0 fromanother value.

§ Turn-off Delay: associated with a gate output transition to z fromanother value.

§ If the output of gate changes to ‘x’, the minimum of the threedelays is considered.

Page 82: Verilog
Page 83: Verilog

Gate Delays (Contd..)

§ Min / Max / Typ delay values: They represent the minimum,maximum and typical delay value that a designer expects thegate to have.

§ Min, typ or max values can be chosen at runtime by optionsprovided in the simulator.

§ The gate delay cam be specified as follows:<gate_primitive> #(rise_time, fall_time, turnoff_delay)

§ The gate delay can be specified with only one delay time or riseand fall times or with all 3 delay values.

Page 84: Verilog

Gate Delays (Contd..)

// rise, fall & turnoff delaysand #(10) a1( and_out, in1, in2 ); // delay timeor #(14,16) OR( op, i1, i2, i3 ); // rise & fall timesxor #(1, 3, 5) xg( o, a, b ); // rise, fall and turnoff delays// For transition to x, the delay is taken as min(1, 3, 5)

// examples for #(min : typ : max) valuesnot #(2:3:5) inv(out, in); // min delay=2

// typ delay = 3// max delay = 5

Page 85: Verilog

Gate Delays (Contd..)

nor #( 2:3:5, 1:4:7 ) inv( out, in1, in2 );// min rise delay=2, typ rise delay=3, max rise delay=5// min fall delay=1, typ fall delay=4, max fall delay=5

buf #( 2:3:5, 1:4:7, 0:1:3 ) inv( out, in );

/* min rise delay=2, typ rise delay=3, max rise delay=5min fall delay=2, typ fall delay=3, max fall delay=5min turnoff delay=0, typ turnoff delay=1,max turnoff delay=3

*/

Page 86: Verilog

Gate Level Modeling Examples

// 1-bit Half Addermodule ha( sum, carry, a, b );

output sum, carry;input a, b;xor #5 x1( sum, a, b );

// rise, fall and turnoff delayand #(1,2,3) a1( carry, a, b );

endmodule

Page 87: Verilog

Gate Level Modeling Examples (Contd..)

module dff ( Q, Q_BAR, D, CLK );output Q,Q_BAR;input D,CLK;

// Four Instantiations of nand gates nand U1 (X,D,CLK) ;nand U2 (Y,X,CLK) ;nand U3 (Q,Q_BAR,X);nand U4 (Q_BAR,Q,Y);

endmodule

Page 88: Verilog

Dataflow Modeling

§ The data flow between registers and the way that data getsprocesses is modeled using dataflow modeling.

§ Dataflow modeling involves continuous assignments, that isdriving values to the net.

§ assign is used to drive value on the net by continuos assignment.

§ Syntax:

assign <drive_strength> #<delay> <list_of_assignments>;

Page 89: Verilog

Dataflow Modeling (Cont..)

// Regular continuous assignmentwire out;assign out = var1 & var2;

// Same effect is achieved by an implicit continuous assignment wire out = var1 & var2;

Page 90: Verilog

Delays§ A delay control expression specifies the time duration between

initially encountering the statement and when the statementactually executes.e.g.-

#10 A = A + 1;

§ The delay is represented using #. A number followed by # showsthe delay value.

§ In real circuits , logic gates have delays associated with them.Verilog provides the mechanism to associate delays with gates.

§ There are different ways to specify delays in continuousassignments.

Page 91: Verilog

§ Regular Assignment Delay:

§ This is the most commonly used method.§ e.g.-

assign #10 q = x + y;

§ Implicit Continuous Assignment Delay:

§ Similar to implicit assignment statement with delay added.§ e.g. –

wire #10 q = a ^ b;// which is equivalent to the following:// wire out;// assign #10 out = a ^ b;

Delays (Cont..)

Page 92: Verilog

§ Net Declaration Delay:

§ The delay can be put on the net in declaration itself.§ e.g. –

wire #10 out;assign out = a & b;

// which is equivalent to the following:// wire out;// assign #10 out = a & b;

Delays (Cont..)

Page 93: Verilog

// All basic logic gatesmodule gates( invo, ao, oo, nao, noo, xoo, xno, a, b );input a, b;output ao, oo, nao, noo, xoo, xno;

assign invo = ~a;assign ao = a & b;#10 assign oo = a | b;assign #1 nao = a ~& b;assign noo = #3 a ~| b;assign xoo = a ^ b;assign xno = a ~^ b;

endmodule

Dataflow Modeling Examples

Page 94: Verilog

Dataflow Modeling Examples (Contd..)

// 2:1 Multiplexermodule mux21(op, a, b, sel );input [3:0] a, b;input sel;output op;

assign op = sel ? a : b;endmodule

Page 95: Verilog

data ready

input data

overflow

request data

received data

acknowledge data

Behavioral Modeling§ In RTL and Gate level implementation, the details of the

handshake mechanism between different processes are implied.The states are cycle-to-cycle accurate.

Page 96: Verilog

data ready

input data

request data

received data

Behavioral Modeling (Contd..)

§ The behavioral model provides the ability to describe designfunctionality in an algorithmic manner or in higher level ofmodeling where behavior of logic is modeled.

§ In behavioral modeling, you can use events for synchronizing. Thedetails of implementation is based on the application.

Page 97: Verilog

Behavioral Modeling (Contd..)

§ Most of the programming languages (e.g. C, Basic) are sequentialin natural, or only one active process at any one time. However,hardware circuitry is concurrent in nature. All the circuitries areactive in parallel.

§ Verilog supports parallelism by allowing any number of “always”and “initial” blocks. Each “always” and “initial” block runconcurrently.

§ always and initial blocks are called procedural blocks. Assignmentinside procedural blocks are called procedural assignment.

Page 98: Verilog

Procedural Blocks

initialbegin… imperative statements …

end

§ Runs when simulation starts§ Terminates when control

reaches the end§ Good for providing stimulus

alwaysbegin… imperative statements …

end§ Runs when simulation starts§ Restarts when control

reaches the end§ Good for modeling /

specifying hardware

§ Procedural blocks are the basic components for behavioralmodeling.

Page 99: Verilog

§ Run until they encounter a delay.

initial begin#10 a = 1; b = 0;#10 a = 0; b = 1;

end

§ or a wait for an event

always @(posedge clk) q = d;always begin wait(i); a = 0; wait(~i); a = 1; end

Procedural Blocks (Contd..)

Page 100: Verilog

§ Procedural blocks are like concurrent processes.§ Statements in a block are executed sequentially, but all

within one unit of simulated time. (unless delay isspecified)

§ All blocks execute in parallel.

§ initial block§ Executes only once.

§ always block§ Executes repeatedly. It must have timing control,

otherwise it become INFINITE LOOPS

Procedural Blocks (Contd..)

Page 101: Verilog

Procedural Blocks (Contd..)§ Syntax:

type_of_block @(sensitivity_list)statement_group: group_namelocal_variable_declarationstiming_control procedural_statements

end_of_statement_group

§ type_of_block is either initial or always.§ initial procedural blocks process statements one time.§ always procedural blocks process statements

repeatedly.

§ sensitivity_list (optional) is an event timing control thatcontrols when all statements in the procedural blockshould be evaluated. The sensitivity list is used to modelcombinational and sequential logic behavior.

Page 102: Verilog

§ statement_group--end_of_statement_group is used to group twoor more procedural statements together and control theexecution order

§ begin--end groups two or more statements together sequentially,so that statements are evaluated in the order they are listed.

§ Each timing control is relative to the previous statement.

§ fork & join are used to two or more statements together inparallel, so that all statements evaluated concurrently.

§ Each timing control is absolute to when the group started.

Procedural Blocks (Contd..)

Page 103: Verilog

Procedural Assignment§ Procedural statements are statements inside a procedure. (they

execute sequentially)

§ This can be expressed in two types of blocks:

§ initial → they execute only once

§ always → they execute for ever

§ The RHS expression is evaluated and assigned to LHS variablebefore next statement executes.

§ RHS expression may contain wires and regs§ Two possible sources for data

§ LHS must be a reg (rooy) type data type.§ Primitives or cont. assignment may set wire values

Page 104: Verilog

Blocking & Non-blocking Assignments

§ There are two types of assignment statements are there in Verilog:§ Blocking statements§ Non-blocking statements.

§ Blocking Assignment:- It is a way of blocking the furtherstatements until the current statement execution is completed.

§ A blocking assignment must evaluate the RHS arguments andcomplete the assignment without interruption from any otherVerilog statement.

§ The assignment is said to "block" other assignments until thecurrent assignment has completed.

Page 105: Verilog

Blocking & Non-blocking Assignments

§ Non Blocking assignments allow scheduling of assignmentswithout blocking execution of the statements that follow in asequential block.

§ Execution of non-blocking assignments can be viewed as a two-stepprocess:§ Evaluate the RHS of non-blocking statements at the beginning

of the time step.§ Update the LHS of non-blocking statements at the end of the

time step.

Page 106: Verilog

§ The blocking assignment operator is an equal sign (=).

§ The blocking assignment with timing delays on the RHS of theblocking operator, which is considered to be a poor coding style.

§ A problem with blocking assignments occurs when

§ the RHS variable of one assignment in one procedural block isalso the LHS variable of another assignment in anotherprocedural block, and

§ both equations are scheduled to execute in the samesimulation time step, such as on the same clock edge.

Blocking Assignments

Page 107: Verilog

§ If blocking assignments are not properly ordered, a racecondition can occur.

§ When blocking assignments are scheduled to execute in the sametime step, the order execution is unknown.

§ Evaluate the RHS (right-hand side equation) and update theLHS (left-hand side expression) of the blocking assignmentwithout interruption from any other Verilog statement.

Blocking Assignments (Contd..)

Page 108: Verilog

Blocking Assignments Example

module fbosc1 ( y1, y2, clk, rst );output y1, y2;input clk, rst;reg y1, y2;always @(posedge clk or posedge rst )

if (rst) y1 = 0; // resetelse y1 = y2;

always @( posedge clk or posedge rst )if (rst) y2 = 1; // presetelse y2 = y1;

endmodule

Page 109: Verilog

A Flawed Shift Register

§ The following code doesn’t work as one may expect:

module flawed_sr;reg d1, d2, d3, d4;always @(posedge clk) d2 = d1;always @(posedge clk) d3 = d2;always @(posedge clk) d4 = d3;

endmodule

§ Because of all blocking assignments in different always blocks,the order of execution becomes tool-specific. So, the design won’tbehave like shift register!

Page 110: Verilog

Non-blocking Assignments

§ The non-blocking assignment operator is the same as the less-than-or-equal-to operator ("<=").

§ They are called “non-blocking” because-§ the assignment evaluates the RHS expression of a it at the

beginning of a time step, and§ schedules the LHS update to take place at the end of the time

step.

§ Between evaluation of the RHS expression and update of theLHS expression, other Verilog statements can be evaluated andupdated.

Page 111: Verilog

Non-blocking Assignments (Contd..)

§ Also, the RHS expression of other Verilog non-blockingassignments can also be evaluated and LHS updates scheduled.The non-blocking assignment does not block other.

§ Verilog statements from being evaluated. Execution of non-blocking assignments can be viewed as a two-step process:§ Evaluate the RHS of non-blocking statements at the

beginning of the time step.§ Update the LHS of non-blocking statements at the end of the

time step.

Page 112: Verilog

Non-blocking Assignments (Contd..)

module fbosc2 ( y1, y2, clk, rst );output y1, y2;input clk, rst;reg y1, y2;always @( posedge clk or posedge rst )

if (rst) y1 <= 0; // resetelse y1 <= y2;

always @( posedge clk or posedge rst )if (rst) y2 <= 1; // presetelse y2 <= y1;

endmodule

Page 113: Verilog

Non-blocking Assignments (Contd..)

This version works:

reg d1, d2, d3, d4;

always @(posedge clk) d2 <= d1;always @(posedge clk) d3 <= d2;always @(posedge clk) d4 <= d3;

Nonblocking rule:

RHS evaluated when assignment runs

LHS updated only after all events for the current instant have run

Page 114: Verilog

Non-blocking Looks Like Latches

a = 1;

b = a;

c = b;

a <= 1;

b <= a;

c <= b;

1a b c“ ”

a

b

c

1

“ ”

Page 115: Verilog

Looping Flow ControlVerilog supports “for”, “while” and “repeat” and “forever” loop

// example of “for” loopfor( i=0; i<`MEMSIZE; i=i+1)begin

mem[i] = 8’b0;end

// example of “while” loopi = 0;while(i<`MEMSIZE)begin

mem[i] = 8’b0;end

Page 116: Verilog

// example of “repeat” loopi = 0;repeat (`MEMSIZE)begin

mem[i] = 8’b0;i = i + 1;

end

// example of “forever” loopi = 0;foreverbegin : mem_init

mem[i] = 8’b0;i = i + 1;if (i == `MEMSIZE)

disable mem_init;end

Page 117: Verilog

Task and Function

§ Verilog support encapsulation of a piece of code into a task or afunction.

§ Use task or function when:

§ A section of the code that is used more than once, withpossibility different inputs.

§ A code that is expected to be issued interactively.§ Break long procedural blocks into smaller parts in order to

improve readability and maintenance of the code.

Page 118: Verilog

Difference between task and function

§ A task can have timing control constructs, whereas functioncannot.A function can only model combinatorial functionality.

§ The code that initiated a task has to wait for that task tocomplete or disabled before continuing execution.

§ A task can have inputs and outputs, whereas function must haveat least one input and only one output. (which is the name of thefunction itself)

Page 119: Verilog

Example of a task

task task_example;input [1:0] in1, in2;output [1:0] out1, out2;#1 out1 = in1 & in2;#1 out2 = in1 | in2;

endtask

function [1:0] function_example;input [1:0] in1, in2;

function_example = in1 & in2;endfunction

Example of a function

Page 120: Verilog

System Tasks

§ Verilog has some of the inbuilt task as part of the language itself.

§ $display : This system task is used to display the text andformatted data on the screen. It inserts a newline at end ofdisplay text automatically.

§ $monitor : It continuously monitors the changes in any of thevariable/signal specified in the parameter list. Whenever, any oneof them changes, it displays the formatted string specified withindouble quotes.

§ $stop: It stops /suspends the simulation.

Page 121: Verilog

System Tasks (Contd..)

§ $finish: It terminates the simulation.

§ $write: It is similar to $display except that it does not insert anewline at the end of the formatted output by default.

§ $strobe: It is used for strobing purpose. When one wants todisplay the values of the variables which are assigned withinnon-blocking statements, it is a good practice to display themusing $strobe.

§ $random: It generates a 32-bit signed integer randomly. It is usedmainly in test bench.

Page 122: Verilog

System Tasks (Contd..)

§ $time: It returns the current simulation time.

§ $realtime: Same as $time excepts it shows the fraction part aswell.

Page 123: Verilog

Compiler Directives

§ All compiler directives are preceded by a ‘back tick’ ( ` ).

§ `define : It is used to define a text macro in Verilog.

§ `include: It is used to include content of some other file inside aVerilog code.

§ `timescale: It is used to specify the timescale for simulation. Ithas two parts: reference time unit & time precision. First onespecifies the time unit and the later determines the minimumunit that is considered for any round off.`timescale <ref_time_unit>/<precision>

Page 124: Verilog

System Tasks & Compiler Directives Example`timescale 10ns/1ns`define A 10

module abc();reg [3:0] a;

initial begina = 3;$display(“Initializing….\nA = %d”, a);monitor($time, “\tA = %d”, a);#300 $finish;

endalways #25 a = $random;

endmodule

Page 125: Verilog

Synchronization

Verilog support the following type of process synchronization

§ event

§ fork and join

§ disable

Page 126: Verilog

Synchronization - Event

§ # <expression>

suspends execution of the process for a fixed time period

§ @event-expression

suspends the execution of the process until the specified event occurs

§ wait (expression)

suspends the execution of the process until the expression become

true

Page 127: Verilog

§ Verilog supports “event” data type.

module event_example;event e1, e2;…

endmodule

§ Trigger an event using “ ->event_variable”

§ Wait for an event using “@event_variable”

Synchronization (Contd..)

Page 128: Verilog

Synchronization – fork and join

module barrel_sync;

always begin…fork

<statement 1>;<statement 2>;…<statement N>;

join<statement S>;

end

endmodule

<statement 1> to <statement N> are executed in parallel

<statement S> is executed only when <statement 1> to <statement N> are completed

Page 129: Verilog

Synchronization – disable

disable <block_name>§ remove pending events from <block_name>§ will not continue to execute the rest of the <block_name>§ if <block_name> is in the always block, execution continues

from the start of the always block

…always begin : write_block

<statement 1>;…if ( write_through )

disable write_block;out = #10 ram[index];

end…

if “write_through”is true,all pending events (e.g. out=#10 ram[index] from the previous cycle) will be removed. Execution start from <statement 1>

Page 130: Verilog

Forever Statement§ This loop executes continuously and never completes.

§ An infinite loop that continuously executes the statement orstatement group.

§ Infinite loops in Verilog use the keyword forever.

§ You must break up an infinite loop with an @(posedge clock) or@(negedge clock).

§ expression to prevent combinational feedback, as shown in anexample:

§ Syntax; forever<execution statement>initialbegin

clock=0;forever #50 clock=~clock;

end

Page 131: Verilog

Generate Statements

§ Generate statements are used when the same operation ormodule instance is repeated for multiple bits of vector.

§ Generate statements allow control over the declaration ofvariables, functions and tasks as well as control overinstantiations.

§ All generate instantiations are coded with a module scope andrequire keywords generate – endgenerate.

§ There are three methods to create generate statements:§ Generate loop.§ Generate conditional.§ Generate case.

Page 132: Verilog

§ Generate loop: It permits one or more of the following to beinstantiated multiple times using a for loop.

§ Generate conditional :It is like an if-else-if generate constructthat permits the following Verilog constructs to be conditionallyinstantiated based on an expression.

Generate Statements (Contd..)

Page 133: Verilog

Parameters§ A parameter is defined by Verilog as a constant value declared

within the module structure. The value can be used to define a setof attributes for the module which can characterize its behavior aswell as its physical representation.

parameter <identifier> = constant;

parameter byte_size = 8;

reg[byte_size-1:0] A;

§ Used to pass information globally.

Page 134: Verilog

Race Conditions

Page 135: Verilog

Race conditions in Verilog

§ A Verilog race condition occurs when two or more statementsthat are scheduled to execute in the same simulation timestep.

§ It would give different results when the order of statementexecution is changed, as permitted by the Verilog Standard.

§ It can be eliminated by using non-blocking assignments insteadof blocking assignments.

Page 136: Verilog

Race Conditions & their Solutions

module race;reg a;initial begina=0;#10 a=1;end;initial begin#10 if (a) $display(“may not print”);end

endmodule

§ In this example, two parallelblocks have no guaranteedordering, so it is ambiguouswhether the $display statementwill be executed.

§ The solution is to delay the$display with a #0 delay:

initial begin#10 if (a)#0 $display ("may not print");

end

Page 137: Verilog

Flip-Flop Race Condition

module test( out, in, clk );input in, clk;output out;wire a;dff dff0( a, in, clk );dff dff1( out, a, clk );

endmodule

module dff( q, d, clk );output q;input d, clk;reg q;always @(posedge clk)

q = d; // race!endmodule

Page 138: Verilog

§ It is very common to have race conditions near latches or flip-flops.

§ The following is the example of it in which an intermediate nodea between two Flip-flops is set and sampled at the same time.

§ The solution for this is to use the non-blocking assignment in theflip-flop to guarantee the ordering of assignment to the output ofthe flip-flop and sampling of that output.

always @(posedge clk)q <= d;

always @(posedge clk)q = #1 d;

always @(posedge clk)q <= #1 d;

Page 139: Verilog

UDPs

Page 140: Verilog

User Defined Primitives

§ Verilog provides a standard set of primitives, such as and, nand,or, nor, and not, as a part of the language. These are alsocommonly known as built-in primitives.

§ However, designers occasionally like to use their own custom-built primitives when developing a design.

§ Verilog provides the ability to define User-Defined Primitives(UDP).

Page 141: Verilog

User Defined Primitives (Contd..)

§ There are two types of UDPs:§ Combinational UDPs§ Sequential UDPs

§ Combinational UDPs are defined where the output is solelydetermined by a logical combination of the inputs. A goodexample is a 4-to-1 multiplexer.

§ Sequential UDPs take the value of the current inputs and thecurrent output to determine the value of the next output. Thevalue of the output is also the internal state of the UDP. Goodexamples of sequential UDPs are latches and flip-flops.

Page 142: Verilog

§ UDPs can take only scalar input terminals (1 bit). Multiple inputterminals are permitted.

§ UDPs can have only one scalar output terminal (1 bit).

§ The terminal must always appear first in the terminal list.Multiple output terminals are not allowed.

§ In the declarations section, the output terminal is declared withthe keyword output. Since sequential UDPs store state, theoutput terminal must also be declared as a reg.

§ The inputs are declared with the keyword input.

Rules to Define UDP

Page 143: Verilog

§ The state in a sequential UDP can be initialized with an initialstatement. This statement is optional. A 1-bit value is assigned tothe output, which is declared as reg.

§ The state table entries can contain values 0, 1, or x. UDPs do nothandle z values. z values passed to a UDP are treated as xvalues.

§ UDPs are defined at the same level as modules. UDPs cannot bedefined inside modules. They can be instantiated only insidemodules. UDPs are instantiated exactly like gate primitives.

§ UDPs do not support inout ports.

Rules to Define UDP (Contd..)

Page 144: Verilog

Combinational UDP-Exampleprimitive mux4_to_1 ( output out, input i0, i1, i2, i3, s1, s0); table // i0 i1 i2 i3, s1 s0 : out

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

endtable endprimitive

MuxOut

I0I1I2I3

S0 S1

Page 145: Verilog

Sequential UDP - Examples//Define level-sensitive latch by using UDP. primitive latch(q, d, clock, clear); output q; reg q; input d, clock, clear; //sequential UDP initialization //only one initial statement allowed initial q = 0; //initialize output to value 0 //state table table//d clock clear : q : q+ ; ? ? 1 : ? : 0 ; //clear condition,q+ is the new o/p value1 1 0 : ? : 1 ; //latch q = data = 10 1 0 : ? : 0 ; //latch q = data = 0 ? 0 0 : ? : - ; //retain original state if clock = 0

endtable endprimitive

Page 146: Verilog

//Define an edge-sensitive sequential UDP; primitive edge_dff(output reg q = 0, input d, clock, clear); table// d clock clear : q : q+ ;

? ? 1 : ? : 0 ; //output = 0 if clear = 1 ? ? (10) : ? : - ; //ignore negative transition of clear

1 (10) 0 : ? : 1 ; //latch data on negative transition of 0 (10) 0 : ? : 0 ; //clock ? (1x) 0 : ? : - ; //hold q if clock transitions to unknown //state ? (0?) 0 : ? : - ; //ignore positive transitions of clock ? (x1) 0 : ? : - ; //ignore positive transitions of clock (??) ? 0 : ? : - ; //ignore any change in d when clock //is steady

endtable endprimitive (10) àNegative edge transition from 1 to 0

(1x) àTransition from 1 to unknown

(0?) àTransition from 0 to 0,1,x.potential +ve edge transition

(??) àTransition in signal value 0,1, or x to 0, 1, or x

Page 147: Verilog

Modelling FSMs in Verilog

Page 148: Verilog

FSM Classification

Next state Decoder Memory

Output DecoderInput

Output

Clock

Mealy:Output is a function of present state and inputs. Output maychange if inputs change during clock period, due to this theoutputs may have momentary false values because of thedelay encountered from the time the input change and thetime that the FF output change.

Page 149: Verilog

Moore:Output is a function of present state only that are synchronizedwith the clock.

FSM ClassificationFSM Classification

Next state Decoder Memory

Output Decoder

Input Output

Next state Decoder Memory

InputOutput

Clock

Clock

Page 150: Verilog

FSM encoding

Encoding the states is assigning unique binary numbers to the states

State Binary Gray One-hot

Initial 000 000 00001

S1 001 001 00010

S2 010 011 00100

S3 011 010 01000

S4 100 110 10000

Page 151: Verilog

§ BinaryThe number of storage devices (Flip-flops) is minimum.

§ GrayIf it is gray encoded, there will be only one switching

betweenadjacent states. This reduces glitches at the outputs due

tounequal delays of storage devices.

FSM encoding

Page 152: Verilog

§ One-hot§ only one of the state variables will be ‘1’ and all others

will be ‘0’s for a state.§ Complexity of Next state Decoder and Output Decoder is

reduced§ Due to reduced complexity of Decoders , the speed of the

FSM (Max.clock frequency) is not limited by the combinational logic. Hence Faster FSM.

§ Use “casex” for output and next state decoder

FSM encoding

Page 153: Verilog

Modeling Mealy FSMModeling Mealy FSM

§ always@(in or pres_state) //Next //State Decoder

§ always@(posedge clock) //Memory

§ always@(in or pres_state) //Output //Decoder

Ex: “101” Sequence detector

Page 154: Verilog

§ always@(in or pres_state) //NS Dec

§ always@(posedge clock) //Memory

§ always@(pres_state) //Output DecEx: 3-bit counter with output ‘1’ when count is “111”

Modeling Moore FSMModeling Moore FSM

Page 155: Verilog

Verilog Logic Synthesis

Page 156: Verilog

RTL Synthesis

What is RTL

Register : storage element, like flip-flop, latchesTransfer : transfer between input, output and registerLevel : level of abstraction

Page 157: Verilog

RTLsynthesis

RTL Synthesis is a process to transform design description from RTL abstraction to the gate abstraction.

RTL Synthesis

Page 158: Verilog

RTL SynthesisVHDL/Verilog

RTL level Optimization

Structural representation, Control-Data Flow Graph

Logic Level Optimization

Fixed Synchronous logic. Boolean equation representation of

combinational logic

Gate level Optimization

Cell from a technology specific library.

Netlist

Page 159: Verilog

§ It is an important tool to improve designers’ productivity tomeet today’s design complexity.

§ If a designer can design 150 gates a day, it will take 6666man’s day to design a 1 million gate design, or almost 2 yearsfor 10 designers. This is assuming a linear grow of complexitywhen design get bigger.

Why is RTL synthesis important?

Page 160: Verilog

Synthesis Process

Cell Library

Design Constraint

RTL

S y

n t h

e s

i s

Gate

§ Cell Name§ Cell Type§ Cell Function§ Cell Area§ Cell Timing§ Cell Power§ Cell Pin§ Cell Pin Loading§ Cell design rule§ Wire Load Table

§ Area§ Timing§ Power§ Design Rule§ DFT

Operating Condition

Page 161: Verilog

§ Not all Verilog commands synthesize easily.

§ For example initial initializing variables is easy to do in aprogram where all variables are stored.

§ However in hardware only variables stored in flip-flops areeasy to initialize. For this reason only a subset of Verilog issynthesizable. These presentation will concentrate on thatsubset.

Synthesis Process

Page 162: Verilog

Technology Library

§ A Technology Library contains a set of primitive cells which canbe used by synthesis tools to build a circuit.

§ Technology libraries are created by the silicon vendor. Not bythe synthesis tools.

§ A library may contain:§ The timing and electrical characteristics of the cells§ Net delay and net parasitic information§ Definition of capacitance, time and resistance units.

§ Most libraries are compiled before delivery. They can beunderstood by the tools, but are unreadable to you.

Page 163: Verilog

Verilog Procedure§ initial is not synthesizable and is used for test benches.§ always without @ condition, is normally only used in test

benches§ Variables on the left-hand side should be of type reg in a

procedural code , or at least not of type wire. In a structural code the LHS variable should be of type wire

Page 164: Verilog

Only Put Latches If Necessary§ Many procedures do not need to store values. If all left-hand

values can be calculated from a single procedure entry, nothing needs to be stored.

§ In example2 we have initialized the value before the if statement so that it need not have to remember the value where as in example1, since it has to remember the values when enable =0 ,it will infer a latch.

Example 1 Example 2

Page 165: Verilog

Only Put Latches If Necessary§ Every time one executes a procedure all of the variables

defined anywhere in the procedure must be calculated.

§ If the procedure has several paths, every path must evaluate alloutputs. Else synthesis will insert latches to hold the old valueof those unevaluated outputs.

Method 1:Set all outputs to some value at the start of the procedure.Later on different values can overwrite those values.

always @(. . .beginx=0; y=0; z=0;if (a) x=2; elseif (b) y=3; else z=4;end

Page 166: Verilog

Method 2Be sure every branch of every if and case generate every output.

always @(. . .beginif (a)

begin x=2; y=0; z=0;

endelseif (b)

begin x=0; y=3; z=0;

endelse

begin x=0; y=0; z=4; endend

end

Page 167: Verilog

Procedural synthesisLogic InferenceDeciding what logic to synthesize from code is called inference.

always @ Can infer: flip-flops, latches, and/or combinational logic.

always @(posedge Clk)This is the statement that tells the logic compiler to generate flip

flops.

Latches and Combinationalalways @(C or D) :- This may generate a latch. It may just result in

combinational logic.

Page 168: Verilog

Latch InferenceInserting Latches With or Without Your AskingLatches form if//Latch Inference form ifreg Q;always @(Clk or D)beginif (Clk) Q <= D; end//No Latch Inference from ifreg Z;always @(Ck or D)beginZ<=1’b0; //Initializeif (Ck) Z <= D;end

Page 169: Verilog

RTL level Optimization

§ Code related processing is first performed when a model issynthesized. Some of the steps are:

§ Expansion - subprograms are in-lie expanded.

§ Constant folding - eg. A + 3 + 2 becomes A + 5

§ Loop unrolling - loop statements are unrolled to a series ofindividual statements.

§ Dead code removal - any unused code is discarded.

Page 170: Verilog

§ Bit minimization - for example, VHDL state encoding, operatorbit width, or assignments of different widths in Verilog, etc.

§ Different implementations of arithmetic operators have differentarea and timing characteristics. E.g. ‘+’ operator can be carrylook-forward (fastest), carry look-ahead or ripple carry (smallest).

§ Common sub-expression sharing.

§ Operator reordering.

§ Resource sharing, etc.

RTL level Optimization

Page 171: Verilog

CDFG format§ The control data flow graph is often used by synthesis tools for

highest internal representation.

If (S == 1’b0) begin

L <= A + B;

M <= L + L;

N <= A - C; end;

else

N <= A + C;

end if;

FORK

JOIN

MERGE

L=A+B

M=L+LN=A-C

N=A+C

SELECT

CDFG level optimization techniques will be used.

Page 172: Verilog

Logic level optimization

§ All registered elements are fixed, only combinational logic isoptimized.

§ Optimization at this level involves restructuring of equationsaccording to the rules of Boolean law.

§ The types of logic optimization include:§ minimization§ equation flattening§ equation factorization

§ The algorithms used work on multiple equations and multipleoutputs.

Page 173: Verilog

L = A.B.C

Y1=L+A.B.D

Y2=A.B+C+D

Y1=A.B.C+A.B.D

Y2=A.B+C+D

flattenequations

M=A.B

N=C+D

Y1=M.N

Y2=M+Nfactorize

M=A.B

L=M.C

Y1=L+M.D

Y2=M+C+D

factorize

Logic level optimization

Page 174: Verilog

Gate Level Optimization

§ Gate level optimization consists of § Combinational mapping§ Sequential mapping

§ Gate level optimization is a process of looking at local area oflogic containing a few cells and trying to replace them by othercells from the technology library that fit the constraints better.

§ It then looks at another local area with an overlap with the firstlocal area. If the optimization effort is increased then theoptimizer will look at a slightly larger area each time.

Page 175: Verilog

Mapped circuit before gate level optimization.

Page 176: Verilog

After gate level optimization

3 cells14 transistors3.5 equivalent gates

Page 177: Verilog

Verilog Coding Guidelines

Page 178: Verilog

Verilog Coding Guidelines

Guideline #1: When modeling sequential logic, use nonblockingassignments.

Guideline #2: When modeling latches, use nonblocking assignments.

Guideline #3: When modeling combinational logic with an alwaysblock, use blocking assignments.

Guideline #4: When modeling both sequential and combinationallogic within the same always block, use nonblocking assignments

Page 179: Verilog

Guideline #5: Do not mix blocking and nonblocking assignments inthe same always block.

Guideline #6: Do not make assignments to the same variable frommore than one always block.

Guideline #7: Use $strobe to display values that have been assignedusing nonblocking assignments.

Guideline #8: Do not make assignments using #0 delays.

Verilog Coding Guidelines

Page 180: Verilog

Verilog "stratified event queue"

Page 181: Verilog

Electrical Properties

Page 182: Verilog

Signal Types

§ 0 : Logical 0, or false condition§ 1 : Logical 1, or false condition§ Z : High impedance state§ X : Unknown logic condition. Can be 0, 1 or Z

Page 183: Verilog

Signal Types(cont)

0 0

1 1

Z X

0

X Z

1

Z Z

XX

Page 184: Verilog

0

X0

1

X1

1

XX

0

XX

S0

S1

SEL

Z

1X11

0X00

S11XX

S00XX

ZSELS1S0

Signals (cont)

Page 185: Verilog

Signal Strength (cont)

Su1St1

Pu1La1We1

Me1Sm1HiZ1

HiZ0

Sm0

Me0We0La0Pu0St0

Su0

7654321001234567

Logic 1 strengthLogic 0 strength

Su1(7)

La0(4)

Su1(7)

Page 186: Verilog

Verilog Syntax for Strength

Only for gate instantiation

// and gate with weak pull upand (supply0, weak1) (out, in1, in2);

Note:Valid strength keywords are supply1, strong1, pull1, weak1, highz1, supply0, strong0, pull0, weak0, highz0.

Page 187: Verilog

Support for transmission gatercmos, rpmos, rnmos, rtran, rtranif0,rtrainif1 reduce the output strength as follow:

in1

out

in0

sel

High impedanceHigh impedance

Medium capacitor

Weak drive

Weak drivePull drive

Pull driveStrong drive

Pull driveSupply drive

Output StrengthInput Strength

Page 188: Verilog

Timing Delay in ASIC libraryPin-to-Pin delay

A1

A2

Z

A1 to Z delay

A2 to Z delay

module AND2 (Z, A1, A2);input A1, A2;output Z;and (Z, A1, A2);specifyspecparam A1_to_Z=12,

A2_to_Z=14;(A1 => Z) = A1_to_Z; (A2 => Z) = A2_to_Z;endspecifyendmodule

Page 189: Verilog

Timing Delay in Gate

Verilog

PhysicalInformation

DelayCalculation SDF

Back-annotation

Page 190: Verilog

Timing Delay Calculation

RCnetwork

Load

Skew

Delay

Load

Inputskew

Outputskew

SDF

TableLook-up

Cell Library

Page 191: Verilog

Timing Delay - SDF Back-Annotation

Using system task $sdf_annotate(). Example

§ $sdf_annotate(“full_chip.sdf”);§ $sdf_annotate(“mod1.sdf”, mod1, , “mod1_sdf.log”);

Note:$sdf_annotate() can be placed anywhere in the HDL code. However, it make no sense to put it after time 0

Page 192: Verilog

Macros, Conditional Compilation

&Naming Convention

Page 193: Verilog

Macro

§ Macro names and the names used in the design are different

§ Macro definition is global. There is not scope restriction.§ Macro can be re-define. The last definition read is used.

§ Keyword cannot be used as macro name. (It does not make sense).

§ One line comment (//) will be excluded in the text substituted.§ Macro can also be defined in the command line. These macro has

the highest priority.(e.g. verilog design.v +define+regressionSuit=“4” )

Page 194: Verilog

�define WORD 8 //word size‘define CLOCKMUX ssmux8

module register(…)reg [‘WORD-1 : 0] cpu_reg;…‘CLOCKMUX hand_clockMux (…);…endmodule

Macro Cont..

Page 195: Verilog

Conditional Compilation§ �ifdef, ‘else and ‘endif can be nested§ Syntax for the ignored Verilog texts are not checked.§ Verilog simulator does not keep record of the ignored text. Thus

any output (e.g. profiling and encryption) from the simulation does not retain the full Verilog input.

module adder(a, b, c);output [8:0] a; input [7:0] b, c;reg [8:0] a;always @ (b or c) begin‘ifdef BEHAVIOURAL

a = b + c;‘else

gateAdder #(8, 7, 7)i0 (a, b, c);‘endifendendmodule

Page 196: Verilog

Good Naming Convention

§ Use all upper-case for constants specified by ‘define macro and

code inclusion control name defined by ‘ifdef and ‘define.§ Use short instance name.

§ Unique pre-fix for modules belong to the same circuit partition.

§ Use the same port name and wire name when the signal goes through different hierarchy.

§ Use very short name in ASIC library.§ Do not use port names that are used in the ASIC library.

Page 197: Verilog

Verilog for Logic Simulation

Page 198: Verilog

Introduction

Design

TestbenchSimulation

Waveform

Log

KeyLog

Inputcommand

line

Page 199: Verilog

File Output

$display(), $write() and $monitor() have a counterpart to write to a specific file, beside the log file.

integer fileID;

initial beginfileID = $fopen(“capture.dat”);if (fileID == 0)

$finish;$fdisplay(fileID, “Start Simulation %s”,

$pli_currentDateTime() );end

Page 200: Verilog

Test bench§ The following things are essentially required to be

provisioned a test bench.

§ timing control

§ input stimulus

§ device under test§ reference model

§ diagnostic logging§ assertion checking

Page 201: Verilog

Test bench – timing control

initial begin#10 inputA = 1’b1;#12 inputB = 1’b1; inputC=1’b0; inputD=1’b1;#9 {inputA, inputB} = 2’b00;

end

initial beginclock = 1’b0;forever

#10 clock = !clock;end

Page 202: Verilog

Waveform Probing using VCD

Verilog supports Value Change Dump (VCD) output. A VCD

waveform viewer can show the result in the form of waveform display.

Specify VCD filename

Specify dump variable

Start/Stop dumping

$dumpfile(“<fileName>”);

$dumpvars(<level> <,<module or variable>>*);

$dumpon; / $dumpoff;

Page 203: Verilog

$dumpfile;§ Dump all variables in the design.

$dumpfile(1, top.mod1);§ Dump all variables in the module top.mod1.

$dumpfile(0, top.mod1);§ Dump all variables in the module top.mod1, and in all module

instances below top.mod1 in the design hierarchy.

$dumpfile(0, top.mod1, top.mod2.net1);§ Dump all variables in top.mod1 and all modules instantiate

below top.mod1. Net top.mod2.net1 is also dumped. <level> only affect module, not variable.

Waveform Probing using VCD

Page 204: Verilog

Interactive DebuggingSimulation control (depends on simulator)

§ $finish() : finish the simulation§ $stop() : stop simulation and enter interactive mode

§ . : continue simulation

§ , ; : step§ $reset : restart the simulation

§ $reset_count : number of times $reset is called

Some useful system tasks§ $showvars() : show unresolved values of specified variables§ $system() : execute a system command§ $showallinstance(): show number of instances of each module,

gate and primitive in the design

Page 205: Verilog

Simulation Tips 1Zero-delay loopA common mistake in big design. Usually indicates a logic error.

module top(reset);input reset;reg a;

always beginif ( !reset ) begin // what happen when

#10 a = 0; // reset is 1#10 a = 1;

endend

endmodule

Page 206: Verilog

A more complicated zero delay loop

module top;reg clk, reset, d;reg [3:0] a, b, c, res;

initial beginclk = 0;forever #10 clk = !clk;

end

initial beginreset = 0;#10 reset = 1;#10 reset = 0;#1000 $finish;

end

always @(posedge clk orposedge reset)

if(reset){a,b,c,d}=13’b0;

else d = !d;

always @(a or d) beginb = b + 1’b1;if (d) res = b + d;

end

always @(b) c = c + 1’b1;

always @(c) a = a + 1’b1;endmodule

Page 207: Verilog

Simulation Tips 2

Accelerated vs. Non-accelerated Construct

…reg var;parameter delay=10assign #delay a = b;assign #(delay + 1) c = d;assign e = f & g;

assign #var h = i;assign j = k + m;…

Acceleratedcontinuousassignment

Non-acceleratedcontinuousassignment

Page 208: Verilog

Simulation Tips 3Timing violation in register when crossing timing domains

clk1

clk2

syncDunSyncD

unSyncD

clk2

syncD

Page 209: Verilog

The timing violation can “kill” the simulation. The “X”state get propagated to the rest of the circuit, and the simulation becomes meaningless.

clk1

clk2

unSyncD

sel

Page 210: Verilog

Introduction to PLI

Page 211: Verilog

Where PLI is Used

§ The Programming Language Interface (PLI) provides a set of interface routines to read internal data representation, write to internal data representation, and extract information about the simulation environment. User-defined system tasks and functions can be created with this predefined set of PLI interface routines.

§ PLI is used to customize the capability of the Verilog language by defining their own system tasks and functions for which designers need to interact with the internal representation of the design and the simulation environment in the Verilog simulator.

Page 212: Verilog

Simulation Flow Using PLI routines

Page 213: Verilog

§ Task/Function (tf_) routines make up the first generation PLI.These routines are primarily used for operations involving user-defined task/function arguments, utility functions, callbackmechanism, and writing data to output devices.

§ Access (acc_) routines make up the second-generation PLI. Theseroutines are provide object-oriented access directly into a VerilogHDL structural description. These routines can be used to accessand modify a wide variety of objects in the Verilog HDLdescription.

§ Verilog Procedural Interface (vpi_) routines make up the third-generation PLI. These routines are a superset of the functionalityof acc_ and tf_ routines.

Generations of Verilog PLI

Page 214: Verilog

Uses Of PLI§ PLI can be used to define additional system tasks and functions.

Typical examples are monitoring tasks, stimulus tasks,debugging tasks, and complex operations that cannot beimplemented with standard Verilog constructs.

§ Application software like translators and delay calculators can bewritten with PLI.

§ PLI can be used to extract design information such as hierarchy,connectivity, fanout, and number of logic elements of a certaintype.

§ PLI can be used to write special-purpose or customized outputdisplay routines. Waveform viewers can use this file to generatewaveforms, logic connectivity, source level browsers, andhierarchy information.

Page 215: Verilog

Uses Of PLI (Contd..)§ Routines that provide stimulus to the simulation can be written

with PLI. The stimulus could be automatically generated ortranslated from some other form of stimulus.

§ General Verilog-based application software can be written withPLI routines. This software will work with all Verilog simulatorsbecause of the uniform access provided by the PLI interface.

Page 216: Verilog

example of a simple system task $hello_verilog#include "veriuser.h" /*include the file provided in release dir */ int hello_verilog(){ io_printf("Hello Verilog World\n");}

Linking and Invocation of PLI Tasks

§ Whenever the task $hello_verilog is invoked in the Verilogcode, the C routine hello_verilog must be executed. Thesimulator needs to be aware that a new system task called$hello_verilog exists and is linked to the C routinehello_verilog. This process is called linking the PLI routinesinto the Verilog simulator.

Page 217: Verilog

§ At the end of the linking step, a special binary executablecontaining the new $hello_verilog system task is created. Forexample, instead of the usual simulator binary executable, anew binary executable hverilog is produced. To simulate, runhverilog instead of your usual simulator executable file.

§ Once the user-defined task has been linked into the Verilogsimulator, it can be invoked like any Verilog system task bythe keyword $hello_verilog. A Verilog module hello_top, whichcalls the task $hello_verilog, is defined in file hello.v as shownbelow:

module hello_top;initial $hello_verilog; //Invoke the user-defined task $hello_verilogendmodule

Output of the simulation is as follows:Hello Verilog World

Page 218: Verilog

Summary

Page 219: Verilog

Summary of Verilog

§ Systems described hierarchically§ Modules with interfaces§ Modules contain instances of primitives, other modules§ Modules contain initial and always blocks

§ Based on discrete-event simulation semantics§ Concurrent processes with sensitivity lists§ Scheduler runs parts of these processes in response to

changes

Page 220: Verilog

Modeling Tools§ Switch-level primitives

CMOS transistors as switches that move around charge.

§ Gate-level primitivesBoolean logic gates

§ User-defined primitivesGates and sequential elements defined with truth tables

§ Continuous assignmentModeling combinational logic with expressions

§ Initial and always blocksProcedural modeling of behavior

Page 221: Verilog

Language Features

§ Nets (wires) for modeling interconnection§ Non state-holding§ Values set continuously

§ Regs for behavioral modeling§ Behave exactly like memory for imperative modeling.§ Do not always correspond to memory elements in synthesized

netlist.

§ Blocking vs. nonblocking assignment§ Blocking behaves like normal “C-like” assignment§ Nonblocking updates later for modeling synchronous behavior

Page 222: Verilog

Language Uses

§ Event-driven simulation§ Event queue containing things to do at particular simulated

times.§ Evaluate and update events.§ Compiled-code event-driven simulation for speed.

§ Logic synthesis§ Translating Verilog (structural and behavioral) into netlists.§ Register inference: whether output is always updated.§ Logic optimization for cleaning up the result.

Page 223: Verilog

Little-used Language Features

§ Switch-level modeling§ Much slower than gate or behavioral-level models.§ Insufficient detail for modeling most electrical problems.§ Delicate electrical problems simulated with a SPICE-like

differential equation simulator.

§ Delays§ Simulating circuits with delays does not improve confidence

enough.§ Hard to get timing models accurate enough.§ Never sure you’ve simulated the worst case.§ Static timing analysis has taken its place.

Page 224: Verilog

Verilog Strengths and Weaknesses § Verilog is widely used because it solves a problem§ Good simulation speed that continues to improve.§ Designers use a well-behaved subset of the language.§ Makes a reasonable specification language for logic synthesis.§ Logic synthesis one of the great design automation success

stories.

§ Verilog is a deeply flawed language§ Non-deterministic.§ Often weird behavior due to discrete-event semantics.§ Vaguely defined synthesis subset.§ Many possible sources of simulation/synthesis mismatch.

Page 225: Verilog

References

§ http://www.asic-world.com/verilog/.§ Palnitkar, Samir, Verilog HDL: A Guide to Design and Synthesis§ www.sunburst-design.com.§ IEEE Standard Hardware Description Language Based on the

Verilog Hardware Description Language, IEEE Computer Society, IEEE Std 1364-1995.

Page 226: Verilog

ThanQ