Behavioral Modelling

Embed Size (px)

Citation preview

  • 7/29/2019 Behavioral Modelling

    1/45

    June 1993 8-1

    Behavioral ModelingBehavioral Model Overview

    8Figure 8-0Example 8-0

    Syntax 8-0Table 8-0

    BehavioralModelingTh e language cons truct s in trodu ce d so far allow hardware to bedescribed at a relatively detailed level. Modeling a circuit with logic gatesand continuous assignments reflects quite closely the logic structure ofthe circuit being modeled; however, these constructs do not provide thepower of abstraction necessary for describing complex high level aspectsof a system. The procedural constructs described in this chapter are wellsuited to tackling problems such as describing a microprocessor or

    implementing complex timing checks.

    Th e ch ap ter st arts with a brief ove rv iew of a be hav ioral mode l to provid ea context in which the reader can understand the many types ofbe hav iora l st ateme nts in Ver ilog. Th e be havio ral co ns truct s are th endiscussed in an order that allows us to introduce them before using themin examples.

    Th e +speedup command line option can enhance the performance ofbehav iora l co de . Se e Se ct ion 24 .4 .36 fo r co mplete in fo rmat io n on th e+speedup command line option.

    8.1Behavioral Model OverviewVe rilo g beh avior al models con ta in pro ce dural sta te ments th at co ntrolthe simulation and manipulate variables o f the data types previouslydescribed. These statements are contained within procedures. Eachprocedure has an activity flow associated with it.

  • 7/29/2019 Behavioral Modelling

    2/45

    8-2 June 1993

    Behavioral ModelingBehavioral Model Overview

    The ac tivit y st arts at th e co ntr ol co nst ructs initial an d always. Eachinitial statement and each always statement starts a s eparateactivity flow. All of the activity flows are concurrent, allowing the user tomodel the inherent concurrence of hardware.

    Example 8-1 is a complete Verilog behavioral model.

    Example 8-1: Simple example of behavioral modeling

    During simulation of this model, all of the flows defined by the initialand always statements start together at simulation time zero. Theinitial statements execute once, and the always statements executerepetitively.

    In this model, the register variables a and b initialize to binary 1 and 0respectively at simulation time zero. The initial statement is thencomplete and does not execute again during this simulation run. Thisinitial statement contains abegin-endblo ck (al so ca lled a seq ue ntialblock ) of st ate ment s. In this begin-end block, a is initialized first,followed byb.

    The always statements also start at time zero, but the values of the

    variables do not ch an ge un til th e times sp ec ified by the de lay con trols(introduced by #) have gone by. Thus, register a inverts after 50 timeunits, and register b inverts after 100 time units. Since the alwaysstatements repeat, this model produces two square waves. Register atoggles with a period of 100 time units, and register b toggles with aperiod of 200 time units. The two always statements proceedconcurrently throughout the entire simulation run.

    module behave;

    reg [1:0]a,b;

    initial

    begin

    a = b1;

    b = b0;

    end

    always

    begin

    #50 a = ~a;

    end

    always

    begin

    #100 b = ~b;

    end

    endmodule

  • 7/29/2019 Behavioral Modelling

    3/45

    June 1993 8-3

    Behavioral ModelingProcedural Assignments

    8.2Procedural Assignment s

    As de scr ibed in Chap te r 5, Assignments , procedural assignments are forupdating reg, integer, time, and memory variables.

    Th ere is a significa nt dif fe ren ce bet ween pr oced ural assignme nt s andcontinuous assignments, as described below:

    Continuous assignments drive net variables and are evaluated andupdated whenever an input operand changes value.

    Procedural assignments update the value of register variablesunder the control of the procedural flow constructs that surroundthem.

    Th e right-h an d side of a pr oc edura l as signme nt can be an y ex pressionthat evaluates to a value. However, part-selects on the right-hand side

    must have constant indices. The left-hand side indicates the variablethat receives the assignment from the right-hand side. The left-hand sideof a procedural assignment can take one of the following forms:

    register, in teger, real, or time va riab le:An as signme nt to the na me refe ren ce of on e of th ese data types .

    bit- select of a register, in teger, rea l, or time va ria ble:An assignme nt to a sin gle bit tha t lea ve s the ot he r bits un touche d.

    p art- select of a register, in teger, rea l, or t ime va riab le:A pa rt-s elect of two or more con tiguous bits th at leav es th e re st ofthe bits untouched. For the part-select form, only constantexpressions are legal.

    memory elemen t:A single word of a memory. Note tha t bit- sel ec ts an d part-s ele ct sare illegal on memory element references.

    con ca ten a tion of a n y of th e a b ove:A co nc atena tion o f any of th e prev ious fo ur forms ca n be sp ec ified ,which ef fec tive ly partitio ns the result of the righ t-han d sideexpression and assigns the partition parts, in order, to the variousparts of the concatenation.

    Please note: Assignment to a register differs from assignment to areal, time, orinteger variable when the right-hand side evaluatesto fewer bits than the left-hand side. Assignment to a register does notsign-extend. Registers are unsigned; if you assign a register to an

    integer, real, or time variable, the variable will not sign-extend.

    Th e Ve rilog HD L con ta in s two types of proce dural ass ign men tstatements:

    blocking procedural assignment statements

    non-blocking procedural assignment statements

    Blocking and non-blocking procedural assignment statements specifydifferent procedural flow in sequential blocks.

  • 7/29/2019 Behavioral Modelling

    4/45

    8-4 June 1993

    Behavioral ModelingProcedural Assignments

    8.2.1Blocking Procedural Assignments

    A blo ck in g pro ce dural assignmen t st atement must be ex ec ute d be fo rethe execution of the statements that follow it in a sequential block(see Section 8.7.1). A blocking procedural assignment statement doesnot prevent the execution of statements that follow it in a parallel block(see Section 8.7.2).

    Syntax:

    The synt ax for a blo ck ing proce dural assignment is as fo llows :

    =

    Whe re lvalue is a data type that is valid for a procedural assignmentstatement, = is the assignment operator, and timing_control is theoptional intra-assignment delay. The timing_control delay can beeither a delay control (for example, #6) or an event control (for example,

    @(posedge clk)). The expression is the right-hand side value thesimulator assigns to the left-hand side.

    The = assignment operator used by blocking procedural assignments isalso used by procedural co ntinuous assignments and continuousassignments.

    Example 8-2 shows examples of blocking procedural assignments.

    Example 8-2: Examples of blocking procedural assignments

    8.2.2The No n-Bl ocki ng Pro c e dural Assi gnme nt

    The no n-blo ck in g proc edura l assignme nt allows you to sc hed uleassignments without blocking the procedural flow. You can use thenon-blocking procedural statement whenever you want to make severalregister assignments within the same time step without regard to orderor dependance upon each other.

    rega = 0;

    rega[3] = 1; // a bit-select

    rega[3:5] = 7; // a part-select

    mema[address] = 8hff; // assignment to a memory

    // element

    {carry, acc} = rega + regb; // a concatenation

  • 7/29/2019 Behavioral Modelling

    5/45

    June 1993 8-5

    Behavioral ModelingProcedural Assignments

    Syntax:

    Th e synt ax fo r a no n-block in g proce dural as signme nt is as fo llows:

  • 7/29/2019 Behavioral Modelling

    6/45

    8-6 June 1993

    Behavioral ModelingProcedural Assignments

    The se two st ep s are sh own in Exa mpl e 8-3.

    Example 8-3: How the simulator evaluates non-blocking procedural assignments

    At the end of the time step means that the non-blocking assignments arethe last assignments executed in a time stepwith one exception.Non-blocking assignment events can create blocking assignment events.The simul ato r proce ss es th es e bloc kin g ass ign men t ev en ts af te r th escheduled non-blocking events.

    module evaluates2(out);

    output out;

    reg a, b, c;

    initial

    begin

    a = 0 ;

    b = 1 ;

    c = 0 ;

    end

    always c = #5 ~c;

    always @(posedge c)

    begin

    a < = b ;

    b < = a ;

    end

    endmodule

    The simulatorevaluates the

    right-hand side o fthe non-blockingassignments and

    schedules theassignments of the

    new values atposedge c.

    Step 1:

    a = 0

    b = 1

    Step 2:

    At posedge c, the

    simulator updatesthe left-hand side ofeach non-blocking

    assignmentstatement.

    non-blockingassignment

    scheduledchanges at

    time 5

    a = 1

    b = 0

    assignmentvalues are:

    evaluates, schedules, andexecutes in two steps

  • 7/29/2019 Behavioral Modelling

    7/45

    June 1993 8-7

    Behavioral ModelingProcedural Assignments

    Unlike a regular event or de lay control, the non-blocking assignmentdoes not block the procedural flow. The non-blocking assignmentevaluates and schedules the assignment, but does not block theexecution of subsequent statements in a begin-end block, as shown inExample 8-4.

    Example 8-4: Non-blocking assignments do not block execution of sequential statements

    //non_block1.v

    module non_block1(out,);

    //input

    output out;

    reg a, b, c, d, e, f;

    //blocking assignments

    initial begin

    a = #10 1 ;

    b = #2 0 ;c = #4 1 ;

    end

    //non-blocking assignments

    initial begin

    d

  • 7/29/2019 Behavioral Modelling

    8/45

    8-8 June 1993

    Behavioral ModelingProcedural Assignments

    Please note: As shown in Example 8-5, the simulator evaluates andschedules assignments for the end of the current time step and canperform swapping operations with non-blocking proceduralassignments.

    Example 8-5: Non-blocking procedural assignments used for swapping operations

    //non_block1.v

    module non_block1(out,);

    //input

    output out;

    reg a, b;

    initial begin

    a = 0 ;

    b = 1 ;

    a

  • 7/29/2019 Behavioral Modelling

    9/45

    June 1993 8-9

    Behavioral ModelingProcedural Assignments

    Wh en yo u sc hed ule mult ip le non -blo cking as signmen ts to oc cur in th esame register in a particular time slot, the simulator cannot guaranteethe order in which it processes the assignmentsthe final value of theregister is indeterminate. As shown in Example 8-6, the value of registera is not known until the end of time step 4.

    Example 8-6: Multiple non-blocking assignments made in a sing le time step

    If the simulator executes two procedural blocks concurrently, and theseprocedural blocks contain non-blocking assignment operators, the final

    va lue of th e register is in det er mina te . For ex ample, in Exa mple 8-7 th eva lue of re giste r a is indeterminate.

    Example 8-7: Processing t wo procedural assignments concurrently

    module multiple2(out);

    output out;

    reg a;

    initial

    begin

    a

  • 7/29/2019 Behavioral Modelling

    10/45

    8-10 June 1993

    Behavioral ModelingProcedural Assignments

    Whe n mul tiple no n-blocking as signme nt s wit h timing controls are madeto the same register, the assignments can be made without cancellingprevious non-blocking assignments. In Example 8-8, the simulatorevaluates the value of i[0] to r1 and schedules the assignments tooccur after each time delay.

    Example 8-8: Multiple non-blocking assignments with timing controls

    r1 = 0

    r1 = 0

    r1 = 1

    r1 = 0

    r1 = 1

    r1 = 1

    module multiple;

    reg r1;

    reg [2:0] i;

    initial

    begin

    // starts at time 0 doesnt hold the block

    for (i = 0; i

  • 7/29/2019 Behavioral Modelling

    11/45

    June 1993 8-11

    Behavioral ModelingConditional Statement

    8.2.3How the Simulator Processes Blocking and Non-BlockingProcedural Assignments

    For each time slot during simulation, blocking and non-blockingprocedural assignments are processed in the following way:

    1. Evaluate the right-hand side of all assignment statements in thecurrent time slot.

    2. Execute all blocking procedural assignments and non-blockingprocedural assignments that have no timing controls. At the sametime, non-blocking procedural assignments with timing controlsare set aside for processing.

    3. Check for procedures that have timing controls and execute iftiming control is set for the current time unit.

    4. Advance the simulation clock.

    8.3Conditional Statement

    Th e co nd ition al st atement (or if-else statement) is used to make adecision as to whether a statement is executed or not. Formally, thesyntax is as follows:

    Syntax 8-1: Syntax ofifstatement

    Th e is ev aluated ; if it is true (that is, h as a non -zer o k no wnva lue), th e first st atement exec utes. If it is fa lse (has a ze ro va lue or theva lue is x or z), the first statement does not execute. If there is an else

    statement and is false, the else statement executes.

    ::= if ( )

    ||= if ( ) else

    ::=

    ||= ;

  • 7/29/2019 Behavioral Modelling

    12/45

    8-12 June 1993

    Behavioral ModelingConditional Statement

    Since the numeric value of the if expression is tested for being zero,certain shortcuts are possible. For example, the following twostatements express the same logic:

    if (expression)

    if (expression != 0)

    Because the else part of an if-else is optional, there can be confusionwhen an else is omitted from a nested if sequence. This is resolved byalways associating the else with the closest previous if that lacks an

    else. In Example 8-9, the else goes with the inner if, as we haveshown by indentation.

    Example 8-9: Association ofelse in nestedif

    If that association is not what you want, use a begin-end block statement

    to force the proper association, as shown in Example 8-10.

    Example 8-10: Forcing correct association ofelse withif

    if (index > 0)

    if (rega > regb)

    result = rega;

    else // else applies to preceding if

    result = regb;

    if (index > 0)

    begin

    if (rega > regb)

    result = rega;

    end

    else

    result = regb;

  • 7/29/2019 Behavioral Modelling

    13/45

    June 1993 8-13

    Behavioral ModelingConditional Statement

    Begin-end blocks left out inadvertently can change the logic behaviorbe ing ex press ed , as sho wn in Ex ample 8-1 1.

    Example 8-11: Erroneous association ofelse with if

    Th e in de nta tion in Ex ampl e 8-11 sh ow s un eq uivoc ally what you want ,but the co mpi ler doe s not get th e messa ge an d ass oc iates the else withthe innerif. This kind of bug can be very hard to find. (One way to findthis kind of bug is to use the $list system task, which indentsaccording to the logic of the description).

    Notice that in Example 8-12, there is a semicolon afterresult = rega.Th is is be ca use a follows the if, and a semicolon is anessential part of the syntax of a .

    Example 8-12: Use o f semicolon inifstatement

    if (index > 0)

    for (scani = 0; scani < index; scani = scani + 1)

    if (memory[scani] > 0)

    begin

    $display(...);

    memory[scani] = 0;

    end

    else /* WRONG */

    $display(error - index is zero);

    if (rega > regb)

    result = rega;

    else

    result = regb;

  • 7/29/2019 Behavioral Modelling

    14/45

    8-14 June 1993

    Behavioral ModelingConditional Statement

    8.3.1if-else-if Construct

    The fo llowing co ns truct io n oc curs so ofte n th at it is worth a briefseparate discussion.

    Syntax 8-2: Syntax ofif-else-ifconstruct

    This se quenc e of ifs (known as an if-else-if construct) is the mostgeneral way of writing a multi-way decision. The expressions areevaluated in order; if any expression is true, the statement associatedwith it is exe cu te d, and this te rmi nat es th e whol e ch ain. Each sta te mentis either a single statement or a block of statements.

    The last else part of the if-else-if construct handles the none of theabove or default case where none of the other conditions was satisfied.Sometimes there is no explicit action for the default; in that case, thetrailing else can be omitted or it can be used for error checking to catchan impossible co ndition.

    if ()

    else if ()

    else if ()

    else

  • 7/29/2019 Behavioral Modelling

    15/45

    June 1993 8-15

    Behavioral ModelingConditional Statement

    8.3.2Example

    Th e module fr agment of Ex ampl e 8-13 uses th e if-else statement totest the variable index to decide whether one of three modify_segnregisters must be added to the memory address, and which increment isto be added to the index register. The first ten lines declare the registersand parameters.

    Example 8-13: Use of if-else-ifconstruct

    // Declare registers and parameters

    reg [31:0] instruction, segment_area[255:0];

    reg [7:0] index;

    reg [5:0] modify_seg1,

    modify_seg2,

    modify_seg3;

    parameter

    segment1 = 0, inc_seg1 = 1,

    segment2 = 20, inc_seg2 = 2,

    segment3 = 64, inc_seg3 = 4,

    data = 128;

    // Test the index variable

    if (index < segment2)

    begin

    instruction = segment_area [index + modify_seg1];

    index = index + inc_seg1;

    endelse if (index < segment3)

    begin

    instruction = segment_area [index + modify_seg2];

    index = index + inc_seg2;

    end

    else if (index < data)

    begin

    instruction = segment_area [index + modify_seg3];

    index = index + inc_seg3;

    end

    else

    instruction = segment_area [index];

  • 7/29/2019 Behavioral Modelling

    16/45

    8-16 June 1993

    Behavioral ModelingCase Statement

    8.4Case Statement

    The case statement is a special multi-way decision statement that testswheth er an ex pre ss ion mat ch es on e of a number of oth er exp re ss ion s,and branches accordingly. The case statement is useful for describing,for example, the deco ding of a microprocessor instruction. The casestatement has the following syntax:

    Syntax 8-3: Syntax forcase statement

    The def ault st ate ment is op tiona l. Use of mult ip le de fa ult st ate ments inone case statement is illegal syntax.

    ::= case ( ) + endcase

    ||= casez ( ) + endcase

    ||= casex ( ) + endcase

    ::= * : ||= default :

    ||= default

  • 7/29/2019 Behavioral Modelling

    17/45

    June 1993 8-17

    Behavioral ModelingCase Statement

    A simp le exa mple of the us e of th e case statement is the decoding ofregister rega to produce a value for result, as follows:

    Example 8-14: Use of thecase statement

    Th e ca se ex pre ss ion s are ev aluated an d co mpared in the ex ac t or de r inwhich th ey are give n. Durin g th e lin ear se arch, if on e of th e ca se itemexpressions matches the expression in parentheses, then the statementassociated with that case item is executed. If all comparisons fail, andthe default item is given, then the default item statement is exe cuted. Ifthe default statement is not given, and all of the comparisons fail, thennone of the case item statements is executed.

    Apart fr om syn tax, the case statement differs from the multi-wayif-else-if construct in two important ways:

    1. The conditional expressions in the if-else-if construct are moregeneral than comparing one expression with several others, as inth e case statement.

    2. The case statement provides a definitive result when there are xan d z values in an expression.

    In a case comparison, the comparison only succeeds when each bitmatches exactly with respect to the values 0, 1, x, and z. As aconsequence, care is needed in specifying the expressions in the casestatement. The bit length of all the expressions must be equal so thatexact bit-wise matching can be performed. The length of all the case itemexpressions, as well as the controlling expression in the parentheses,will be mad e eq ual to the length of th e longest ex press ion.

    reg [15:0] rega;

    reg [9:0] result;

    case (rega)

    16d0: result = 10b0111111111;

    16d1: result = 10b1011111111;

    16d2: result = 10b1101111111;

    16d3: result = 10b1110111111;

    16d4: result = 10b1111011111;

    16d5: result = 10b1111101111;16d6: result = 10b1111110111;

    16d7: result = 10b1111111011;

    16d8: result = 10b1111111101;

    16d9: result = 10b1111111110;

    default result = bx;

    endcase

  • 7/29/2019 Behavioral Modelling

    18/45

    8-18 June 1993

    Behavioral ModelingCase Statement

    The most co mmo n mis ta ke made he re is to sp eci fy bx or bz instead of

    nbx or nbz, where n is the bit length of the expression in parentheses.The de fa ult len gth of x an d z is the word size of the host machine,usually 32 bits.

    The re ason fo r prov idin g a case comparison that handles the x an d zvalue s is th at it provides a mecha nis m for de tec ting suc h value s an dreducing the pessimism that can be generated by their presence.Example 8-15 illustrates the use of acase statement to properly handle

    x and z values.

    Example 8-15: Detectingxand z values with thecase statement

    Example 8-15 contains a robustcase statement used to trap x and z

    value s. Notice tha t if select[1] is 0 an d flaga is 0, then no matterwhat the va lue of select[2] is, the result is set to 0. The first, second,and third case items cause this assignment.

    Example 8-16 shows another way to use a case statement to detect xand z values.

    Example 8-16: Another example of detectingxandz withcase

    case (select[1:2])

    2b00: result = 0;

    2b01: result = flaga;

    2b0x,

    2b0z: result = flaga ? b x : 0 ;

    2b10: result = flagb;

    2bx0,

    2bz0: result = flagb ? bx : 0;

    default: result = bx;

    endcase

    case(sig)

    1bz:

    $display(signal is floating);

    1bx:

    $display(signal is unknown);default:

    $display(signal is %b, sig);

    endcase

  • 7/29/2019 Behavioral Modelling

    19/45

    June 1993 8-19

    Behavioral ModelingCase Statement

    8.4.1Case Statement with Dont-Cares

    Two oth er types of case statements are provided to allow handling ofdo nt-care conditions in the case comparisons. One of these treatshigh-impedance values (z) as don t-cares, and the other treats bothhigh-impedance and unknown (x) values as dont-cares.

    Th ese case statements are used in the same way as the traditional casestatement, but they begin with new keywordscasez an d casex,respectively.

    Do nt-care values (z values forcasez, z an d x values forcasex), in anybit of eithe r the cas e ex pre ss ion or the ca se items, are tr ea ted asdo nt-care conditions during the comparison, and that bit position is notconsidered.

    Note that allowing don t-cares in the case items means that you can

    dynamically control which bits of the case ex pression are comparedduring simulation.

    Th e syn ta x of lite ral numbers allo ws th e use of th e ques tio n mark (?) inplace of z in these case statements. This provides a convenient formatfor specification of dont-care bits in case statements.

    Example 8-17 is an example of the casez statement. It demonstrates aninstruction decode, where values of the most significant bits select whichtask should be called. If the most significant bit of ir is a 1, then thetask instruction1 is called, regardless of the values of the other bitsof ir.

    Example 8-17: Using thecasez statement

    Example 8-18 is an example of the casex statement. It demonstrates anextreme case of how don t-care conditions can be dynamically controlledduring simulation. In this case, if r = 8b01100110 , then the taskstat2 is called.

    reg [7:0] ir;

    casez (ir)

    8b1???????: instruction1(ir);

    8b01??????: instruction2(ir);

    8b00010???: instruction3(ir);

    8b000001??: instruction4(ir);

    endcase

  • 7/29/2019 Behavioral Modelling

    20/45

    8-20 June 1993

    Behavioral ModelingLooping Statements

    Example 8-18: Using thecasexstatement

    8.5Looping Stateme nts

    The re are fo ur types of lo op ing st atement s. Th ey pro vide a means ofcontrolling the execution of a statement zero, one, or more times.

    forever continuously executes a statement.

    repeat executes a statement a fixed number of times.

    while executes a statement until an expression becomes false. If

    the expression starts out false, the statement is not executed atall.

    for controls execution of its associated statement(s) by athree-step process, as fo llows:

    1. executes an assignment normally used to initialize ava riable th at co nt rols the number of loop s exe cu te d

    2. evaluates an expressionif the result is zero, the forloop exits, and if it is not zero, the for loop executesits associated statement(s) and then performs step 3

    3. executes an assignment normally used to modify theva lue of th e lo op-co ntr ol va riable, th en re pe ats ste p 2

    reg [7:0] r, mask;

    mask = 8bx0x0x0x0;

    casex (r ^ mask)

    8b001100xx: stat1;

    8b1100xx00: stat2;

    8b00xx0011: stat3;

    8bxx001100: stat4;

    endcase

  • 7/29/2019 Behavioral Modelling

    21/45

    June 1993 8-21

    Behavioral ModelingLooping Statements

    Th e fo llowing are the synta x rule s fo r th e loop ing sta te men ts :

    Syntax 8-4: Syntax for the looping statements

    Th e re st of this se ct ion prese nt s examp les fo r th ree of th e lo opi ngstatements.

    8.5.1forever Loop

    Th e forever loop should only be used in conjunction with the timingcontrols or the disable statement; therefore, this example is presented inSection 8.6.3.

    ::= forever ||=forever

    begin+

    end

    ::= repeat ( ) ||=repeat ( )

    begin+

    end

    ::= while ( ) ||=while ( )begin

    +end

    ::= for ( ; ; )

    ||=for ( ; ; )begin

    +end

  • 7/29/2019 Behavioral Modelling

    22/45

    8-22 June 1993

    Behavioral ModelingLooping Statements

    8.5.2repeat Loop Example

    In the following example of a repeat loop, add and shift operatorsimplement a multiplier.

    Example 8-19: Use of therepeat loop to implement a multiplier

    parameter size = 8, longsize = 16;

    reg [size:1] opa, opb;

    reg [longsize:1] result;

    begin :mult

    reg [longsize:1] shift_opa, shift_opb;

    shift_opa = opa;

    shift_opb = opb;

    result = 0;

    repeat (size)

    begin

    if (shift_opb[1])

    result = result + shift_opa;

    shift_opa = shift_opa > 1;

    end

    end

  • 7/29/2019 Behavioral Modelling

    23/45

    June 1993 8-23

    Behavioral ModelingLooping Statements

    8.5.3while Loop Example

    An ex ample of the while loop follows. It counts up the number of logic1 values in rega.

    Example 8-20: Use of thewhile loop to count logic values

    8.5.4for Loop Examples

    Th e for loop construct accomplishes the same results as the followingpseudocode that is based on the while loop:

    Example 8-21: Pseudocode equivalent of afor loop

    Th e for loop implements the logic in the preceding 8 lines while usingonly two lines, as shown in the pseudocode in Example 8-22.

    begin :count1s

    reg [7:0] tempreg;

    count = 0;

    tempreg = rega;

    while(tempreg)

    begin

    if (tempreg[0]) count = count + 1;

    tempreg = tempreg >> 1;

    end

    end

    begin

    initial_assignment;

    while (condition)

    begin

    statement

    step_assignment;

    end

    end

  • 7/29/2019 Behavioral Modelling

    24/45

    8-24 June 1993

    Behavioral ModelingLooping Statements

    Example 8-22: Pseudocode for afor loop

    Example 8-23 uses a for loop to initialize a memory.

    Example 8-23: Use of thefor loop to initialize a memory

    Here is another example of a for loop statement. It is the samemultiplier that was described in Example 8-19 using the repeat loop.

    Example 8-24: Use of thefor loop to implement a multiplier

    Note that the for loop statement can be more general than the normalarithmetic progression of an index variable, as in Example 8-25. This isanother way of counting the number of logic 1 values in rega (seeExample 8-20).

    for (initial_assignment; condition; step_assignment)

    statement

    begin :init_mem

    reg [7:0] tempi;

    for (tempi = 0; tempi < memsize; tempi = tempi + 1)

    memory[tempi] = 0;

    end

    parameter size = 8, longsize = 16;

    reg [size:1] opa, opb;

    reg [longsize:1] result;

    begin :mult

    integer bindex;

    result = 0;

    for (bindex = 1; bindex

  • 7/29/2019 Behavioral Modelling

    25/45

    June 1993 8-25

    Behavioral ModelingProcedural Timing Controls

    Example 8-25: Use of thefor loop to count logic values

    8.6

    Proce dural T iming ControlsTh e Ve rilog language pro vide s two types of ex plicit timi ng con trol ov erwhen in simulation time proced ural sta te men ts are to oc cur. The firsttype is a delay control in which an expression specifies the time durationbetween in itia lly enc ou nte ring th e st ate ment an d when th e sta te mentactually executes. The delay expression can be a dynamic function of thestate of the circuit, but is usually a simple number that separatesstatement executions in time. The delay control is an important featurewhen sp eci fyin g stimul us wavef or m des cr iptio ns . It is de sc ribed inSections 8.6.1, 8.6.2, and 8.6.7.

    Th e se co nd type of timi ng con trol is th e even t ex press io n, wh ich all ows

    statement execution to wait for the occurrence of some simulation eventoccurring in a procedure executing concurrently with this procedure. Asimulation event can be a change of value on a net or register (an implicitevent), or the occurrence of an explicitly named event that is triggeredfrom other procedures (an explicit event). Most often, an event control isa positive or negative edge on a clock signal. Sections 8.6.3 through8.6.7 discuss event control.

    In Verilog, actions are scheduled in the future through the use of delaycontrols. A general principle of the Verilog language is that where youdo not see a timing control, simulation time does not advance if youspecify no timing delays, the simulation completes at time zero. Toschedule activity for the future, use one of the following methods oftiming control:

    a delay control, which is introduced by the number symbol (#)

    an event control, which is introduced by the at symbol (@)

    the wait statement, which operates like a combination of theevent control and the while loop

    Th e ne xt sec tions disc uss th ese th ree meth ods .

    begin :count1s

    reg [7:0] tempreg;count = 0;

    for (tempreg = rega; tempreg; tempreg = tempreg >

    > 1)

    if (tempreg[0]) count = count + 1;

    end

  • 7/29/2019 Behavioral Modelling

    26/45

    8-26 June 1993

    Behavioral ModelingProcedural Timing Controls

    8.6.1Delay Control

    The ex ec ution of a pro ce dural sta te ment ca n be de lay- co ntr ol led byusing the following syntax:

    Syntax 8-5: Syntax for delay_control

    The follow ing ex ampl e de lays th e ex ecu tion of th e as signme nt by 10 timeunits:

    #10 rega = regb;

    The ne xt th ree examp les pro vide an exp re ss ion fol lo wing the numbersign (#). Execution of the assignment delays by the amount of simulationtime specified by the value of the expression.

    #d rega = regb; // d is defined as a parameter

    #((d+e)/2) rega = regb;// delay is the average of d and e

    #regr regr = regr + 1; // delay is the value in regr

    8.6.2Zero-Delay cont rol

    A spe cial ca se of th e delay co ntr ol is th e ze ro- de lay co nt rol , as in th efollowing example:

    forever

    #0 a = ~a;

    ::=

    ::= #

    ||= #

    ||= # ( )

  • 7/29/2019 Behavioral Modelling

    27/45

    June 1993 8-27

    Behavioral ModelingProcedural Timing Controls

    Th is type of de lay co ntr ol ha s th e eff ec t of movin g th e ass ignmentstatement to the end of the list of statements to be evaluated at thecurrent simulation time unit. Note that if there are several such delaycontrols encountered at the same simulation time, the order ofevaluation of the statements which they control cannot be predicted.

    8.6.3Event Control

    Th e ex ec ution of a proced ural sta te ment ca n be syn ch ron ized wit h ava lue cha nge on a net or re giste r, or the oc curre nc e of a dec lared ev ent ,by us in g th e follo wing ev ent cont ro l syn ta x:

    Syntax 8-6: Syntax forevent_control

    Va lue ch anges on ne ts an d regis ter s ca n be use d as eve nt s to trigger th eexecution of a statement. This is known as detecting an implicit event.See item 1 in Example 8-26 for a syntax example of a wait for an implicitevent. Verilog syntax also allows you to detect change based on thedirection of the changethat is, toward the value 1 ( posedge) or towardthe value 0 (negedge). The behavior of posedge an d negedge fo runknown expression values is as follows:

    a negedge is detected on the transition from 1 to unknown andfrom unknown to 0

    a posedge is detected on the transition from 0 to unknown andfrom unknown to 1

    ::=

    ::= @

    ||= @ ( )

    ::=

    ||= posedge

    ||= negedge

    ||= *

    is an expression that resolvesto a one bit value.

  • 7/29/2019 Behavioral Modelling

    28/45

    8-28 June 1993

    Behavioral ModelingProcedural Timing Controls

    Items 2 and 3 in Example 8-26 show illustrations of edge-controlledstatements.

    Example 8-26: Event controlled statements

    8.6.4Named Events

    Ver ilo g also pro vi de s syn ta x to name an ev en t an d th en to tr igg er th eoccurrence of that event. A model can then use an event expression towait fo r the trigge ring of th is ex plicit eve nt . Named ev ent s ca n be madeto occur from a procedure. This allows control over the enabling ofmultiple actions in other procedures. Named events and event controlgive a powerful and efficient means of describing the communicationbet ween, an d sync hro nizatio n of , two or more co ncu rrent ly activeprocesses. A basic example of this is a small waveform clock generatorthat synchronizes control of a synchronous circuit by signalling the

    occurrence of an explicit event periodically while the circuit waits for theevent to occur.

    An ev ent name mus t be de clare d ex plicitly be for e it is us ed . T he fol lo wingis the syntax for declaring events.

    Syntax 8-7: Syntax for event_declaration

    @r rega = regb; // controlled by any value changes

    // in the register r

    @(posedge clock) rega = regb; // controlled by positive

    // edge on clock

    forever @(negedge clock) rega = regb; // controlled by

    // negative edge

    ::= event * ;

    ::= - the name of an explicit event

  • 7/29/2019 Behavioral Modelling

    29/45

    June 1993 8-29

    Behavioral ModelingProcedural Timing Controls

    Note that an event does not hold any data. The following are thecharacteristics of a Verilog event:

    it can be made to occur at any particular time

    it has no time duration

    its occurrence can be recognized by using the syntax described in Section 8.6.3

    Th e po wer of th e explicit ev en t is tha t it ca n re pre se nt an y gener alhappening. For example, it can represent a positive edge of a clocksignal, or it can represent a microprocessor transferring data down aserial communications channel. A declared event is made to occur by theactivation of an event-triggering statement of the following syntax:

    -> ;

    An ev ent -con tro lled sta te ment (fo r ex ample, @trig rega = regb;)causes simulation of its containing procedure to wait until some otherprocedure executes the appropriate event-triggering statement (forexample, ->trig;).

    8.6.5Event OR Construct

    Th e OR in g of an y numbe r of ev en ts ca n be ex press ed su ch th at th eoccurrence of any one will trigger the execution of the statement. Thenext two examples show the ORing of two and three events respectively.

    @(trig or enable) rega = regb;// controlled by trig or enable

    @(posedge clock_a or posedge clock_b or trig) rega = regb;

    8.6.6Level-Sensitive Event Control

    Th e ex ec ution of a st ate ment can also be delayed un til a co ndition

    be com es true. Th is is acc omplish ed us ing th e wait statement, which isa special form of event control. The nature of the wait statement islevel-sensitive, as opposed to basic event control (specified by the @character), which is edge-sensitive. The wait statement checks a

  • 7/29/2019 Behavioral Modelling

    30/45

    8-30 June 1993

    Behavioral ModelingProcedural Timing Controls

    condition, and, if it is false, causes the procedure to pause until thatcondition becomes true befo re continuing. The wait statement has thefollowing form:

    wait(condition_expression) statement

    Example 8-27 shows the use of the wait statement to accomplishlevel-sensitive event control.

    Example 8-27: Use ofwait statement

    If the value of enable is one when the block is entered, the waitstatement delays the evaluation of the next statement (#10 a = b;) untilthe value of enable changes to zero. Ifenable is already zero when thebegin-en d blo ck is en te red , the n th e nex t st atement is ev aluatedimmediately and no delay occurs.

    8.6.7

    Intra-Assignment Timing ControlsThe de lay and ev ent co ntr ol co nst ruct s prev iousl y de sc ribed prec ede astatement and delay its execution. The intra-assignment delay and eventcontrols are contained within an assignment statement and modify theflow of activity in a slightly different way.

    Encountering an intra-assignment delay or event control delays theassignment just as a regular delay or event control does, but theright-hand side expression is evaluated before the delay, instead of afterthe delay. This allows data swap and data shift operations to bedescribed without the need for temporary variables. This sectiondescribes the purpose o f intra-assignment timing controls and the

    repeat timing control that can be used in intra-assignment delays.

    begin

    wait(!enable) #10 a = b;

    #10 c = d ;

    end

  • 7/29/2019 Behavioral Modelling

    31/45

    June 1993 8-31

    Behavioral ModelingProcedural Timing Controls

    Figure 8-1 illustrates the philosophy of intra-assignment timing controlsby sh ow ing the co de tha t cou ld acc omplish the sa me timing ef fe ctwit hout us ing intra -as signmen t.

    Figure 8-1: Equivalents to intra-assignment timing controls

    Th e ne xt three examp les use the fork-join behavioral construct. Allstatements between the keywords fork an d join execute concurrently.Section 8.7.2 describes this construct in more detail.

    Th e follo wing ex ampl e sh ow s a race co ndition th at cou ld be prev ent ed byusing intra-assignment timing control:

    fork

    # 5 a = b ;

    # 5 b = a ;

    join

    Intra-assignment timing control

    a = #5 b ;begin

    temp = b;

    #5 a = temp;

    end

    a = @(posedge clk) b;

    begin

    temp = b;

    @(posedge clk) a = temp;end

    a = repeat(3)@(posedge clk) b;

    begin

    temp = b;

    @(posedge clk;

    @(posedge clk;

    @(posedge clk) a = temp;

    end

    with intra-assignment construct without intra-assignment construct

  • 7/29/2019 Behavioral Modelling

    32/45

    8-32 June 1993

    Behavioral ModelingProcedural Timing Controls

    The cod e in th e prev iou s ex ampl e sa mpl es th e va lues of bo th a an d b atthe same simulation time, thereby creating a race condition. Theintra-assignment form of timing control used in the following exampleprevents this race condition:

    fork // data swap

    a = # 5 b ;

    b = # 5 a ;

    join

    Intra-assignment timing control works because the intra-assignmentdelay c auses the values ofa an d b to be evaluated before the delay, andthe assignments to be made after the delay. Verilog-XL and other toolsthat implement intra-assignment timing control use temporary storage

    in evaluating each expression on the right-hand side.Intra-assignment waiting for events is also effective. In the examplebelow , th e right-han d-side ex press io ns are evaluated when th eassignment statements are encountered, but the assignments aredelayed until the rising edge of the clock signal.

    fork // data shift

    a = @(posedge clk) b;

    b = @(posedge clk) c;

    join

    The repeat even t co n t r ol

    The repeat event control specifies an intra-assignment delay o f aspecified number of occurrences of an event. This construct isconvenient when events must be synchronized with counts of clocksignals.

  • 7/29/2019 Behavioral Modelling

    33/45

    June 1993 8-33

    Behavioral ModelingProcedural Timing Controls

    Syntax 8-8 presents the repeat event control syntax:

    Syntax 8-8: Syntax of therepeat event control

    Th e ev en t ex press ion must res ol ve to a one bit value . A sca lar eve ntexpression is an expression which resolves to a one bit value.

    Th e fo llowing is an exa mple of a repeat event control as theintra-assignment delay of a non-blocking assignment:

    a

  • 7/29/2019 Behavioral Modelling

    34/45

    8-34 June 1993

    Behavioral ModelingProcedural Timing Controls

    Figure 8-2 illustrates the activities that result from this repeat eventcontrol:

    Figure 8-2: Repeatevent control utilizing a clock edge

    In this example, the value of data is evaluated when the assignment isencountered. After five occurrences of posedge clk, a is assigned thepreviously evaluated value of data.

    The fo llowing is an ex ample of a repeat event control as theintra-assignment delay of a procedural assignment:

    a = repeat(num)@(clk)data;

    In this example, the value of data is evaluated when the assignment isencountered. After the number of transitions o f clk equals the value of

    num, a is assigned the previously evaluated value of data.

    The fo llowin g is an exa mpl e of a repeat event control with expressionscontaining operations to specify both the number of event occurrencesand the event that is counted:

    a

  • 7/29/2019 Behavioral Modelling

    35/45

    June 1993 8-35

    Behavioral ModelingBlock Statements

    8.7Block Statem ents

    Th e bloc k sta te ments are a mean s of group in g two or more sta te mentstogether so that they act syntactically like a single statement. We havealready introduced and used the sequential block statement which isdelimited by the keywords begin and end. Section 8.7.1 discussessequential blocks in more detail.

    A sec on d type of bloc k, de limite d by the keywords fork and join, isused for executing statements in parallel. A fork-join block is knownas a parallel block, and enables procedures to execute concurrentlythrough time. Section 8.7.2 discusses parallel blocks.

    8.7.1

    Sequential BlocksA seq ue nt ial block ha s th e fo llowing cha racte rist ics :

    statements execute in sequence, one after another

    delay values for each statement are relative to the simulation timeof the execution of the previous statement

    control passes out of the block after the last statement executes

    Th e fo llowing is th e fo rmal synta x fo r a se quent ial block:

    Syntax 8-9: Syntax for the sequential block

    ::= begin * end||= begin :

    **

    end

    ::=

    ::=

    ||=

    ||=

    ||=

    ||= ||=

  • 7/29/2019 Behavioral Modelling

    36/45

    8-36 June 1993

    Behavioral ModelingBlock Statements

    A seq ue nt ial bloc k en ables th e fo llowin g two ass ignment s to ha ve adeterministic result:

    begin

    areg = breg;

    creg = areg; // creg becomes the value of breg

    end

    Here the first assignment is performed and areg is updated beforecontrol passes to the second assignment.

    Delay control can be used in a sequential block to separate the twoassignments in time.

    beginareg = breg;

    #10 creg = areg; // this gives a delay of 10 time

    end // units between assignments

    Example 8-28 shows how the combination of the sequential block anddelay control can be used to specify a time-sequenced waveform.

    Example 8-28: A waveform controlled by sequential delay

    parameter d = 50; // d declared as a parameter

    reg [ 7:0] r; // a nd r declared a s an 8-bit r egister

    begin // a waveform controlled by sequential

    // delay

    # d r = h35;

    # d r = hE2;

    # d r = h00;

    # d r = hF7;

    #d -> end_wave;// trigger the event called end_wave

    end

  • 7/29/2019 Behavioral Modelling

    37/45

    June 1993 8-37

    Behavioral ModelingBlock Statements

    Example 8-29 shows three examples of sequential blocks.

    Example 8-29: Three examples of sequential blocks

    8.7.2Parallel Blocks

    A parallel bloc k ha s th e fol lo wing ch aract er ist ics: statements execute concurrently

    delay values for each statement are relative to the simulation timewhe n co nt rol en ter s th e block

    delay control is used to provide time-ordering for assignments

    control passes out of the block when the last time-orderedstatement executes or a disable statement executes

    begin@trig r = 1;

    #250 r = 0; // a 250 delay monostable

    end

    begin

    @(posedge clock) q = 0;

    @(posedge clock) q = 1;

    end

    begin // a waveform synchronized by the event c

    @ c r = h35;

    @ c r = hE2;

    @ c r = h00;@ c r = hF7;

    @c -> end_wave;

    end

  • 7/29/2019 Behavioral Modelling

    38/45

    8-38 June 1993

    Behavioral ModelingBlock Statements

    Syntax 8-10 gives the formal syntax for a parallel block.

    Syntax 8-10: Syntax for the parallel block

    Example 8-30 codes the waveform description shown in Example 8-28by us in g a parall el block in st ead of a se quent ial bloc k. The wavef or mproduced on the register is exactly the same for both implementations.

    Example 8-30: Use of thefork-join construct

    ::= fork * join

    ||= fork :

    *

    *

    join

    ::=

    ::=

    ||=

    ||= ||=

    ||=

    ||=

    fork

    #50 r = h35;

    #100 r = hE2;

    #150 r = h00;

    #200 r = hF7;

    #250 -> end_wave;

    join

  • 7/29/2019 Behavioral Modelling

    39/45

    June 1993 8-39

    Behavioral ModelingBlock Statements

    8.7.3Block Names

    Note that blocks can be named by adding: name_of_block after thekeywords begin or fork. The naming of blocks serves several purposes:

    It allows local variables to be declared for the block.

    It allows the block to be referenced in statements like the disablestatement (as discussed in Chapter 10,Disabling of Named Blocksand Tasks).

    In the Verilog language, all variables are staticthat is, a uniquelocation exists for all variables and leaving or entering blocks doesnot affect the values stored in them.

    Th us, bloc k na mes giv e a means of un ique ly ident if ying all variables atany simulation time. This is very important for debugging purposes,

    where it is nec es sa ry to be ab le to re fer en ce a loc al var iab le in side ablock fr om out side the bo dy of the block .

    8.7.4Start and Finish Times

    Both forms of blocks have the notion of a start and finish time. Forsequential blocks, the start time is when the first statement is executed,and the finish time is when the last statement has finished. For parallelblock s, the st art time is the same for all th e st ate ments , an d the fin is htime is when the last time-ordered statement has finished executing.Wh en blo ck s are embed de d with in ea ch ot her , t he timi ng of when a block

    starts and finishes is important. Execution does not continue to thestatement following a block until the blocks finish time has beenreachedthat is, until the block has completely finished executing.

    Moreover, the timing controls in a fork-join block do not have to begiven sequentially in time. Example 8-31 shows the statements fromExample 8-30 written in the reverse order and still producing the samewav efo rm.

    Example 8-31: Timing controls in a parallel block

    fork

    #250 -> end_wave;

    #200 r = hF7;

    #150 r = h00;

    #100 r = hE2;

    #50 r = h35;

    join

  • 7/29/2019 Behavioral Modelling

    40/45

    8-40 June 1993

    Behavioral ModelingBlock Statements

    Sequential and parallel blocks can be embedded within each otherallowing complex control structures to be expressed easily and with ahigh degree of structure.

    One simple example of this is when an assignment is to be made aftertwo separate events have occurred. This is known as the jo ining ofevents.

    Example 8-32: The joining of events

    Note that the two events can occur in any order (or even at the sametime), the fork-join block will complete, and the assignment will bemade. In contrast to this, if the fork-joinblock was abegin-endblockand the Bevent occurred before the Aevent, then the block would bedeadlocked waiting for the Bevent.

    Example 8-33 shows two sequential blocks, each of which will executewhen its con tr ol ling ev en t oc curs. Because th e wait statements are

    with in a fork-join block, they execute in parallel and the sequentialblock s ca n th er efo re also ex ecu te in parallel.

    begin

    fork

    @Aevent;

    @Bevent;

    join

    areg = breg;

    end

  • 7/29/2019 Behavioral Modelling

    41/45

    June 1993 8-41

    Behavioral ModelingStructured Procedures

    Example 8-33: Enabling sequential blocks to execute in parallel

    8.8Structured Procedures

    All pro ce dures in Ve rilog are sp ec ified with in one of th e fol lo wing fo urstatements:

    initial statement

    always statement

    task

    function

    Th e initial an d always statements are enabled at the beginning ofsimulation. The initial statement executes only once and its activitydies when the statement has finished. In contrast, the always statementexecutes repeatedly. Its activity dies only when the simulation isterminated. There is no limit to the number of initial an d alwaysblock s th at ca n be de fin ed in a module.

    Tasks and fun ct ion s are proc edure s tha t are en able d fr om on e or moreplaces in other procedures. Tasks and functions are covered in detail in

    Chapter 9, Tasks and Functions.

    fork

    @enable_a

    begin

    #ta wa = 0;

    #ta wa = 1;

    #ta wa = 0;

    end

    @enable_b

    begin

    #tb wb = 1;

    #tb wb = 0;

    #tb wb = 1;

    end

    join

  • 7/29/2019 Behavioral Modelling

    42/45

    8-42 June 1993

    Behavioral ModelingStructured Procedures

    8.8.1initial Statement

    The synt ax for the initial statement is as follows:

    Syntax 8-11: Syntax for

    Example 8-34 illustrates use of the initial statement for initializationof variables at the start of simulation.

    Example 8-34: Use ofinitial statement

    Ano th er typical usa ge of th e initial statement is specification ofwavef orm de sc riptions th at exe cute onc e to pro vide st imu lus to the mainpart of the circuit being simulated. Example 8-35 illustrates this usage.

    Example 8-35: Another use forinitial statement

    ::= initial

    initial

    begin

    areg = 0; // initialize a register

    for (index = 0; index < size; index = index + 1)

    memory[index] = 0; //initialize a memory

    word

    end

    initial

    begin

    inputs = b000000;

    // initialize at time zero#10 inputs = b011001; // first pattern

    #10 inputs = b011011; // second pattern

    #10 inputs = b011000; // third pattern

    #10 inputs = b001000; // last pattern

    end

  • 7/29/2019 Behavioral Modelling

    43/45

    June 1993 8-43

    Behavioral ModelingStructured Procedures

    8.8.2always Statement

    Th e always statement repeats continuously throughout the wholesimulation run. Syntax 8-12 gives the s yntax for the always statement.

    Syntax 8-12: Syntax for always_statement

    Th e always statement, because of its looping nature, is only useful whenused in conjunction with some form of timing control. If an always

    statement provides no means for time to advance, the always statementcreates a simulation deadlock condition. The following code, forexample, creates an infinite zero-delay loop:

    always areg = ~areg;

    Providing a timing control to the above code creates a potentially usefuldescriptionas in the following example:

    always #half_period areg = ~areg;

    8.8.3Examples

    We ha ve now intro duc ed en ou gh sta te men t types fo r so me com plet e an dmore practical examples to be given. These examples are given ascomplete descriptions enclosed in modulessuch that they can be putdirectly through the Verilog-XL compiler, simulated and the resultsobserved.

    Example 8-36 is a simple traffic light sequencer described with its ownclock generator.

    ::= always

  • 7/29/2019 Behavioral Modelling

    44/45

    8-44 June 1993

    Behavioral ModelingStructured Procedures

    Example 8-36: Behavioral model of traffic light sequencer

    module traffic_lights;

    reg

    clock,

    red,

    amber,

    green;

    parameter

    on = 1,

    off = 0,

    red_tics = 350,

    amber_tics = 30,

    green_tics = 200;

    // the sequence to control the lights

    always

    begin

    red = on;

    amber = off;

    green = off;

    repeat (red_tics) @(posedge clock);

    red = off;

    green = on;

    repeat (green_tics) @(posedge clock);

    green = off;

    amber = on;

    repeat (amber_tics) @(posedge clock);

    end

    // waveform for the clock

    alwaysbegin

    #100 clock = 0;

    #100 clock = 1;

    end

    // simulate for 10 changes on the red light

    initial

    begin

    repeat (10) @red;

    $finish;

    end

    // display the time and changes made to the lights

    always

    @(red or amber or green)$display(%d red=%b amber=%b green=%b,

    $time, red, amber, green);

    endmodule

  • 7/29/2019 Behavioral Modelling

    45/45

    Behavioral ModelingStructured Procedures

    Example 8-37 shows a use of variable delays. The module has a clockinput and produces two s ynchronized clock outputs. Each o utput clockhas equal mark and space times, is out of phase from the other by 45degrees, and has a period half that of the input clock. Note that the clockgeneration is independent of the simulation time unit, except as it affectsthe accuracy of the divide operation on the input clock period.

    Example 8-37: Behavioral model with variable delays

    module synch_clocks;

    reg

    clock,

    phase1,

    phase2;

    time clock_time;

    initial clock_time = 0;

    always @(posedge clock)begin :phase_gen

    time d; // a local declaration is possible

    // because the block is named

    d = ($time - clock_time) / 8;

    clock_time = $time;

    phase1 = 0;

    #d phase2 = 1;

    #d phase1 = 1;

    #d phase2 = 0;

    #d phase1 = 0;

    #d phase2 = 1;

    #d phase1 = 1;

    #d phase2 = 0;end

    // set up a clock waveform, finish time,

    // and display

    always

    begin

    #100 clock = 0;

    #100 clock = 1;

    end

    initial #1000 $finish; //end simulation at time 1000

    always

    @(phase1 or phase2)

    $display($time,,

    clock=%b phase1=%b phase2=%b,

    clock, phase1, phase2);

    endmodule