people-courses-142-summary of verilog syntax.pdf

11
Copyright © 1997, Hon-Chi Ng. Permission to duplicate and distribute this document is herewith granted for sole educational purpose without any commercial advantage, provided this copyright message is accompanied in all the duplicates distributed. All other rights reserved. All Cadence’s tools referred are trademarks or registered trademarks of Cadence Design Systems, Inc. All other trademarks belong to their respective owners. Summary of Verilog Syntax 1. Module & Instantiation of Instances A Module in Verilog is declared within the pair of keywords module and endmodule. Following the keyword module are the module name and port interface list. module my_module ( a, b, c, d ); input a, b; output c, d; ... endmodule All instances must be named except the instances of primitives. Only primitives in Verilog can have anonymous instances, i.e. and, or, nand, nor, xor, xnor, buf, not, bufif1, bufi0, notif1, notif0, nmos, pmos, cmos, tran, tranif1, tranif0, rnmos, rpmos, rcmos, rtran, rtranif1, rtranif0. Port Connections at Instantiations In Verilog, there are 2 ways of specifying connections among ports of instances. a) By ordered list (positional association) This is the more intuitive method, where the signals to be connected must appear in the module instantiation in the same order as the ports listed in module definition. b) By name (named association) When there are too many ports in the large module, it becomes difficult to track the order. Connecting the signals to the ports by the port names increases readability and reduces possible errors. module top; reg A, B; wire C, D; my_module m1 (A, B, C, D); // By order my_module m2 (.b(B), .d(D), .c(C), .a(A)); // By name ... endmodule Parameterized Instantiations The values of parameters can be overridden during instantiation, so that each instance can be customized separately. Alternatively, defparam statement can be used for the same purpose.

Upload: eng-cina-hassan-cina

Post on 09-Sep-2015

227 views

Category:

Documents


4 download

