Verilog Tut

download Verilog Tut

of 21

Transcript of Verilog Tut

  • 7/29/2019 Verilog Tut

    1/21

    The Verilog Language

    Aleksandar MilenkovicE-mail: [email protected]

    Web: http://www.ece.uah.edu/~milenka

    2

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments

    Timing Controls and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

    3

    The Verilog Language

    Originally a modeling languagefor a very efficient event-driven digital logic simulator

    Later pushed into use as a specification languagefor logic synthesis

    Now, one of the two most commonly-used languages indigital hardware design (VHDL is the other)

    Combines structural and behavioral modeling styles

    Introduction

    4

    Multiplexer Built From Primitives

    a

    b

    sel

    f

    nself1

    f2

    g1

    g2

    g3g4

    Verilog programs builtfrom modulesEach module hasan interface

    Module may containstructure: instances ofprimitives and othermodules

    modul e mux( f , a, b, sel ) ;output f ;i nput a, b, sel ;

    and g1( f 1, a, n sel ) ,g2(f 2, b, sel );

    or g3( f , f 1, f 2) ;not g4( nsel , sel ) ;

    endmodul e

    Introduction

    5

    Multiplexer Built From Primitives

    a

    b

    sel

    f

    nself1

    f2

    g1

    g2

    g3g4

    Identifiers notexplicitly defineddefault to wires

    modul e mux( f , a, b, sel ) ;out put f ;i nput a, b, sel ;

    and g1( f 1, a , ns el ) ,g2(f 2, b, sel) ;

    or g3( f , f 1, f 2) ;not g4( nsel , sel ) ;

    endmodul e

    Introduction

    6

    Multiplexer Built With Always

    a

    b

    sel

    f

    Modules may contain oneor more always blocks

    Sensitivity listcontains signalswhose change

    triggers theexecution of theblock

    modul e mux( f , a, b, sel ) ;out put f ;i nput a, b, sel ;reg f ;

    al ways @( a or b or sel )

    i f ( s el ) f = b;el se f = a;

    endmodul e

    Introduction

  • 7/29/2019 Verilog Tut

    2/21

    7

    Multiplexer Built With Always

    a

    b

    sel

    f

    A regbehaves like memory:holds its value untilimperatively assignedotherwise

    Body of an alwaysblock containstraditional imperativecode

    modul e mux( f , a, b, sel ) ;out put f ;i nput a, b, sel ;

    reg f ;

    al ways @( a or b or sel )i f ( sel ) f = a;el se f = b;

    endmodul e

    Introduction

    8

    Mux with Continuous Assignment

    a

    b

    sel

    f

    LHS is always set to thevalue on the RHS

    Any change on the right

    causes reevaluation

    modul e mux( f , a, b, sel ) ;out put f ;i nput a, b, sel ;

    assi gn f = sel ? a : b;

    endmodul e

    Introduction

    9

    Mux with User-Defined Primitive

    a

    b

    sel

    f

    Behavior defined using atruth table that includesdont cares

    This is a less pessimisticthan others: when a & bmatch, sel is ignored

    (others produce X)

    pri mi ti ve mux(f, a, b, sel );output f ;i nput a, b, sel ;

    tabl e1?0 : 1;0?0 : 0;?11 : 1;?01 : 0;11? : 1;00? : 0;

    endtabl eendpri mi t i ve

    Introduction

    10

    How Are Simulators Used?

    Testbench generates stimulus and checks response

    Coupled to model of the system

    Pair is run simultaneously

    Testbench System Model

    Stimulus

    ResponseResultchecker

    Introduction

    11

    Styles

    Structural - instantiation of primitives and modules

    RTL/Dataflow - continuous assignments

    Behavioral - procedural assignments

    Introduction

    12

    Structural Modeling

    When Verilog was first developed (1984) most logicsimulators operated on netlists

    Netlist: list of gates and how theyre connected

    A natural representation of a digital logic circuit

    Not the most convenient way to express test benches

    Introduction

  • 7/29/2019 Verilog Tut

    3/21

    13

    Behavioral Modeling

    A much easier way to write testbenches

    Also good for more abstract models of circuits

    Easier to write

    Simulates faster

    More flexible

    Provides sequencing

    Verilog succeeded in part because it allowed both themodel and the testbench to be described together

    Introduction

    14

    Style Example - Structural

    module full_add (S, CO, A, B, CI) ;

    output S, CO ;input A, B, CI ;

    wire N1, N2, N3;

    half_add HA1 (N1, N2, A, B),HA2 (S, N3, N1, CI);

    or P1 (CO, N3, N2);

    endmodule

    module half_add (S, C, X, Y);

    output S, C ;input X, Y ;

    xor (S, X, Y) ;and (C, X, Y) ;

    endmodule

    Introduction

    15

    Style Example Dataflow/RTL

    module fa_rtl (S, CO, A, B, CI) ;

    output S, CO ;input A, B, CI ;

    assign S = A ^ B ^ CI; //continuous assignmentassign CO = A & B | A & CI | B & CI; //continuous assignment

    endmodule

    Introduction

    16

    Style Example Behavioral

    module fa_bhv(S, CO, A, B, CI) ;

    output S, CO ;input A, B, CI ;

    reg S, CO; // required to hold values between events.

    always@(A or B or CI) //;begin

    S

  • 7/29/2019 Verilog Tut

    4/21

    19

    An Example: Counter (contd)

    Verilog using ModelSim Assume working directory: cpe626/VlogExamples/Counter

    Invoke ModelSim

    Change Directoryto cpe626/VlogExamples/Counter

    Copy file counter.v to the working directory

    Create a design library: vlib work

    Compile counter.v: vlog counter.v

    Start the simulator: vsim counter

    Run the simulation: e.g., run 200ns

    > run 200# ti me = 20 count = 1# ti me = 40 count = 2# ti me = 60 count = 3# ti me = 80 count = 4# ti me = 100 count = 5# ti me = 120 count = 6# ti me = 140 count = 7# ti me = 160 count = 0# ti me = 180 count = 1# ti me = 200 count = 2

    Introduction

    20

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments

    Timing Controls and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

    21

    Basics of the Verilog Language

    Language Conventions

    Logic Values

    Data Types

    Wire Types

    Numbers

    Negative Numbers

    Strings

    22

    Language Conventions

    Case-sensitivity

    Verilog is case-sensitive.

    Some simulators are case-insensitive

    Advice: - Dont use case-sensitive feature!

    Keywords are lower case

    Different names must be used for different itemswithin the same scope

    Identifier alphabet:

    Upper and lower case alphabeticals

    decimal digits

    underscore

    Basics of theVerilog

    23

    Language Conventions (contd)

    Maximum of 1024 characters in identifier

    First character not a digit

    Statement terminated by ;

    Free format within statement except for within quotes

    Comments: All characters after // in a line are treated as a

    comment

    Multi-line comments begin with /* and end with */

    Compiler directives begin with // synopsys

    Built-in system tasks or functions begin with $

    Strings enclosed in double quotes and must be on a singleline

    Basics of theVerilog

    24

    Four-valued Logic

    Verilogs nets and registers hold four-valued data

    0, 1 Logical Zero, Logical One

    z

    Output of an undriven tri-state driver high-impedance value

    Models case where nothing is setting a wires value

    x Models when the simulator cant decide the value

    uninitialized or unknown logic valueo Initial state of registers

    o When a wire is being driven to 0 and 1 simultaneously

    o Output of a gate with z inputs

    Basics of theVerilog

  • 7/29/2019 Verilog Tut

    5/21

    25

    Four-valued Logic (contd)

    Logical operators work on three-valued logic

    0 1 X Z

    0 0 0 0 0

    1 0 1 X X

    X 0 X X X

    Z 0 X X X

    Output 0 if one inputis 0

    Output X if bothinputs are gibberish

    Basics of theVerilog

    26

    Two Main Data Types

    Nets represent connections between things Do not hold their value

    Take their value from a driver such as a gate or

    other module Cannot be assigned in an initialor alwaysblock

    Regs represent data storage Behave exactly like memory in a computer

    Hold their value until explicitly assignedin an initialor alwaysblock

    Never connected to something

    Can be used to model latches, flip-flops, etc.,but do not correspond exactly

    Shared variables with all their attendant problems

    Basics of theVerilog

    27

    Data Types

    nets are further divided into several net types

    wire, tri, supply0, ...

    registers - stores a logic value - reg

    integer - supports computation

    time - stores time 64-bit unsigned

    real - stores values as real num

    realtime - stores time values as real numbers

    event an event data type

    Wires and registers can be bits, vectors, and arrays

    Basics of theVerilog

    28

    Nets and Registers (contd)Basics of the

    Verilog

    modul e decl arat i ons_4;

    wi re Data; // a scal ar net of type wi re

    wi re [31:0] ABus, DBus; // two 32-bi t wi de vector wi res. . .

    // DBus[31] = l eft- most = most-s i gni f i cant bi t = msb

    / / DBus[0] = r i ght -most = l eas t - s igni f i cant b i t = l sb

    / / Noti ce the si ze decl arati on precedes t he names

    // wi re [31:0] TheBus, [15:0] Bi gBus; // i l l egal

    reg [3:0] vector; // a 4-bit vector register

    reg [4: 7] nibble; // msb i ndex < l sb i ndex

    i nteger i;

    i n i t i a l begi n

    i = 1;

    vector = ' b1010; / / vector wi thout an i ndex

    nibbl e = vector; // this i s OK too

    #1; $di splay("T=%0g", $ti me," vector=", vector, " ni bbl e=", nibble) ;

    #2; $displ ay("T=%0g",$t i me," Bus=%b", DBus[15: 0]) ;

    end

    assign DBus [1] = 1; // this i s a bit- select

    assign DBus [3:0] = ' b1111; // this i s a part- select

    // assi gn DBus [0:3] = ' b1111; // i l l egal - wrong directi on

    endmodul e

    29

    Nets and Registers (contd)

    i n t ege r imem[ 0: 1 023] ; / / Ar r ay o f 1024 i n t ege r s

    reg [31:0] dcache[0: 63]; / / A 64-word by 32-bi t wi de memory

    t ime t ime_l og[ 1: 1 000] ; / / as an ar ray o f r egs

    / / real I l l egal [1 :10] ; / / I l l egal . There are no real arrays.

    Basics of theVerilog

    modul e declar ati ons_5;

    reg [31: 0] Vi deoRam[ 7:0] ; / / a 8-word by 32-bi t wide memory

    in i t i a l b eginVi deoRam[1] = ' bxz; / / must speci fy an i ndex for a memory

    Vi deoRam[2] = 1;

    Vi deoRam[7] = VideoRam[Vi deoRam[2] ]; / / need 2 clock cycl es for t hi s

    VideoRam[8] = 1; / / careful ! t he compil er won't complai n!

    / / Veri fy what we entered:

    $displ ay("Vi deoRam[0] i s %b", VideoRam[0] );

    $displ ay("Vi deoRam[1] i s %b", VideoRam[1] );

    $displ ay("Vi deoRam[2] i s %b", VideoRam[2] );

    $displ ay("Vi deoRam[7] i s %b", VideoRam[7] );

    end

    endmodul e

    30

    Net Types

    wire - connectivity only

    tri - same as wire, but will be 3-stated in hardware

    wand - multiple drivers - wired and

    wor - multiple drivers - wired or

    triand - same as wand, but 3-state trior - same as wor but 3-state

    supply0 - Global net GND

    supply1 - Global Net VCC (VDD)

    tri0, tri1 model resistive connections to VSS and VDD

    trireg like wire but associates some capacitancewith the net, so it can model charge storage

    Basics of theVerilog

  • 7/29/2019 Verilog Tut

    6/21

    31

    Declarations: An Example

    modul e declar ati ons_1;

    wi re pwr_good,pwr_on,pwr_st able; / / Expli ci tl y declare wi res

    i nteger i ; / / 32-bi t, si gned (2' s complement)

    ti me t; / / 64-bi t, unsi gned, behaves l i ke a 64-bi t reg

    event e; / / Decl are an event data type

    real r; / / Real data type of i mplementati on defi ned si ze

    // assign statement conti nuousl y dri ves a wi re. ..

    assign pwr_st abl e = 1'b1; assign pwr_on = 1; / / 1 or 1'b1

    assi gn pwr_ good = pwr_ on &pwr_st able;

    i n i t i a l begin

    $displ ay("pwr_ on=", pwr_ on);

    i = 123.456; / / There must be a digi t on eit her si de

    r = 123456e-3; / / of the deci mal poi nt i f i t i s present.

    t = 123456e-3; / / Ti me i s rounded to 1 second by default .

    $di splay("i =%0g", i , " t=%6.2f", t, " r=%f" ,r );

    #2 $di spl ay(" TI ME=%0d", $ti me, " ON=", pwr_ on,

    " STABLE=", pwr _st abl e, " GOOD=", pwr_ good);

    end

    endmodul e

    # pwr _on=x

    # i =123 t=123.00 r =123.456000

    # TI ME=2 ON=1 STABLE=1 GOOD=1

    32

    Register Assignment

    A register may be assigned value only within:

    a procedural statement

    a user-defined sequential primitive

    a task, or

    a function.

    A reg object may never be assigned value by:

    a primitive gate output or

    a continuous assignment

    Examples

    reg a, b, c;

    reg [15:0] counter, shi f t_ reg;

    i nteger sum, di f f erence;

    Basics of theVerilog

    33

    Constants & Strings

    Constants

    Strings No explicit data type

    Must be stored in reg (or array)

    Basics of theVerilog

    parameter A = 2b00, B = 2b01, C = 2b10;

    parameter regsi ze = 8;

    reg [r egsi ze - 1:0]; / * i l l ustrates use of parameter regsi ze */

    reg [255: 0] buff er; / / stores 32 charactersparameter Tab = "\ t" ; / / tab characterparameter NewLi ne = "\ n"; / / newl i ne charact erparameter BackSlash = "\ \ "; / / back sl ash

    34

    Number Representation

    Format:

    - decimal specification of number of bits

    o default is unsized and machine-dependent but at least 32 bits

    - ' followed by arithmetic base of number

    o - decimal - default base if no given

    o - hexadecimal

    o - octal

    o - binary

    - value given in base of

    o_ can be used for reading clarity

    o If first character of sized, binary number 0, 1, x or z, willextend 0, 1, x or z (defined later!)

    Basics of theVerilog

    35

    Number Representation

    Examples:

    6b010_111 gives 010111

    8'b0110 gives 00000110

    4'bx01 gives xx01

    16'H3AB gives 0000001110101011

    24 gives 00011000

    5'O36 gives 11100

    16'Hx gives xxxxxxxxxxxxxxxx

    8'hz gives zzzzzzzz

    Basics of theVerilog

    36

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments Timing Controls and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

  • 7/29/2019 Verilog Tut

    7/21

    37

    Operators

    Arithmetic (pair of operands, binary word)[binary: +, -,*,/,%*]; [unary: +, -]

    Bitwise (pair of operands, binary word)[~, &,|,^,~^,^~]

    Reduction (single operand, bit) [&,~&,|,~|,^,~^,^~]

    Logical (pair of operands, boolean value)[!,&&,||,==,!=,===,!==]

    Relational (pair of operands, boolean value) [=]

    Shift (single operand, binary word) [>>, (right shift)

    Conditional

    E.g.: Y = (A==B) ? A: B

    wire[15:0] bus_a = drive_bus_a ? data : 16bz;

    Concatenation

    {4{a}} = {a, a, a, a}

    Operators

    40

    Operators (contd)Operators

    modul e operat ors;

    parameter A10xz = {1' b1, 1'b0,1' bx,1'bz}; / / concatenati on

    parameter A01010101 = {4{2' b01}}; / / repl i cati on

    / / ari thmeti c operators: +, - , *, / , and modulus %

    parameter A1 = (3+2) %2; / / resul t of % takes si gn of argument #1

    / / l ogi cal shi f t operators : > ( r i ght )

    parameter A2 = 4 >> 1; parameter A4 = 1 2) $s top;

    // l ogi cal operators: ! (negati on), &&( and), || (or)

    parameter B0 = !12; parameter B1 =1 && 2;

    reg [2:0] A00x; i nit i al begin A00x = ' b111; A00x = !2' bx1; end

    parameter C1 = 1 || (1/ 0); / * thi s may or may not c ause an

    error: the short-ci rcuit behavior of && and || i s undef i ned. An

    evaluat i on incl udi ng && or | | may stop when an expressi on is known

    to be true or f alse */

    / / == ( l ogical equal i t y ) , != ( l ogical inequal i ty )

    parameter Ax = (1==1' bx); parameter Bx = (1' bx!=1' bz);

    paramet er D0 = (1==0); parameter D1 = (1==1);

    . . .

    41

    Operators (contd)Operators

    . . .

    parameter D0 = ( 1==0); parameter D1 = ( 1==1);

    // === case equali ty, ! == (case i nequal i ty)

    // case operators only return tr ue or fal se

    parameter E0 = (1===1' bx); parameter E1 = 4' b01xz === 4' b01xz;

    parameter F1 = (4' bxxxx === 4' bxxxx);

    / / bi twi se l ogi cal :

    / / ~ (negat ion) , & (and) , | ( i ncl usi ve or) ,

    // ^ (excl usi ve or), ~ or ~ (equi val ence)parameter A00 =2' b01 & 2' b10;

    // unary logical reducti on:

    // & (and), ~&( nand), | (or) , ~| (nor),

    // ^ (xor), ~ or ~ (xnor)

    parameter G1= & 4' b1111;

    // condit i onal expression x =a ? b : c

    / / i f (a) then x = b el se x = c

    reg H0, a, b, c; i nit i al begin a=1; b=0; c=1; H0=a?b:c; end

    reg[2:0] J 01x, J xxx, J 01z, J 011;

    i nit i al begin J xxx = 3'bxxx; J01z =3' b01z; J011 =3'b011;

    J 01x = J xxx ? J 01z : J 011; end / / bi t wi se r esul t

    . . . .

    42

    Expression Bit Widths

    Depends on:

    widths of operands and

    types of operators

    Verilog fills in smaller-width operands

    by using zero extension. Final or intermediate result width

    may increase expression width

    Unsized constant number - same as integer (usually 32bit)

    Sized constant number - as specified

    x op y where op is +, -, *, /, %, &, |, ^, ^~:

    Arithmetic binary and bitwise

    Bit width = max (width(x), width(y))

    Operators

  • 7/29/2019 Verilog Tut

    8/21

    43

    Expression Bit Widths (continued)

    op x where op is +, - Arithmetic unary

    Bit width = width(x)

    op x where op is ~ Bitwise negation

    Bit width = width(x)

    x op y where op is ==, !==, ===, !===, &&, ||, >, >=,

  • 7/29/2019 Verilog Tut

    9/21

    49

    Module Declaration

    Basic structure of a Verilog module:

    modul e mymod( out put 1, out put 2, i nput1, i nput2) ;

    out put out put 1;out put [ 3:0] out put 2;

    i nput i nput1;

    i nput [2: 0] i nput 2;

    endmodul e

    Modules

    50

    Module Declaration (contd)

    Example:

    / * module_keyword module_i denti f i er ( l i st of ports) */

    modul e C24DecoderWi t hEnabl e ( A, E, D) ;i nput [1:0] A; / / i nput_declarati on

    i nput E; / / i nput_declarati on

    output [3:0] D; / / output_decl arati on

    assi gn D = {4{E}} & ( ( A == 2' b00) ? 4' b0001 :

    ( A == 2' b01) ? 4' b0010 :

    ( A == 2' b10) ? 4' b0100 :

    ( A == 2' b11) ? 4' b1000 :

    4' bxxxx) ; / / conti nuous_assign

    endmodul e

    Modules

    51

    Module Declaration (contd)

    Identifiers - must not be keywords!

    Ports First example of signals

    Scalar: e. g., E

    Vector: e. g., A[1:0], A[0:1], D[3:0], and D[0:3]

    o Range is MSB to LSB

    o Can refer to partial ranges - D[2:1]

    Type: defined by keywords

    o input

    o output

    o inout (bi-directional)

    Modules

    52

    Module Instantiation

    Instances of

    look like

    modul e mymod(y, a, b) ;

    mymod mm1(y1, a1, b1); / / Connect- by-posi ti on

    mymod ( y2, a1, b1) ,

    ( y3, a 2, b 2) ; / / I ns t ance names omi t t e d

    mymod mm2(. a(a2), . b(b2), . y(c2) ) ; / / Connect - by- name

    Modules

    53

    Module Instantiation (contd)

    Example: 4/16 decoder using 2/4 decoders

    modul e C416Decoder Wi t hEnabl e ( A, E, D) ;

    i nput [3: 0] A ;

    i nput E;

    out put [ 15: 0] D ;

    wi re [3: 0] S;

    C24Decoder Wi t hEnabl e DE ( A[3: 2], E, S);

    C24DecoderWi thEnabl e D0 ( A[1: 0], S[0], D[ 3:0] ) ;

    C24DecoderWi thEnabl e D1 ( A[1: 0], S[1], D[ 7:4] ) ;

    C24DecoderWi thEnabl e D2 ( A[1: 0], S[2], D[ 11: 8]) ;

    C24DecoderWi thEnabl e D3 ( A[1: 0], S[3], D[ 15: 12] );

    endmodul e

    Modules

    54

    Module Instantiation (contd)

    Example:

    Single module instantiation for five module instances

    . . .

    C24DecoderWi thEnabl e DE ( A[ 3:2] , E, S),D0 (A[1: 0], S_n[0] , D[3: 0]),D1 (A[1: 0], S_n[1] , D[7: 4]),

    D2 (A[1: 0], S_n[2] , D[11:8]) ,D3 (A[1: 0], S_n[3] , D[15:12] );

    . . .

    Modules

  • 7/29/2019 Verilog Tut

    10/21

    55

    Connections

    Position association C24DecoderWithEnable DE (A[3:2], E, S);

    Name association C24DecoderWithEnableDE (.E(E), .A(A[3:2]), .D(S));

    . . .

    C24DecoderWi thEnable DE (. E (E), .A ( A[3:2]) . D (S)) ;/ / Note order i n li st no l onger i mport ant/ / ( E and A i nterchanged) ./ / A = A[3:2] , E =E, D = S. . .

    . . .

    C24DecoderWi thEnabl e DE (A[3: 2], E, S);/ / A = A[3:2] , E =E, S =S. . .

    Modules

    56

    Connections (contd)

    Empty Port Connections

    . . .

    / / E i s at hi gh i mpedance stat e (z)

    C24DecoderWi thEnabl e DE (A[3: 2], , S);/ / Outputs S[3: 0] are unused

    C24DecoderWi thEnabl e DE (A[3: 2], E,) ;

    Modules

    57

    Array of Instances

    { , } is concatenate

    Example

    modul e add_arr ay (A, B, CI N, S, COUT) ;

    i nput [7:0] A, B ;i nput CI N ;output [7: 0] S ;output COUT ;

    wi re [7:1] carry;

    f ull _add FA[7: 0] ( A, B, {carry, CI N},S, {COUT, carr y});/ / f ul l _add is a modul e

    endmodul e

    Modules

    58

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments

    Timing Controls and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

    59

    Procedures and Assignments

    Verilog procedures

    initial and always statements

    tasks

    functions

    Sequential block: a group of statementsthat appear between a begin and an end

    executed sequentially

    considered as a statement can be nested

    Procedures execute concurrently with other procedures

    Assignment statements

    continuous assignments: appear outside procedures

    procedural assignments: appear inside procedures

    Procedures

    60

    Assignments

    Continuous assignment

    Procedural assignment

    modul e hol i day_1(sat , sun, weekend);

    i nput s at, sun; output weekend;

    assi gn weekend = sat | sun; / / outsi de a procedure

    endmodul e

    modul e hol i day_2(sat , sun, weekend);

    i nput sat , sun; out put weekend; r eg weekend;

    al ways #1 weekend = sat | sun; / / i nsi de a procedure

    endmodul e

    modul e assi gnments

    / / conti nuous assignments go here

    al ways begi n/ / procedural assi gnments go here

    end

    endmodul e

    Procedures

  • 7/29/2019 Verilog Tut

    11/21

    61

    Continuous Assignments

    Convenient for logical or datapath specifications

    Define bus widths

    Continuousassignment:permanently sets thevalue of sum to bea+b+carryin

    Recomputed when a,b, or carryin changes

    wi r e [ 8:0] sum;wi re [7: 0] a, b;

    wi re carryi n;

    assi gn sum= a + b + carr yin;

    Procedures

    62

    Continuous Assignment (contd)

    module ass i gnment_1( ) ;

    wi re pwr_good, pwr_on, pwr_st able; reg Ok, Fi re;

    assign pwr_st abl e =Ok & (! Fir e);

    assi gn pwr_on = 1;

    assi gn pwr_good = pwr_on & pwr_st able;i nit i al begi n Ok = 0; Fi re = 0; #1 Ok = 1; #5 Fire = 1; end

    i ni t i al begi n $moni t or( "TI ME=%0d", $ti me, " ON=", pwr_ on, " STABLE=",

    pwr_ st abl e, " OK=", Ok, " FI RE=", Fi re, " GOOD=", pwr_ good) ;

    #10 $f i nish; end

    endmodul e

    >>>

    TI ME=0 ON=1 STABLE=0 OK=0 FI RE=0 GOOD=0

    TI ME=1 ON=1 STABLE=1 OK=1 FI RE=0 GOOD=1

    TI ME=6 ON=1 STABLE=0 OK=1 FI RE=1 GOOD=0

    Procedures

    63

    Sequential Block

    Sequential block may appear in an always orinitial statement

    i ni t i a l

    begi n

    i mper ati ve stat ement s

    end

    Runs when simulation starts

    Terminates when controlreaches the end(one time sequential activity flow)

    Good for providing stimulus(testbenches); not synthesizable

    al ways

    begi n

    i mperat i ve stat ement s

    end

    Runs when simulation starts

    Restarts when controlreaches the end(cycle sequential activity flow)

    Good for modeling/specifyinghardware

    Procedures

    64

    Initial and Always

    Run until they encounter a delay

    or a wait for an event

    i ni t i al begi n#10 a = 1; b = 0;#10 a = 0; b = 1;

    end

    al ways @( posedge cl k) q = d; / / edge- sensi t i ve f f

    al ways

    begi n

    wai t ( i ) ; a = 0;

    wai t( ~i ); a = 1;

    end

    Procedures

    65

    Initial and Always (contd)

    modul e always_1; r eg Y, Clk;

    al ways // Statements i n an al ways stat ement execute repeatedly:

    begi n: my_block // Start of sequenti al bl ock.

    @( posedge Cl k) #5 Y = 1; / / At +ve edge set Y=1,

    @( posedge Cl k) #5 Y = 0; / / at t he NEXT +ve edge set Y=0.

    end / / End of sequenti al block.

    al ways #10 Clk = ~ Clk; / / We need a cl ock.

    i nit i al Y = 0; // These i nit i al statements execute

    i n i t i a l Cl k =0; / / onl y once, but f i r s t .i nit i al $moni tor( "T=%2g", $ti me," Clk=", Clk, " Y=", Y);

    i nit i al #70 $f i nish;

    endmodul e

    Procedures

    >>>>

    T= 0 Cl k=0 Y=0

    T=10 Cl k=1 Y=0

    T=15 Cl k=1 Y=1

    T=20 Cl k=0 Y=1

    T=30 Cl k=1 Y=1

    T=35 Cl k=1 Y=0

    T=40 Cl k=0 Y=0

    T=50 Cl k=1 Y=0

    T=55 Cl k=1 Y=1

    T=60 Cl k=0 Y=1

    66

    Procedural Assignment

    Inside an initial or always block:

    sum= a + b + c in;

    Just like in C: RHS evaluated and assigned to LHSbefore next statement executes

    RHS may contain wires and regs

    Two possible sources for data

    LHS must be a reg

    Primitives or cont. assignment may set wire values

    Procedures

  • 7/29/2019 Verilog Tut

    12/21

    67

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments

    Timing Control and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

    68

    Timing Control

    Statements within a sequential block are executed in order

    In absence of any delay they will execute at the samesimulation time the current time stamp

    Timing control

    Delay control

    Event control

    Delay control delays an assignment by a specified amount of time

    Event control delays an assignment until a specified event occur

    Timing Control

    69

    Delay control

    Timescale compiler directive

    Intra-assignment delay vs. delayed assignment

    `t i mescale 1ns/10ps / / Unit s of ti me are ns. Round ti mes to 10 ps.

    // Al l owed uni t/ preci si on values: {1 | 10 | 100, s | ms | us | ns | ps}

    x = #1 y; / / i ntra-assi gnment del ay

    // Equivalent t o i ntra- assignment del ay.

    begin

    hold = y; / / Sample and hol d y i mmedi atel y.

    #1; / / Delay.

    x = hold; / / Assignment to x. Overall same as x =#1 y.

    end

    #1 x =y; / / delayed assi gnment

    / / Equival ent to del ayed assignment.

    begin

    #1; / / Delay.

    x = y; / / Assign y to x. Overal l same as #1 x =y.end

    Timing Control

    70

    Event control

    posedge 0 => 1, 0 => x, x => 1

    negedge 1 => 0, 1 => x, x => 0

    Timing Control

    event_control : := @event_i denti fi er | @( event_expression)

    event_expression : := expressi on | event_i denti fi er

    | posedge expressi on | negedge expressi on

    | event_expression or event_expression

    modul e s how_event ;

    reg clock;

    event event_1, event_ 2; / / Decl are t wo named events.

    al ways @(posedge clock) -> event_1; // Tri gger event_1.

    al ways @event_ 1

    begi n $di splay("Str i ke 1!!") ; - > event_2; end // Tri gger event_2.

    al ways @event_2 begi n $displ ay("Stri ke 2!! ");

    $fi nish; end // Stop on detecti on of event_2.

    al ways #10 clock = ~ cl ock; / / We need a cl ock.

    i n i t i al c l o ck = 0 ;

    endmodul e

    Stri ke 1!!Stri ke 2!!

    71

    Event control (contd)Timing Control

    module del ay_contr ol s; reg X, Y, Clk, Dummy;

    al ways #1 Dummy=! Dummy; / / Dummy cl ock, j ust f or graphi cs.

    / / Examples of del ay contr ol s:

    al ways begi n #25 X=1; #10 X=0; #5; end

    // An event contr ol:

    al ways @( posedge Cl k) Y=X; / / Wai t f or +ve cl ock edge.

    always #10 Cl k = !Clk; // The real cl ock.

    i n i t i a l begin Cl k =0;$di splay("T Cl k X Y");

    $moni tor( "%2g", $ti me,, , Cl k,, , , X, , Y);

    $dumpvars; #100 $f i ni sh; end

    endmodul e

    T Cl k X Y

    0 0 x x

    10 1 x x

    20 0 x x

    25 0 1 x

    30 1 1 1

    35 1 0 140 0 0 1

    50 1 0 0

    60 0 0 0

    65 0 1 0

    70 1 1 1

    75 1 0 1

    80 0 0 1

    90 1 0 0

    72

    Data Slip Problem

    modul e data_sl i p_1 (); reg Cl k, D, Q1, Q2;

    /************* bad sequenti al l ogi c bel ow ***************/

    al ways @( posedge Cl k) Q1 = D;

    al ways @( posedge Clk) Q2 =Q1; / / Data sl i ps here!

    /************* bad sequenti al l ogi c above ***************/

    i nit i al begi n Cl k = 0; D = 1; end al ways #50 Cl k = ~Cl k;

    i nit i al begi n $di splay("t Cl k D Q1 Q2");

    $moni tor( "%3g", $ti me,, Cl k,, , , D, , Q1,, , Q2); endi nit i al #400 $fi nish; / / Run for 8 cycl es.

    i nit i al $dumpvars;

    endmodul e

    t Clk D Q1 Q2

    0 0 1 x x

    50 1 1 1 1

    100 0 1 1 1

    150 1 1 1 1

    200 0 1 1 1

    250 1 1 1 1

    300 0 1 1 1350 1 1 1 1

    al ways @( posedge Cl k) Q1 = #1 D; / / The del ays i n the assgn.

    al ways @(posedge Clk) Q2 = #1 Q1;/ / f i x the data sl i p.

    t Clk D Q1 Q2

    0 0 1 x x

    50 1 1 x x

    51 1 1 1 x

    100 0 1 1 x

    150 1 1 1 x

    151 1 1 1 1

    200 0 1 1 1

    250 1 1 1 1

    300 0 1 1 1

    350 1 1 1 1

    Timing Control

  • 7/29/2019 Verilog Tut

    13/21

    73

    Wait Statement

    Suspends a procedure until a condition becomes true

    there must be another concurrent procedure that alters thecondition otherwise we have an infinite hold

    modul e test _dff _wai t;

    reg D, Cl ock, Reset; dff _wai t u1(D, Q, Clock, Reset) ;

    i ni t i al begi n D=1; Cl ock=0;Reset=1' b1; #15 Reset=1' b0; #20D=0; end

    al ways #10 Cl ock = !Cl ock;

    i n i t i a l begin $di spl ay("T Cl k DQ Reset" );

    $moni tor( "%2g", $ti me,, Cl ock, , , , D, , Q, , Reset) ; #50 $fi nish;end

    endmodul e

    modul e df f _wai t( D, Q, Clock, Reset) ;

    output Q; i nput D, Cl ock, Reset; reg Q; wi re D;

    al ways @(posedge Clock) i f (Reset ! == 1) Q = D;

    al ways begin wai t ( Reset == 1) Q = 0; wai t ( Reset !== 1);end

    endmodul e

    T Cl k D Q Reset

    0 0 1 0 1

    10 1 1 0 1

    15 1 1 0 0

    20 0 1 0 0

    30 1 1 1 0

    35 1 0 1 0

    40 0 0 1 0

    Timing Control

    74

    Blocking and Nonblocking Assignments

    Fundamental problem:

    In a synchronous system, all flip-flops sample simultaneously

    In Verilog, always @(posedge clk) blocks run in someundefined sequence

    reg d1, d2, d3, d4;

    al ways @( posedge cl k) d2 = d1;

    al ways @( posedge cl k) d3 = d2;

    al ways @( posedge cl k) d4 = d3;

    reg d1, d2, d3, d4;

    al ways @( posedge cl k) d2

  • 7/29/2019 Verilog Tut

    14/21

    79

    Control Statements (contd)

    Loop statements:for, while, repeat, forever

    i nteger i ; reg [15: 0] Dbus;

    i ni t i al Dbus = 0;

    / / f o r l oop

    f or ( i = 0 ; i

  • 7/29/2019 Verilog Tut

    15/21

    85

    A Sequential Primitive

    Pr i mi t i ve df f (q, c lk , data);out put q; r eg q;i nput cl k, data;tabl e

    / / clk dat a q new- q( 01) 0 : ? : 0; / / Lat ch a 0( 01) 1 : ? : 1; / / Lat ch a 1( 0x) 1 : 1 : 1; / / Hol d when d and q bot h 1( 0x) 0 : 0 : 0; / / Hol d when d and q bot h 0( ?0) ? : ? : - ; / / Hol d when cl k f al l s? ( ??) : ? : - ; / / Hol d when cl k st abl e

    endtabl eendpri mi ti ve

    Shorthand notations:

    - * is (??) - r is (01) - f is (10)

    - p is (01), (0x), or (x1) - n is (10), (1x), (x0)

    Gate level modeling

    86

    Switch-level Primitives (FIO)

    Verilog also provides mechanisms for modeling CMOS transistorsthat behave like switches

    A more detailed modeling scheme that can catch some additional

    electrical problems when transistors are used in this way Now, little-used because circuits generally arent built this way

    More seriously, model is not detailed enough tocatch many of the problems

    These circuits are usually simulated using SPICE-like simulatorsbased on nonlinear differential equation solvers

    Switch Level

    *mos where * is p, c, rn, rp, rc; pullup, pulldown;*tran+ where * is (null), r and + (null), if0, if1 with both* and + not (null)

    Gate level modeling

    87

    Delay Uses and Types

    Ignored by synthesizers;may be useful for simulation

    Uses

    Behavioral (Pre-synthesis) Timing Simulation

    Testbenches

    Gate Level (Post-synthesis and Pre-Layout)Timing Simulation

    Post-Layout Timing Simulation

    Types

    Gate Delay (Inertial Delay)

    Net Delay (Transport Delay)

    Module Path Delay

    Modeling delay

    88

    Transport and Inertial Delay

    Transport delay - pure time delay

    Inertial delay

    Multiple events cannot occur on the output in a time lessthan the delay.

    Example AND with delay = 2

    A

    B

    C

    C

    Transport Delay

    Inertial Delay

    1 ns

    Modeling delay

    89

    Gate Delay - Examples

    nd01 has a delay of 3 ns (assuming ns timescale)

    for both falling and rising delays nd02 has a triplet for the delay

    (min is 2.6 ns, typ is 3.0 ns, max is 3.4)

    nd03 has two triplets for the delay

    first triplet specifies min/typ/max for rising delay

    second triplet specifies min/typ/max for falling delay

    For primitives which can produce high-impedance outputwe can specify turn-off triplet

    Modeling delay

    nand #3. 0 nd01(c, a, b);nand #(2. 6:3. 0:3. 4) nd02(d, a, b); / / mi n:t yp: maxnand #(2. 8:3. 2:3. 4, 2. 6:2. 8:2. 9) nd03( e, a, b) ;/ / #(r i s ing, f al l i ng) del ay

    90

    Net Delay (Transport)

    Example - Continuous Assignment

    For rising output from x1 to N25, 200 + 40 = 240 ps

    Example - Implicit Continuous Assignment

    For rising output from x1 to N25, 240 ps

    Modeling delay

    #(1. 1:1. 3:1. 7) assi gn del ay_a = a; / / mi n:t yp: maxwi re #( 1.1: 1.3: 1.7) a_delay; / / mi n:t yp: maxwi re #( 1.1: 1.3: 1.7) a_del ay = a; / / mi n:t yp: max

    `t i mescal e 10ps / 1pswi re #4 N25; / / t r ansport del ayassi gn #(20, 30) N25 = ~ (x1 | x2); / / i nert i al del ay

    t i mescal e 10ps / 1pswi re #(24, 34) N25 = ~ (x1 | x2); / / i nert i al del ay onl y

  • 7/29/2019 Verilog Tut

    16/21

    91

    Module Delay

    Example: norf201 3-input nor gate from a 1.2um CMOS

    Modeling delay

    modul e nor f 201(o, a1, b1) ;output o;i nput a1, b1;

    nor( o, a1, b1);speci f y / / modul e pat hs

    (a1, b1 *> o) = (0. 179:0. 349:0. 883, 0:084: 0.169:0. 466);endspeci f y;

    endmodul e;

    92

    Outline

    Introduction

    Basics of the Verilog Language

    Operators

    Hierarchy/Modules

    Procedures and Assignments

    Timing Controls and Delay

    Control Statement

    Logic-Gate Modeling

    Modeling Delay

    Other Verilog Features

    Summary

    93

    Altering Parameters

    Use parameter

    Override the parameter in instantiation

    Or using defparam

    module Vector _And( Z, A, B);parameter CARDI NALITY = 1;i nput [ CARDI NALI TY-1:0] A, B;output [ CARDI NALITY- 1:0] Z;wi re [ CARDI NALI TY-1:0] Z =A & B;

    endmodul e

    module Four_ And_Gates( OutBus, I nBusA, I nBusB);i nput [ 3:0] I nBusA, I nBusB; output [ 3:0] OutBus;Vect or_ And #( 4) My_AND( OutBus, I nBusA, I nBusB); / / 4 AND gates

    endmodul e

    module And_Gat es(OutBus, I nBusA, I nBusB);paramet er WI DTH = 1;i nput [WI DTH- 1:0] I nBusA, I nBusB; output [WI DTH- 1:0] OutBus;Vect or_ And #( WI DTH) My_And( OutBus, I nBusA, I nBusB);

    endmodul emodule Super_Si ze; defparam And_Gates. WI DTH = 4; endmodule

    Other Verilogfeatures

    94

    Modeling FSMs Behaviorally

    There are many ways to do it:

    Define the next-state logic combinationallyand define the state-holding latches explicitly

    Define the behavior in a single always @(posedge clk)block

    Variations on these themes

    Other Verilogfeatures

    95

    FSM with Combinational Logic

    Combinational block

    must be sensitive toany change on any ofits inputs

    (Implies state-holdingelements otherwise)

    Output o is declared a regbecause it is assignedprocedurally, not becauseit holds state

    modul e FSM( o, a, b, reset) ;out put o;r eg o;i nput a, b, reset;reg [1: 0] stat e, nextState;

    al ways @( a or b or st at e)case (state)

    2 b00: begi nnextSt ate = a ? 2 b00 : 2 b01;o = a & b;

    end2b01: begin nextState = 2b10; o = 0; end

    endcase

    Other Verilogfeatures

    96

    FSM with Combinational Logic

    Latch implied bysensitivity to the clockor reset only

    modul e FSM( o, a, b, r eset ) ;

    al ways @( posedge cl k or r eset)i f ( r e set )

    st ate

  • 7/29/2019 Verilog Tut

    17/21

    97

    FSM from Combinational Logic

    This is a Mealy machinebecause the output isdirectly affected by anychange on the input

    al ways @( a or b or st ate)case (st ate)

    2 b00: begi n

    nextSt ate = a ? 2 b00 : 2 b01;o = a & b;end2b01: begin nextState = 2b10; o = 0; end

    endcase

    al ways @( posedge cl k or r eset)i f ( re set )

    st ate

  • 7/29/2019 Verilog Tut

    18/21

    103

    Simulation Behavior (contd)

    Infinite loops are possible andthe simulator does not check for them

    This runs forever: no context switch allowed,so ready can never change

    whi l e ( ~r eady)count = count + 1;

    Instead, use

    wai t ( r eady);

    Other Verilogfeatures

    104

    Simulation Behavior (contd)

    Race conditions abound in Verilog

    These can execute in either order -final value ofaundefined:

    al ways @( posedge cl k) a = 0;

    al ways @( posedge cl k) a = 1;

    Other Verilogfeatures

    105

    Compiled-Code Discrete-Event Sim.

    Most modern simulators use this approach

    Verilog program compiled into C

    Each concurrent process (e.g., continuous assignment,always block) becomes one or more C functions

    Initial and always blocks split into multiple functions, oneper segment of code between a delay, a wait, or eventcontrol (@)

    Central, dynamic event queue invokes these functions andadvances simulation time

    Other Verilogfeatures

    106

    Verilog and Logic Synthesis

    Verilog is used in two ways

    Model for discrete-event simulation

    Specification for a logic synthesis system

    Logic synthesis converts a subset of the Verilog languageinto an efficient netlist

    One of the major breakthroughs in designing logic chips inthe last 20 years

    Most chips are designed using at least some logicsynthesis

    Other Verilogfeatures

    107

    Logic Synthesis

    Takes place in two stages:

    Translation of Verilog (or VHDL) source to a netlist

    Register inference

    Optimization of the resulting netlist to improvespeed and area

    Most critical part of the process

    Algorithms very complicated and beyond the scope of thisclass

    Other Verilogfeatures

    108

    Logic Optimization

    Netlist optimization the critical enabling technology

    Takes a slow or large netlist and transforms it into onethat implements the same function more cheaply

    Typical operations Constant propagation

    Common subexpression elimination

    Function factoring

    Time-consuming operation

    Can take hours for large chips

    Other Verilogfeatures

  • 7/29/2019 Verilog Tut

    19/21

    109

    Translating Verilog into Gates

    Parts of the language easy to translate

    Structural descriptions with primitives

    oAlready a netlist

    Continuous assignment

    o Expressions turn into little datapaths

    Behavioral statements the bigger challenge

    Other Verilogfeatures

    110

    What Can Be Translated

    Structural definitions

    Everything

    Behavioral blocks

    Depends on sensitivity list

    Only when they have reasonable interpretation ascombinational logic, edge, or level-sensitive latches

    Blocks sensitive to both edges of the clock, changes onunrelated signals, changing sensitivity lists, etc. cannot besynthesized

    User-defined primitives

    Primitives defined with truth tables

    Some sequential UDPs cant be translated (not latches orflip-flops)

    Other Verilogfeatures

    111

    What Isnt Translated

    Initial blocks

    Used to set up initial state or describe finite testbench stimuli

    Dont have obvious hardware component

    Delays

    May be in the Verilog source, but are simply ignored

    A variety of other obscure language features

    In general, things heavily dependent on discrete-eventsimulation semantics

    Certain disable statements

    Pure events

    Other Verilogfeatures

    112

    Register Inference

    The main trick

    reg does not always equal latch

    Rule: Combinational if outputs always depend exclusivelyon sensitivity list

    Sequential if outputs may also depend on previous values

    Other Verilogfeatures

    113

    Register Inference

    Combinational:

    Sequential

    Sensitive to changes onall of the variables itreads

    Y is always assigned

    q only assigned when clk is 1

    r eg y;al ways @( a or b or sel )

    i f ( s el ) y = a ;else y = b;

    r eg q;al ways @( d or cl k)

    i f ( c l k) q = d;

    Other Verilogfeatures

    114

    Register Inference

    A common mistake is not completely specifying a casestatement

    This implies a latch:

    f is not assigned when{a,b}=2b11al ways @( a or b)

    case ({a, b})2 b00 : f = 0;

    2 b01 : f = 1;

    2 b10 : f = 1;

    endcase

    Other Verilogfeatures

  • 7/29/2019 Verilog Tut

    20/21

    115

    Register Inference

    The solution is to always have a default case

    f is always assigned

    al ways @( a or b)

    case ({a, b})

    2 b00: f = 0;

    2 b01: f = 1;

    2 b10: f = 1;

    defaul t : f = 0;

    endcase

    Other Verilogfeatures

    116

    Inferring Latches with Reset

    Latches and Flip-flops often have reset inputs

    Can be synchronous or asynchronous

    Asynchronous positive reset:

    al ways @( posedge cl k or posedge reset )

    i f ( r e set )

    q

  • 7/29/2019 Verilog Tut

    21/21

    121

    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 insynthesized netlist

    Blocking vs. nonblocking assignment

    Blocking behaves like normal C-like assignment

    Nonblocking updates later for modeling synchronousbehavior

    Summary

    122

    Language Uses

    Event-driven simulation

    Event queue containing things to do at particular simulatedtimes

    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

    Summary

    123

    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-likedifferential equation simulator

    Delays

    Simulating circuits with delays does not improve confidenceenough

    Hard to get timing models accurate enough

    Never sure youve simulated the worst case

    Static timing analysis has taken its place

    Summary

    124

    Compared to VHDL

    Verilog and VHDL are comparable languages

    VHDL has a slightly wider scope

    System-level modeling

    Exposes even more discrete-event machinery

    VHDL is better-behaved

    Fewer sources of nondeterminism(e.g., no shared variables ???)

    VHDL is harder to simulate quickly

    VHDL has fewer built-in facilities for hardware modeling

    VHDL is a much more verbose language

    Most examples dont fit on slides

    Summary