TRANSCRIPT

  • Copyright1997,Hon -ChiNg.

    Permissiontoduplicateanddistributethisdocumentisherewithgrantedforsoleeducationalpurposewithoutanycommercialadvantage,providedthiscopyrightmessageisaccompanied inalltheduplicatesdistributed.Allotherrightsreserved.AllCadencestoolsreferredaretrademarksorregisteredtrademarksofCadenceDesignSystems,Inc.Allothertrademarksbelongtotheirrespectiveowners.

    SummaryofVerilogSyntax

    1.Module&InstantiationofInstances

    AModule in Verilogisdeclaredwithinthepairofkeywords moduleand endmodule.Followingthekeyword modulearethe modulename and portinterfacelist .

    modulemy_module(a,b,c, d); inputa,b; outputc,d; ...

    endmodule

    All instances mustbe namedexcepttheinstancesofprimitives.Onlyprimitivesin Verilogcanhave anonymousinstances ,i.e. and, or, nand, nor, xor, xnor, buf, not,bufif1, bufi0, notif1, notif0, nmos, pmos, cmos, tran, tranif1, tranif0,rnmos, rpmos, rcmos, rtran, rtranif1, rtranif0.

    PortConnectionsatInstantiations In Verilog,thereare2waysofspecifyingconnectionsamongportsofinstances.

    a) Byorderedlist (positionalassociation) Thisisthemoreintuitivemethod,wherethesignalstobeconnectedmustappearinthe

    moduleinstantiationinthesameorderastheportslistedinmoduledefinition.

    b) Byname (namedassociation) Whentherearetoomanyportsinthelargemodule, itbecomesdifficulttotracktheorder.

    Connectingthesignalstotheportsbytheportnamesincreases readability andreducespossibleerrors.

    moduletop; regA,B; wireC,D;

    my_modulem1(A,B,C,D); //Byorder my_modulem2(.b(B), .d(D),.c(C),.a(A)); //Byname ...

    endmodule

    ParameterizedInstantiations Thevaluesofparameterscanbe overriddenduringinstantiation,sothateachinstancecan

    becustomizedseparately.Alternatively, defparamstatementcanbeusedforthe samepurpose.

  • CprE305LaboratoryTutorial VerilogSyntax Page 2of 2

    LastUpdated: 02/07/01 4:24 PM

    modulemy_module(a,b,c,d); parameterx=0;

    inputa,b; outputc,d;

    parametery=0,z=0; ...

    endmodule

    moduletop; regA,B; wireC,D;

    my_module#(2,4,3)m1(A,B,C,D); //x=2,y=4,z =3ininstancem1

    my_module#(5,3,1)m2(.b(B),.d(D),.c(C),.a(A)); //x=5,y=3,z=1ininstancem2

    defparamm3.x=4,m3.y=2,m3.z=5; my_modulem3(A,B,C,D); //x=4,y=2,z=5ininstancem3 ...

    endmodule

    2.Da taTypes

    Thereare2groupsofdatatypesin Verilog,namely physical and abstract.

    a) Physicaldatatype Net( wire, wand, wor, tri, triand, trior).Defaultvalueis z.Usedmainlyin

    structuralmodeling. Register( reg).Defaultvalueis x.Usedindataflow/RTLandbehavioralmodelings. Chargestoragenode( trireg).Defaultvalueis x.Usedingate -levelandswitch -

    level modelings.

    b) Abstractdatatype usedonlyinbehavioralmodelingandtestfixture. Integer( integer)st ores32 -bitsignedquantity. Time( time)stores64 -bitunsignedquantityfromsystemtask $time. Real( real)storesfloating -pointquantity. Parameter( parameter)substitutesconstant. Event( event)isonlynamereference doesnotholdva lue.

    Unfortunately,thecurrentstandardof Verilogdoesnotsupportuser -definedtypes,unlikeVHDL.

    3.Values&Literals

    Verilogprovides4basicvalues, a) 0 logiczeroorfalsecondition b) 1 logicone,ortruecondition c) x unkno wn/undefinedlogicvalue.Onlyforphysicaldatatypes.

  • CprE305LaboratoryTutorial VerilogSyntax Page 3of 3

    LastUpdated: 02/07/01 4:24 PM

    d) z high -impedance/floatingstate.Onlyforphysicaldatatypes.

    Constantsin Verilogareexpressedinthefollowingformat: width 'radix value width Expressedindecimalinteger.Opt ional,defaultisinferredfromvalue. 'radix Binary(b),octal( o),decimal( d),orhexadecimal( h).Optional,defaultisdecimal.

    value Anycombinationofthe4basicvaluescanbedigitsforradixoctal,decimalorhexadecimal.

    4'b1011 //4 -bitbinaryofvalue1011 234 //3 -digitdecimalofvalue234 2'h5a //2 -digit(8 -bit)hexadecimalofvalue5A 3'o671 //3 -digit(9 -bit)octalofvalue671 4b'1x0z //4 -bitbinary.2ndMSBisunknown.LSBisHi -Z. 3.14 //Floatingpoint 1.28e5 //Sc ientificnotation

    Thereare8differentstrengthlevelsthatcanbeassociatedbyvalues0and1.

    StrengthLevel Abbreviation Type Degree

    supply0supply1

    Su0Su1 driving strongest

    strong0strong1

    St0St1 driving

    pull0pull1

    Pu0Pu1 driving

    large0large1

    La0La1 chargestorage

    weak0weak1

    We0We1 driving

    medium0medium1

    Me0Me1 chargestorage

    small0small1

    Sm0Sm1 chargestorage

    highz0highz1

    HiZ0HiZ1

    weakest

    Inthecaseof contention,the strongersignaldominates .Combinationof2o ppositevaluesofsamestrengthresultsinavalueof x.

    St0, Pu1 St0 Su1, La1 Su1 Pu0, Pu1 PuX

    4.Nets&Registers

    Netisthe connectionbetweenportsofmoduleswithinahighermodule.Netisusedintestfixturesandallmodelingabst ractionincludingbehavioral.Defaultvalueofnetis high-Z(z).Netsjustonly passvalues fromoneendtotheother,i.e.itdoesnotstorethevalue.Oncetheoutputdevicediscontinuesdrivingthenet,thevalueinthenetbecomeshigh -Z( z).Besidestheusualnet( wire), Verilogalsoprovidesspecialnets( wor, wand)toresolvethe

  • CprE305LaboratoryTutorial VerilogSyntax Page 4of 4

    LastUpdated: 02/07/01 4:24 PM

    finallogicwhenthereislogiccontentionbymultipledrivers. tri, triorand triandarejustthealiasesfor wire, worand wandforreadabilityreason.

    Registeris the storagethatretains(remembers)thevaluelastassignedtoit,therefore,unlike wire,itneedsnottobecontinuouslydriven.Itisonlyusedinthetestfixture,behavioral,anddataflowmodelings.Thedefaultvalueofaregisteris unknown ( x).

    Otherspecialnetsin VerilogarethesupplieslikeV CC/VDD( supply1),Gnd( supply0),pullup( pullup)andpulldown( pulldown),resistivepullup( tri1)andresistivepulldown( tri0),andchargestorage/capacitivenode( trireg)whichhas storagestrengtha ssociatedwithit.

    5.Vectors&Arrays

    Physicaldatatypes ( wire, reg, trireg)canbedeclaredas vector/bus(multiplebitwidths).An Arrayisachunkofconsecutivevaluesofthesametype.Datatypes reg,integerand timecanbedeclaredasanarra y.Multidimensionalarraysarenotpermittedin Verilog,however,arrayscanbedeclaredforvectoredregistertype.

    wire[3:0]data; //4 -bitwidevector regbit[1:8]; //arrayof81 -bitscalar reg[3:0]mem[1:8]; //arrayof84 -bitvector

    The rangeofvectorsandarraysdeclaredcanstartfromanyinteger,andineitherascendingordescendingorder.However,whenaccessingthevectororarray,the slice(subrange)specifiedmustbewithintherangeandinthesameorderasdeclared.

    data[4] //Out -of-range bit[5:2] //Wrongorder

    Thereisnosyntaxavailabletoaccessabitsliceofanarrayelement thearrayelementhastobestoredtoa temporaryvariable .

    //Can'tdomem[7][2] reg[3:0]tmp; //Needtemporaryvariable tmp=mem[7]; tmp[2];

    6.Tasks&Functions

    Tasksandfunctionsin Verilogcloselyresembletheproceduresandfunctionsinprogramminglanguages.Bothtasksandfunctionsare definedlocally inthemoduleinwhichthetasksandfunctionswillbeinvo ked.No initialor alwaysstatementmaybedefinedwithineithertasksorfunctions.

    Tasksandfunctionsaredifferent taskmayhave0ormoreargumentsoftype input,outputor inout; functionmusthaveatleastoneinputargument.Tasksdonotreturnvaluebutpassvaluesthrough outputand inoutarguments;functionsalwaysreturnasinglevalue,butcannothave output or inoutarguments.Tasksmaycontain

  • CprE305LaboratoryTutorial VerilogSyntax Page 5of 5

    LastUpdated: 02/07/01 4:24 PM

    delay,eventortimingcontrolstatements;functionsmaynot.Taskscaninvokeothertasksandfunctions;functionscanonlyinvokeotherfunctions,butnottasks.

    modulem;reg[1:0]r1;reg[3:0]r2;regr3;

    ...

    alwaysbegin...

    r2=my_func(r1); //Invokefunction...

    my_task(r2,r3); //Invoketask...

    end

    taskmy_task;input[3:0]i;outputo;begin...

    endendtask...

    function[3:0]my_func;input[1:0]i;begin...

    my_func=...; //Returnvalueendendfunction...

    endmodule

    7.SystemTasks &CompilerDirectives

    Systemtasksarethe built-intasks standardin Verilog.Allsystemtasksareprecededwith$.Someusefulsystemtaskscommonlyusedare:

    $display("format", v1, v2,...); //Similarformattoprintf()inC$write("format", v1, v2,...); //$displayappendsnewlineattheend, //but$writedoesnot.$strobe("format", v1, v2,...); //$strobealwaysexecuteslastamong //assignmentstatementsofthesame //time.Orderfor$displayamong //as signmentstatementsofthesame //timeisunknown.

    $monitor("format", v1, v2,...); //Invokeonlyonce,andexecute(print) //automaticallywhenanyofthe //variableschangevalue.$monitoron; //Enablemonitoringfromhe re$monitoroff; //Disablemonitoringfromhere

    $stop; //Stopthesimulation$finish; //Terminateandexitthesimulation

    $time; //Returncurrentsimulationtimein64 -bitinteger$stime; //Returncurrentsimulationtimein32 -bitinteger

  • CprE305LaboratoryTutorial VerilogSyntax Page 6of 6

    LastUpdated: 02/07/01 4:24 PM

    $realtime; //Returncurrentsimulationtimein64 -bitreal

    $random(seed); //Returnrandomnumber.Seedisoptional.

    Compilerdirectivesareinstructionsto Verilogduring compilationinsteadofsimulation.Allcompilerdirectivesareprecededwith `.

    `define alias text //Createanalias.Aliasesarereplaced/substituted //priortocompilation.

    `include file //Insertanotherfileaspartofthecurrentfile.

    `ifdef cond //Ifcondisdefined,compilethefollowing.`else`endif

    8.Opera tors

    OperatorSymbol Function Group Operands

    PrecedenceRank

    ! logicalnegation Logical unary 1~ bitwisenegation Bitwise unary& reductionand Reduction unary| reductionor Reduction unary^ reductionxor Reduction unary~& reductionnand Reduction unary~| reductionnor Reduction unary~^ reductionxnor reduction unary+ unarypositive arithmetic unary- unarynegative arithmetic unary

    * multiplication arithmetic binary 2/ division arithmetic binary% modulus arithmetic binary

    + addition arithmetic binary 3- subtraction arithmetic binary

    > rightshift shift binary

    < lessthan relational binary 5 greaterthan relational binary>= greaterthanorequal relational binary

    == equality equality binary 6!= inequality equality binary=== caseequality equality binary!== caseinequality equality binary

    & bitwiseand bitwise binary 7

    ^ bitwisexor bitwise binary 8^~ bitwisexnor bitwise binary

  • CprE305LaboratoryTutorial VerilogSyntax Page 7of 7

    LastUpdated: 02/07/01 4:24 PM

    | bitwiseor bitwise binary 9

    && logicaland logical binary 10

    || logicalor logical binary 11

    ?: conditional ternary 12

    = blockingassignment assignment binary 13

  • CprE305LaboratoryTutorial VerilogSyntax Page 8of 8

    LastUpdated: 02/07/01 4:24 PM

    a) Sequentialblock Sequentialblocksaredelimitedbythepairofkeywords beginand end.The

    statementsinsequentialblocksareexecutedinthe order theyarespecified,exceptnon -blockingassignments.

    b) Parallelblock Parallelblocksaredelimitedbythepairofkeywords forkand join.Thestatementsin

    parallelblocksareexecuted concurrently.Hence,theorderofthestatementsinparallelblocksareimmaterial.

    11.Assignments

    a) Continuousassignment Continuousassignmentsarealways active changesinRHS(righthandside)

    expressionisassignedtoisLHS(lefthandside)net.

    LHSmustbeascalarorvectorof nets,andassignment mustbeperformed outsideprocedurestatements.

    assign#delaynet=expression;

    Delaymaybeassociatedwiththeassignment,wherenewchangesinexpressionisassignedtonetafterthedelay.However,notethatsuchdelayiscalled inertialdelay ,i .e.iftheexpressionchangesagainwithinthedelayafterthe1stchange,onlythelatestchangeisassignedtonetafterthedelayfrom2ndchange.The1stchangewithinthedelayisnotassignedtonet.

    b) Proceduralassignment LHSmustbeascalar orvectorof registers,andassignmentmustbeperformed inside

    procedurestatements( initialor always).Assignmentisonlyactive(evaluatedandloaded)whencontrolistransferredtoit.Afterthat,thevalueofregisterremainsuntilitisreassigne dbyanotherproceduralassignment.

    Thereare2typesofproceduralassignments: Blockingassignment Blockingassignmentsareexecutedintheorderspecifiedinthesequentialblock,i.e.a

    blockingassignmentwaitsforpreviousblockingassignme ntofthesametimetocompletebeforeexecuting.

    register=expression;

    Nonblockingassignment Nonblockingassignmentsareexecutedconcurrentlywithinthesequentialblocks,i.e.a

    nonblockingassignmentexecuteswithoutwaitingforothernonblo ckingassignmentsofoccurringatthesametimetocomplete.

    register

  • CprE305LaboratoryTutorial VerilogSyntax Page 9of 9

    LastUpdated: 02/07/01 4:24 PM

    Theexpressionisevaluatedimmediately,butthevalueisassignedtor egisterafterthedelay.Thisisequivalentto

    regtemporary; temporary=expression; #delayregister=temporary;

    c) Quasi-continuous (proceduralcontinuous) assignment TheLHSmustbeascalarorvectorof registers,andassignmentmustbe inside

    procedurestatements.

    Similartoproceduralassignment,howeverquasi -continuousassignmentbecomes activeand staysactive fromthepointoftheassignmentuntilitis deactivatedthroughdeassignment.Whenactive,quasi -continuousassignment overridesanyproceduralassignmenttotheregister.

    begin ...

    assignregister=expression1; //Activatequasi -continuous ...

    register=expression2; //Noeffect.Overriddenbyactive //quasi -continuous ...

    assignregister =expression3; //Becomesactiveandoverrides //previousquasi -continuous ...

    deassignregister; //Disablequasi -continuous ...

    register=expression4; //Executed. ...

    end

    Thereis nodelay associatedwithquasi -continuousassignment..Onlytheactivationmaybedelayed.However,onceitis activated,anychangesinexpressionwillbeassignedtotheregister immediately.

    12.TimingControls

    a) Delay-based Executionofastatementcanbedelayedbyafixed -timeperiodusingthe#operator.

    #numstatement; //Delaynumtimefrompreviousstatementbefore //executing

    Intra-assignmentdelay ThisevaluatestheRHSexpressionimmediately,butdelaysforafixed -timeperiodbefore

    assigningtoLHS,whic hmustbearegister.

    register=#numexpr; //Evaluateexprnow,butdelaynumtimeunit //beforeassigningtoregister

    b) Event-based

  • CprE305LaboratoryTutorial VerilogSyntax Page 10of 10

    LastUpdated: 02/07/01 4:24 PM

    Executionofastatementistriggeredbythechangeofvalueinaregisteroranet.The @operatorcapt uressuchchangeofvaluewithinits recognizinglist .Toallowmultipletriggers,use orbetweeneachevent.

    @(signal)statement; //Executewheneversignalchangesvalues @(posedgesignal)statement;//Executeatpositiveedgeofsignal @(negedges ignal)statement;//Executeatnegativeedgeofsignal register=@(signal)expr; //Similartointra -assignment always@(s1ors2ors3) //Enteralwaysblockwheneithers1,s2 ... //ors3changesvalue

    Level-sensitive The @isedge -sensitive.Toachievelevel -sensitive,useadditional ifstatementtocheck

    thevaluesofeachevent.

    always@(signal) if(signal) ...

    else ...

    Alternatively,combinationof alwaysand waitcanbeused.But,notethat waitisablockingstatement,i.e. waitblocksfollowingstatementuntiltheconditionistrue.

    always wait(event)statement; //Executestatementwheneventistrue

    c) Named-event Eventis explicitlytriggered (with -> operator)and recognized(with @operator).

    Notethatthenamedeventcannotholdanydata.

    eventmy_event; //Declareanevent

    always@(my_event) //Executewhenmy_eventistriggered begin ...

    end

    always begin ...

    if(...) ->my_event; //Triggermy_event ...

    end13.ConditionalStatements

    Thebodyonlyallowsasinglestatement.Ifmultiplestatementsaredesired,blockstatementsmaybeusedtoenclosemultiplestatementsinplaceofthebody.

    a) If-Then-Else if(expr) statement;

    if(expr)

  • CprE305LaboratoryTutorial VerilogSyntax Page 11of 11

    LastUpdated: 02/07/01 4:24 PM

    statemen t; else statement;

    if(expr)statement; elseif(expr)statement; elseif(expr)statement; elsestatement;

    b) Case case(expr) value1:statement; value2:statement; value3:statement; ...

    default:statement; endcase

    14.LoopStatements

    Thebodyonlyallowsasinglestatement.Ifmultiplestatementsaredesired,blockstatementsmaybeusedtoenclosemultiplestatementsinplaceofthebody.

    a) While while(expr) statement;

    b) For for(init;expr; step) statement;

    c) Repeat Iterationsarebasedonaconstantinsteadofconditionalexpression.

    repeat(constant) //Fixnumberofloops statement;

    d) Forever forever //Sameaswhile(1) statement;

    References:

    [1] "Verilog-XLReferenceManualver2.2."OpenBook,CadenceDesignSystems,1995.[2] SamirPalnitkar."VerilogHDL:AGuidetoDigitalDesignandSynthesis."SunSoftPress,

    1996.[3] DonaldThomas,PhilMoorby."TheVerilogHardwareDescriptionLanguage,2nded."

    KluwerAcademicPublishers,1994.[4] EliSternheim,RajvirSingh,RajeevMadhavan,YatinTrivedi."DigitalDesignand

    SynthesiswithVerilogHDL."AutomataPublishingCompany,1993.