Short Notes on Verilog and SystemVerilog

JasonPulikkottil 88 views 17 slides Aug 18, 2024
Slide 1
Slide 1 of 17
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17

About This Presentation

Originally a modeling language for a very efficient
event-driven digital logic simulator
Later pushed into use as a specification language for logic
synthesis
Now, one of the two most commonly-used languages in
digital hardware design (VHDL is the other)
Virtually every chip (FPGA, ASIC, etc.) is de...


Slide Content

The
V
erilog
Langua
g
e
Or
iginally
a
modeling
language
for
a
v
er
y
efcient
e
v
ent-dr
iv
en
digital
logic
sim
ulator
Later
pushed
into
use
as
a
specication
language
for
logic
synthesis No
w
,
one
of
the
tw
o
most
commonly-used
languages
in
digital
hardw
are
design
(VHDL
is
the
other)
Vir
tually
e
v
er
y
chip
(FPGA,
ASIC
,
etc.)
is
designed
in
par
t
using
one
of
these
tw
o
languages
Combines
str
uctur
al
and
beha
vior
al
modeling
styles
MultiplexerBuiltFromPrimitives modulemux(f,a,b,sel);
Verilogprograms
builtfrommodules
outputf;
inputa,b,sel;
Eachmodulehas
aninterface
andg1(f1,a,nsel),
g2(f2,b,sel);
org3(f,f1,f2);
notg4(nsel,sel);
Modulemaycontain
structure:instancesof
primitivesandother
modules
endmodule
g1
g4
g2
g3
a
b
sel
f
nsel
f1 f2
MultiplexerBuiltwithAlways modulemux(f,a,b,sel);
outputf;
inputa,b,sel;
regf;
always
Modulesmay
containoneormore
alwaysblocks
@(aorborsel)
Sensitivitylist
containssignals
whosechange
makestheblock
execute
if(sel)f=a;
elsef=b;
endmodule
a
b
sel
f
MultiplexerBuiltwithAlways modulemux(f,a,b,sel);
outputf;
inputa,b,sel;
regf;
Aregbehaveslike
memory:holdsitsvalue
untilimperatively
assignedotherwise
always@(aorborsel)
if(sel)f=a;
elsef=b;
Bodyofanalwaysblock
containstraditional
imperativecode
endmodule
a
b
sel
f
MuxwithContinuousAssignment modulemux(f,a,b,sel);
outputf;
inputa,b,sel;
assign
LHSisalwayssetto
thevalueontheRHS
Anychangeontheright
causesreevaluation
f=sel?a:b;
endmodule
a
b
sel
f
MuxwithUser-DenedPrimitive primitivemux(f,a,b,sel);
outputf;
inputa,b,sel;
table
1?0:1;
Behaviordenedusing
atruthtablethat
includes“don'tcares”
0?0:0;
?11:1;
?01:0;
11?:1;
Thisisalesspessimisticthan
others:whena&bmatch,selis
ignored;othersproduceX
00?:0;
endtable
endprimitive
a
b
sel
f
HowAreSimulatorsUsed? Testbenchgeneratesstimulusandchecksresponse
Coupledtomodelofthesystem
Pairisrunsimultaneously
Testbench
SystemModel
Stimulus
Respons e
Resultchecker
StructuralModeling WhenVerilogwasrstdeveloped(1984)mostlogic
simulatorsoperatedonnetlists
Netlist:listofgatesandhowthey'reconnected
Anaturalrepresentationofadigitallogiccircuit
Notthemostconvenientwaytoexpresstestbenches
Short Notes on
Verilog
&
SystemVerilog

BehavioralModeling Amucheasierwaytowritetestbenches
Alsogoodformoreabstractmodelsofcircuits

Easiertowrite

Simulatesfaster
Moreexible
Providessequencing
Verilogsucceededinpartbecauseitallowedboththe
modelandthetestbenchtobedescribedtogether
HowVerilogIsUsed VirtuallyeveryASICisdesignedusingeitherVerilogor
VHDL(asimilarlanguage)
Behavioralmodelingwithsomestructuralelements
“Synthesissubset”canbetranslatedusingSynopsys'
DesignCompilerorothersintoanetlist
DesignwritteninVerilog
Simulatedtodeathtocheckfunctionality
Synthesized(netlistgenerated)
Statictiminganalysistochecktiming
TwoMainComponentsofVerilog:
Behavioral
Concurrent,event-triggeredprocesses(behavioral)
InitialandAlwaysblocks
Imperativecodethatcanperformstandarddata
manipulationtasks(assignment,if-then,case)
Processesrununtiltheydelayforaperiodoftimeorwait
foratriggeringevent
TwoMainComponentsofVerilog:
Structural
Structure(Plumbing)
VerilogprogrambuildfrommoduleswithI/Ointerfaces
Modulesmaycontaininstancesofothermodules
Modulescontainlocalsignals,etc.
Modulecongurationisstaticandallrunconcurrently
TwoMainDataTypes:Nets Netsrepresentconnectionsbetweenthings
Donotholdtheirvalue
Taketheirvaluefromadriversuchasagateorother
module
Cannotbeassignedinaninitialoralwaysblock
TwoMainDataTypes:Regs Regsrepresentdatastorage
Behaveexactlylikememoryinacomputer
Holdtheirvalueuntilexplicitlyassignedinaninitialor
alwaysblock
Neverconnectedtosomething
Canbeusedtomodellatches,ip-ops,etc.,butdonot
correspondexactly
Actuallysharedvariableswithalltheirattendantproblems
Discrete-eventSimulation Basicidea:onlydoworkwhensomethingchanges
Centeredaroundaneventqueuethatcontainsevents
labeledwiththesimulatedtimeatwhichtheyaretobe
executed
Basicsimulationparadigm

Executeeveryeventforthecurrentsimulatedtime

Doingthischangessystemstateandmayschedule
eventsinthefuture

Whentherearenoeventsleftatthecurrenttime
instance,advancesimulatedtimesoonesteventinthe
queue
Four-valuedData Verilog'snetsandregistersholdfour-valueddata
0,1:Obvious
Z:Outputofanundriventri-statedriver.Modelscase
wherenothingissettingawire'svalue
X:Modelswhenthesimulatorcan'tdecidethevalue

Initialstateofregisters

Whenawireisbeingdrivento0and1simultaneously

OutputofagatewithZinputs
Four-valuedLogic Logicaloperatorsworkonthree-valuedlogic
01XZ
0
0000
Outputs0ifeither
inputis0
1
01XX
X
0XXX
OutputsXifboth
inputsaregibberish
Z
0XXX

StructuralModeling
NetsandRegisters Wiresandregisterscanbebits,vectors,andarrays
wirea;//Simplewire
tri[15:0]dbus;//16-bittristatebus
tri#(5,4,8)b;//Wirewithdelay
reg[-1:4]vec;//Six-bitregister
trireg(small)q;//Wirestoresasmallcharge
integerimem[0:1023];//Arrayof1024integers
reg[31:0]dcache[0:63];//A32-bitmemory
ModulesandInstances BasicstructureofaVerilogmodule:
modulemymod(out1,out2,
Verilogconvention
listsoutputsrst in1,in2);
outputout1;
output[3:0]out2;
inputin1;
input[2:0]in2;
endmodule
InstantiatingaModule Instancesof
modulemymod(y,a,b);
looklike
mymodmm1(y1,a1,b1);
//Connect-by-position
mymod(y2,a1,b1),
(y3,a2,b2);
//Instancenamesomitted
//Connect-by-name
mymodmm2(.a(a2),.b(b2),.y(c2));
Gate-levelPrimitives Verilogprovidesthefollowing:
andnandlogicalAND/NAND
ornorlogicalOR/NOR
xorxnorlogicalXOR/XNOR
bufnotbuffer/inverter
buf0notif0Tristatewithlowenable
bif1notif1Tristatewithhighenable
DelaysonPrimitiveInstances Instancesofprimitivesmayincludedelays
bufb1(a,b);
//Zerodelay
buf#3b2(c,d);
//Delayof3
buf#(4,5)b3(e,f);
//Rise=4,fall=5
buf#(3:4:5)b4(g,h);
//Min-typ-max
Switch-levelPrimitives VerilogalsoprovidesmechanismsformodelingCMOS
transistorsthatbehavelikeswitches
Amoredetailedmodelingschemethatcancatchsome
additionalelectricalproblemswhentransistorsareusedin
thisway
Now,little-usedbecausecircuitsgenerallyaren'tbuiltthis
way
Moreseriously,modelisnotdetailedenoughtocatch
manyoftheproblems
ThesecircuitsareusuallysimulatedusingSPICE-like
simulatorsbasedonnonlineardifferentialequationsolvers
User-DenedPrimitives Waytodenegatesandsequentialelementsusingatruth
table
Oftensimulatefasterthanusingexpressions,collections
ofprimitivegates,etc.
GivesmorecontroloverbehaviorwithXinputs
Mostoftenusedforspecifyingcustomgatelibraries
ACarryPrimitive primitivecarry(out,a,b,c);
outputout;
Alwayshasexactly
oneoutput
inputa,b,c;
table
00?:0;
0?0:0;
?00:0;
Truthtablemayinclude
don't-care(?)entries
11?:1;
1?1:1;
?11:1;
endtable
endprimitive

ASequentialPrimitive Primitivedff(q,clk,data);
outputq;regq;
inputclk,data;
table
//clkdataqnew-q
(01)0:?:0;
//Latcha0
(01)1:?:1;
//Latcha1
(0x)1:1:1;
//Holdwhendandqboth1
(0x)0:0:0;
//Holdwhendandqboth0
(?0)?:?:-;
//Holdwhenclkfalls
?(??):?:-;
//Holdwhenclkstable
endtable
endprimitive
ContinuousAssignment Anotherwaytodescribecombinationalfunction
Convenientforlogicalordatapathspecications
wire[8:0]sum;
Denebuswidths
wire[7:0]a,b;
wirecarryin;
assignsum=a+b+carryin;
Continuous
assignment:
permanently
setsthevalueof
sumtobe
a+b+carryin.
Recomputed
whena,b,or
carryinchanges
BehavioralModeling
InitialandAlwaysBlocks initial
begin
//imperativestatements
end
Runswhensimulationstarts
Terminateswhencontrol
reachestheend
Goodforprovidingstimulus
always
begin
//imperativestatements
end
Runswhensimulationstarts
Restartswhencontrol
reachestheend
Goodformodelingor
specifyinghardware
InitialandAlways Rununtiltheyencounteradelay
initialbegin
#10a=1;b=0;
#10a=0;b=1;
end
orawaitforanevent
always@(posedgeclk)q=d;
alwaysbegin
wait(i);
a=0;
wait(i);
a=1;
end
ProceduralAssignment Insideaninitialoralwaysblock:
sum=a+b+cin;
JustlikeinC:RHSevaluatedandassignedtoLHSbefore
nextstatementexecutes
RHSmaycontainwiresand/orregs
LHSmustbeareg
(onlyprimitivesorcontinuousassignmentmaysetwire
values)
ImperativeStatements if(select==1)y=a;
elsey=b;
case(op)
2'b00:y=a+b;
2'b01:y=a-b;
2'b10:y=aˆb;
default:y='hxxxx;
endcase
ForLoops Examplegeneratesanincreasingsequenceofvalueson
anoutput
reg[3:0]i,output;
for(i=0;i<=15;i=i+1)begin
output=i;
#10;
end
WhileLoops Aincreasingsequenceofvaluesonanoutput
reg[3:0]i,output;
i=0;
while(i<=15)begin
output=i;
#10i=i+1;
end

ModelingAFlip-FlopWithAlways Verybasic:anedge-sensitiveip-op
regq;
always@(posedgeclk)
q=d;
q=dassignmentrunswhenclockrises:exactlythe
behavioryouexpect
Blockingvs.Nonblocking Veriloghastwotypesofproceduralassignment
Fundamentalproblem:

Inasynchronoussystem,allip-opssample
simultaneously

InVerilog,always@(posedgeclk)blocksrunin
someundenedsequence
AFlawedShiftRegister Thisdoesnotworkasyouwouldexpect:
regd1,d2,d3,d4;
always@(posedgeclk)d2=d1;
always@(posedgeclk)d3=d2;
always@(posedgeclk)d4=d3;
Theseruninsomeorder,butyoudon'tknowwhich
Non-blockingAssignments Thisversiondoeswork:
regd1,d2,d3,d4;
always@(posedgeclk)d2<=d1;
Nonblockingrule:
RHSevaluated
whenassignment
runs
always@(posedgeclk)d3<=d2;
always@(posedgeclk)d4
LHSupdatedonly
afteralleventsfor
thecurrentinstant
haverun
<=d3;
NonblockingCanBehaveOddly Asequenceofnonblockingassignmentsdon't
communicate
a=1;
b=a;
c=b;
Blockingassignment:
a=b=c=1
a<=1;
b<=a;
c<=b;
Nonblockingassignment:
a=1
b=oldvalueofa
c=oldvalueofb
NonblockingLooksLikeLatches RHSofnonblockingtakenfromlatches
RHSofblockingtakenfromwires
a=1;
b=a;
c=b;
ª
1
c
a
b
º
a<=1;
b<=a;
c<=b;
ª
1
c
a b
º
BuildingBehavioral
Models
ModelingFSMsBehaviorally Therearemanywaystodoit:

Denethenext-statelogiccombinationallyanddene
thestate-holdinglatchesexplicitly

Denethebehaviorinasinglealways@(posedge
clk)block

Variationsonthesethemes
FSMwithCombinationalLogic moduleFSM(o,a,b,reset);
outputo;
rego;
Outputoisdeclaredareg
becauseitisassigned
procedurally,notbecauseit
holdsstate
inputa,b,reset;
reg[1:0]state,nextState;
always@(aorborstate)
case(state)
2'b00:begin
o=a&b;
nextState=a?2'b00:2'b01;
end
2'b01:begin
o=0;nextState=2'b10;
end
endcase
always@(posedgeclkorreset)
if(reset)
state<=2'b00;
else
state<=nextState;
endmodule

FSMwithCombinationalLogic moduleFSM(o,a,b,reset);
outputo;
rego;
inputa,b,reset;
reg[1:0]state,nextState;
always@(aorborstate)
Combinationalblockmustbe
sensitivetoanychangeonany
ofitsinputs(Implies
state-holdingelements
otherwise)
case(state)
2'b00:begin
o=a&b;
nextState=a?2'b00:2'b01;
end
2'b01:begin
o=0;nextState=2'b10;
end
endcase
always@(posedgeclkorreset)
Latchimpliedby
sensitivitytotheclock
orresetonly
if(reset)
state<=2'b00;
else
state<=nextState;
endmodule
FSMfromaSingleAlwaysBlock moduleFSM(o,a,b);
outputo;rego;
inputa,b;
reg[1:0]state;
always@(posedgeclkorreset)
ExpressesMoore
machinebehavior:
Outputsarelatched.
Inputsonlysampled
atclockedges
if(reset)state<=2'b00;
elsecase(state)
2'b00:begin
state<=a?2'b00:2'b01;
o<=a&b;
end
2'b01:begin
state<=2'b10;
o<=0;
Nonblockingassignments
usedthroughouttoensure
coherency.RHSrefersto
valuescalculatedin
previousclockcycle
end
endcase
WritingTestbenches moduletest;
rega,b,sel;
Inputstodevice
undertest
muxm(y,a,b,sel);
Deviceundertest
initialbegin
$monitor
$monitorisabuilt-ineven-driven“printf”
($time,,"a=%bb=%bsel=%by=%b",
a,b,sel,y);
a=0;b=0;sel=0;
#10a=1;
#10sel=1;
Stimulusgeneratedby
sequenceof
assignmentsand
delays
#10b=1;
end
SimulatingVerilog
SimulationBehavior Scheduledusinganeventqueue
Non-preemptive,nopriorities
Aprocessmustexplicitlyrequestacontextswitch
Eventsataparticulartimeunordered
Schedulerrunseacheventatthecurrenttime,possibly
schedulingmoreasaresult
TwoTypesofEvents Evaluationeventscomputefunctionsofinputs
Updateeventschangeoutputs
Splitnecessaryfordelays,nonblockingassignments,etc.
Updateeventwrites
newvalueofaand
schedulesany
evaluationevents
thataresensitiveto
achangeona
a<=b+c
Evaluationevent
readsvaluesofb
andc,addsthem,
andschedulesan
updateevent
SimulationBehavior Concurrentprocesses(initial,always)rununtiltheystop
atoneofthefollowing

#42
Scheduleprocesstoresume42timeunitsfromnow

wait(cf&of)
Resumewhenexpression“cf&of”becomestrue

@(aorbory)
Resumewhena,b,orychanges

@(posedgeclk)
Resumewhenclkchangesfrom0to1
SimulationBehavior Inniteloopsarepossibleandthesimulatordoesnot
checkforthemThisrunsforever:nocontextswitch
allowed,soreadycanneverchange
while(˜ready)
count=count+1;
Instead,use
wait(ready);
SimulationBehavior RaceconditionsaboundinVerilog
Thesecanexecuteineitherorder:nalvalueofa
undened:
always@(posedgeclk)a=0;
always@(posedgeclk)a=1;

SimulationBehavior Semanticsofthelanguagecloselytiedtosimulator
implementation
Contextswitchingbehaviorconvenientforsimulation,not
alwaysbestwaytomodel
Undenedexecutionorderconvenientforimplementing
eventqueue
Compiled-CodeDiscrete-EventSim. Mostmodernsimulatorsusethisapproach
VerilogprogramcompiledintoC
Eachconcurrentprocess(e.g.,continuousassignment,
alwaysblock)becomesoneormoreCfunctions
Initialandalwaysblockssplitintomultiplefunctions,one
persegmentofcodebetweenadelay,await,orevent
control(@)
Central,dynamiceventqueueinvokesthesefunctionsand
advancessimulationtime
VerilogandLogic
Synthesis
LogicSynthesis Verilogisusedintwoways
Modelfordiscrete-eventsimulation
Specicationforalogicsynthesissystem
LogicsynthesisconvertsasubsetoftheVeriloglanguage
intoanefcientnetlist
Oneofthemajorbreakthroughsindesigninglogicchipsin
thelast20years
Mostchipsaredesignedusingatleastsomelogic
synthesis
LogicSynthesisTools Mostlycommercialtools

Verydifcult,complicatedprogramstowritewell

Limitedmarket

Commercialproductsin$10k–$100kpricerange
Majorvendors

SynopsysDesignCompiler,FPGAExpress

CadenceBuildGates

Synplicity(FPGAs)

Exemplar(FPGAs)
Academictools

SIS(UCBerkeley)
LogicSynthesis Takesplaceintwostages:
1.TranslationofVerilog(orVHDL)sourcetoanetlist
Registerinferenceperformedhere
2.Optimizationoftheresultingnetlisttoimprovespeed
andarea
Mostcriticalpartoftheprocess
Algorithmsverycomplicatedandbeyondthescopeof
thisclass
LogicOptimization Netlistoptimizationthecriticalenablingtechnology
Takesasloworlargenetlistandtransformsitintoonethat
implementsthesamefunctionmorecheaply
Typicaloperations:

Constantpropagation

Commonsubexpressionelimination

Functionfactoring
Time-consumingoperation.Cantakehoursforlargechips
TranslatingVerilogintoGates Partsofthelanguageeasytotranslate
Structuraldescriptionswithprimitivesisalreadyanetlist
Continuousassignmentexpressionsturnintolittle
datapaths
Behavioralstatementsthebiggerchallenge
WhatCanBeTranslated Everystructuralde®nition
Behavioralblocks

Dependsonsensitivitylist

Onlywhentheyhavereasonableinterpretationas
combinationallogic,edge,orlevel-sensitivelatches

Blockssensitivetobothedgesoftheclock,changeson
unrelatedsignals,changingsensitivitylists,etc.cannotbe
synthesized
User-de®nedprimitives

Primitivesde®nedwithtruthtables

SomesequentialUDPscan'tbetranslated(notlatchesor
¯ip-¯ops)

WhatIsNotTranslated Initialblocks

Usedtosetupinitialstateordescribe®nitetestbenchstimuli

Don'thaveobvioushardwarecomponent
Delays

MaybeintheVerilogsource,butaresimplyignored
Avarietyofotherobscurelanguagefeatures

Ingeneral,thingsheavilydependentondiscrete-event
simulationsemantics

Certainªdisableºstatements

Pureevents
RegisterInference Themaintrick
Aregisnotalwaysalatchorip-op
Rule:Combinationalifoutputsalwaysdependexclusively
onsensitivitylist
Sequentialifoutputsmayalsodependonpreviousvalues
RegisterInference Combinational:
regy;
always@(aorborsel)
Sensitiveto
changesonallthe
variableitreads
if(sel)y=a;
elsey=b;
yisalwaysassigned
Sequential:
regq;
always@(dorclk)
if(clk)q=d;
qonlyassigned
whenclkis1
RegisterInference Acommonmistakeisnotcompletelyspecifyingacase
statement
Thisimpliesalatch:
always@(aorb)
case({a,b})
2'b00:f=0;
2'b01:f=1;
2'b10:f=1;
endcase
fisnotassignedwhen
{a,b}=2'b11
RegisterInference Thesolutionistoalwayshaveadefaultcase
always@(aorb)
case({a,b})
2'b00:f=0;
2'b01:f=1;
2'b10:f=1;
default:f=0;
fisalwaysassigned
endcase
InferringLatcheswithReset LatchesandFlip-opsoftenhaveresetinputs
Canbesynchronousorasynchronous
Asynchronouspositivereset:
always@(posedgeclkorposedgereset)
if(reset)
q<=0;
elseq<=d;
Simulation-synthesisMismatches Manypossiblesourcesofconict

Synthesisignoresdelays(e.g.,#10),butsimulation
behaviorcanbeaffectedbythem

SimulatormodelsXexplicitly,synthesisdoesnot

Behaviorsresultingfromshared-variable-likebehavior
ofregsisnotsynthesized:
always@(posedgeclk)a=1;
Newvalueofamaybeseenbyother@(posedgeclk)
statementsinsimulation,neverinsynthesis
SummaryofVerilog1995 Systemsdescribedhierarchically

Moduleswithinterfaces

Modulescontaininstancesofprimitives,other
modules

Modulescontaininitialandalwaysblocks
Basedondiscrete-eventsimulationsemantics

Concurrentprocesseswithsensitivitylists

Schedulerrunspartsoftheseprocessesinresponse
tochanges
ModelingTools Switch-levelprimitives:CMOStransistorsasswitchesthat
movearoundcharge
Gate-levelprimitives:Booleanlogicgates
User-denedprimitives:Gatesandsequentialelements
denedwithtruthtables
Continuousassignment:Modelingcombinationallogic
withexpressions
Initialandalwaysblocks:Proceduralmodelingofbehavior

LanguageFeatures Nets(wires)formodelinginterconnection

Nonstate-holding

Valuessetcontinuously
Regsforbehavioralmodeling

Behaveexactlylikememoryforimperativemodeling

Donotalwayscorrespondtomemoryelementsin
synthesizednetlist
Blockingvs.nonblockingassignment

Blockingbehaveslikenormal“C-like”assignment

Nonblockingdelaysupdate,modelingsynchronous
behavior
LanguageUses Event-drivensimulation

Eventqueuecontainingthingstodoatparticular
simulatedtimes

Evaluateandupdateevents

Compiled-codeevent-drivensimulationforspeed
Logicsynthesis

TranslatingVerilog(structuralandbehavioral)into
netlists

Registerinference:whetheroutputisalwaysupdated

Logicoptimizationforcleaninguptheresult
Little-usedLanguageFeatures Switch-levelmodeling

Muchslowerthangateorbehavioral-levelmodels

Insufcientdetailformodelingmostelectrical
problems

Delicateelectricalproblemssimulatedwitha
SPICE-likedifferentialequationsimulator
Little-usedLanguageFeatures Delays

Simulatingcircuitswithdelaysdoesnotimprove
condenceenough

Hardtogettimingmodelsaccurateenough

Neversureyouhavesimulatedtheworstcase

Statictiminganalysishastakenitsplace
ComparedtoVHDL VerilogandVHDLarecomparablelanguages
VHDLhasaslightlywiderscope

System-levelmodeling

Exposesevenmorediscrete-eventmachinery
VHDLisbetter-behaved:Fewersourcesof
nondeterminism(e.g.,nosharedvariables)
VHDLishardertosimulatequickly
VHDLhasfewerbuilt-infacilitiesforhardwaremodeling
VHDLisamuchmoreverboselanguage:Mostexamples
don'ttonslides
InConclusion Verilogisadeeplyawedlanguage

Nondeterministic

Oftenweirdbehaviorduetodiscrete-eventsemantics

Vaguelydenedsynthesissubset

Manypossiblesourcesofsimulation/synthesis
mismatch
InConclusion Verilogiswidelyusedbecauseitsolvesaproblem

Goodsimulationspeedthatcontinuestoimprove

Designersuseawell-behavedsubsetofthelanguage

Makesareasonablespecicationlanguageforlogic
synthesis

Logicsynthesisoneofthegreatdesignautomation
successstories
Verilog2001
Verilog2001 RevisedversionoftheVeriloglanguage
IEEEStandard1364-2001
Minorchangestothelanguage:
ANSICstyleports
standardleI/O
(*attributes*)
multidimensionalarrays
generate
$value$plusargs
congurations
signedtypes
localparam
`ifndef`elsif`line
memorypartselects
automatic
constantfunctions
@*
variablepartselect
**(poweroperator)

Impliciteventlists Commonmistake:forgettingavariableincombinational
sensitivitylist
always@(aorborc
Forgottoincluded
)
f=a&b|c&d;
Doesnotsimulatelikehardwarebehaves.
Verilog2001'simplicitsensitivitylist:
always@*
f=a&b|c&d;
Makesprocesssensitivetoallvariablesonright-handside
ofassignments.
Generate Hardwarestructuresoftenveryregular.Wanttocreate
themalgorithmically.
Verilog'sgenerate:veryclevermacroexpansion.
modulegray2bin1(bin,gray);
parameterSIZE=8;
output[SIZE-1:0]bin;
input[SIZE-1:0]gray;
genvar
i;
//Compile-timeonly
generatefor(i=0;i<SIZE;i=i+1)
begin:bit
assignbin[i]=ˆgray[SIZE-1:i];
end
endgenerate
endmodule
Attributes Logicsynthesishasreliedonhintsincomments: always@(posedgeclk)
begin
case(instr[6:5])//
synopsysfull_caseparallel_case
0:mask<=8'h01;
1:mask<=8'h02;
2:mask<=8'h04;
3:mask<=8'h08;
endcase
end
full_casemeansonecasewillalwaysbetrue,
parallel_casemeansatmostonewillbetrue.
Cangreatlysimplifythegeneratedlogic,but
simulation/synthesismismatchifassertionisnottrue.
Attributes Suchattributesnowarst-classpartofthelanguage.
Simulatorunderstandsandchecksvalidity.
always@(posedgeclk)
begin
(*full_case,parallel_case=1*) case(instr[6:5])
0:mask<=8'h01;
1:mask<=8'h02;
2:mask<=8'h04;
3:mask<=8'h08;
endcase
end
ANSIC-styleports Verilog1995portscouldrequirethreedeclarations:
modulefoo(
myport1
,
myport2
);
output
myport1
;
reg[7:0]
myport1
;
input[3:0]
myport2
;
...
endmodule
Verilog2001reducesthistoone:
modulefoo(outputreg[7:0]
myport1
,
input[3:0]
myport2
);
...
endmodule
Congurations ®lelib.map
librarygateLib./*.vg;
libraryrtlLib*.v;
//specifyrtladderfortop.a1
//gate-leveladderfortop.a2
configcfg1;
designrtlLib.top;
defaultliblistrtlLib;
instancetop.a2
liblistgateLib;
endconfig
Awaytoselectamongdifferent
implementationsusingthesame
top-levelmodules.
®leadder.v
moduleadder(...);
//RTLadder
//implementation
...
endmodule
®letop.v
moduletop();
addera1(...);
addera2(...);
endmodule
®leadder.vg
moduleadder(...);
//gate-leveladder
...
endmodule
SystemVerilog
SystemVerilog Muchbiggerchangetothelanguage.
Veri®cationFeatures
assertions
biasedrandomvariables
testprogramblocks
processcontrol
mailboxes
semaphores
clockingdomains
directCfunctioncalls
C++-likefeatures
classes
dynamicarrays
inheritance
associativearrays
strings
references
MoreSystemVerilogFeatures C-likefeatures
intshortint
longintbyte
shortrealvoid
aliasenum
structunion
consttypedef
breakcontinue
returndowhile
casting
globals
++--
+=-=*=/=
>>=<<=>>>=<<<=
&=|=Ã=%=
ModelingFeatures
interfaces
dynamicprocesses
nestedhierarchy
2-statemodeling
unrestrictedports
packedarrays
implicitportconnections
arrayassignments
enhancedliterals
enhancedeventcontrol
timevalues&units
unique/prioritycase/if
logic-speci®cprocesses
rootnamespaceaccess

C-likeFeatures
NewTypes
typevalueswidthnew
reg{0,1,X,Z}1+
logic{0,1,X,Z}1+3
integer{0,1,X,Z}32
bit{0,1}1+3
byte{0,1}83
shortint{0,1}163
int{0,1}323
longint{0,1}643
reg&logicnowthesame:bothpermiteithercontinuous
orproceduralassignment,butnotboth.
Othernewtypesfortwo-valuedfunctionalsimulation.
`ifdefandtypedef Candenealiasesforexistingtypes.Useful,e.g.,for
switchingbetweenfour-andtwo-valuedsimulation:
`ifdef
TWOSTATE
typedef
bitbit_t;
`else
typedef
logicbit_t;
`endif moduledff(
outputbit_tq,
inputbit_td,clk,rst);
always@(posedgeclk)
if(rst)q<=0;
elseq<=d;
endmodule
StructsandUnions SystemVerilogprovidesC-likestructsandunionsinboth
packedandunpackedforms.
typedefstruct
{
logicPARITY;
logic[3:0]ADDR;
logic[3:0]DEST;
}pkt_t;
pkt_tmypkt;
mkpkt.ADDR=12;
Packedvs.Unpacked Structsareunpackedbydefault.Thealignmentoftheir
eldsisimplementation-dependentforefciency,e.g.,
chosenbytheCcompiler.
typedefstruct
{
logicPARITY;
logic[3:0]ADDR;
logic[3:0]DEST;
}pkt_t;
31310
PARITY
ADDR DATA
Packedvs.Unpacked Markingthempackedremovespadding:usefulinunions.
typedefstruct
packed
{
logicPARITY;
logic[3:0]ADDR;
logic[3:0]DEST;
}pkt_t;
85410
DEST
ADDR
PARITY
PackedStructsandUnions typedefstruct
packed
{
logic[15:0]source_port;
logic[15:0]dest_port;
logic[31:0]sequence;
}tcp_t;
typedefstruct
packed
{
logic[15:0]source_port;
logic[15:0]dest_port;
logic[15:0]length;
logic[15:0]checksum;
}udp_t;
typedef
unionpacked
{
tcp_ttcp_h;
udp_tudp_h;
bit[63:0]bits;
bit[7:0][7:0]bytes;
}ip_t;
ip_tip_h;
logicparity;
//allareequivalent ip_h.upd_h.length=5;
ip_h.bits[31:16]=5;
ip_h.bytes[3:2]=5;
tcp_t
source_port
dest_port
sequence
udp_t
source_port
dest_port
length
checksum
OperatorOverloading SystemVerilogprovidesoperatoroverloadingfacilitieslike
thoseinC++throughthebindkeyword.
typedefstruct{
bitsign;
bit[3:0]exponent;
bit[10:0]mantissa;
}float;
bind
+functionfloatfaddfr(float,real);
bind
+functionfloatfaddff(float,
float);
floatA,B,C,D;
assignA=B
+
C;
//meansA=faddff(B,C);
assignD=A
+
1.0;
//meansA=faddfr(A,1.0);
Classes SystemVerilogprovidesC++-likeclasseswithautomatic
garbagecollection.
class
Packet;
bit[3:0]cmd;
intstatus;
header_theader;
functionintget_status();
returnstatus;
endfunction
extern
taskset_cmd(inputbit[3:0]a);
endclass
task Packet::
set_cmd(inputbit[3:0]a);
cmd=a;
endtask
initialbegin
PacketmyPkt=
new
;
//Createanewpacket
end

Inheritance AsinC++,classescaninheritfromotherclasses: classErrPkt
extends
Packet;
bit[3:0]err;
//Newfunction functionbit[3:0]show_err;
returnerr;
endfunction
//OverridesPacket::set
cmd
taskset_cmd(inputbit[3:0]a);
cmd=a+1;
endtask
endclass
Packages package
ComplexPkg;
typedefstruct{
floati,r;
}Complex;
functionComplexadd(Complexa,b);
add.r=a.r+b.r;
add.i=a.i+b.i;
endfunction
functionComplexmul(Complexa,b);
mul.r=(a.r*b.r)+(a.i*b.i);
mul.i=(a.r*b.i)+(a.i*b.r);
endfunction
endpackage
:ComplexPkg
modulefoo(inputbitclk);
importComplexPkg::*; Complexa,b;
always@(posedgeclk)
c=add(a,b);
endmodule
HardwareModeling
Features
always
comb,
latch,and
ff
InRTLdesign,aVerilogalwaysblockmodels
combinationallogic,sequentiallogicdrivingip-ops,or
sequentiallogicdrivinglatches,nevermorethanone.
SystemVerilog'salways
comb,always
ff,andalways
latch
keywordsmakethedesigner'sintentcleartothecompiler
soitcanissueerrormessages.
always
comb,
latch,and
ff
//Probablyintendedcombinational,butcbecomeslatch always@(aorb)
if(b)c=a;
//Error:“missingelsebranch:cisnotassigned” always_comb
if(b)c=a;
//Acorrectlevel-sensitivelatch always_latch
if(clk)
if(en)q<=d;
//Error:“qalwaysassigned:itisnotalatch” always_latch
q<=d
always
comb,
latch,and
ff
Compilerveriescodingstyle. //Correctedge-sensitiveFFwithasynchronousreset always_ff@(posedgeclk,negedgerst_n)
if(!rst_n)q<=0;
elseq<=d;
//Error:sensitivitynotonedges always_ff@(clk,rst_n)
if(!rst_n)q<=0;
elseq<=d;
//Error:combinationallogicloop always_latch
if(en)q<=d;
elseq<=q;
//Error
Unique/Priority Verilog1995hadnoprovisionforcheckinguniquenessof
conditions:synthesistoolsplacedpragmasincomments.
Verilog2001addedattributesforsuchconditionsas
rst-classentities.
SystemVerilogintroducesnewkeywordsimplyingunique
andcompleteconditions.
CasesmustbeConditionmustbe
completeunique
priority3
unique33
PriorityExamples //errorifnoneofirq0–irq2istrue prioritycase(1'b1)
irq0:irq=3'b1<<0;
irq1:irq=3'b1<<1;
irq2:irq=3'b1<<2;
endcase
//errorifnoneofirq0–irq2istrue priorityif(irq0)irq=3'b1;
elseif(irq1)irq=3'b2;
elseif(irq2)irq=3'b4;
//Defaultorelseignorespriority
//Thisneverraisesanerror:
priorityif(irq0)irq=3'b1;
elseirq=3'b0;
//Nordoesthis: prioritycase(1'b1)
irq0:irq=3'b1<<0;
default:irq=0;
endcase
UniqueExamples //Errorifnotexactlyoneofirq0±irq2istrue uniquecase(1'b1)
irq0:irq=3'b1<<0;
irq1:irq=3'b1<<1;
irq2:irq=3'b1<<2;
endcase
//Errorifnotexactlyoneofirq0±irq2istrue uniqueif(irq0)irq=3'b1;
elseif(irq1)irq=3'b2;
elseif(irq2)irq=3'b4;
//Errorifbothirq0andirq1aretrue uniqueif(irq0)irq=3'b1;
elseif(irq1)irq=3'b2;
elseirq=3'b0;
//Errorifbothirq0andirq1aretrue: uniquecase(1'b1)
irq0:irq=3'b1<<0;
irq1:irq=3'b1<<1;
default:irq=0;
endcase

Implicitly-namedports HierarchyinVerilogusuallyforseparatingnamespaces.
Netandportnamestypicallycommonacrossmodules.
VerboseinVerilog1995: moduletop;
wire[3:0]a;
wire[7:0]b;
wire[15:0]c;
foofoo1(a,b,c);
barbar1(a,b,c);
endmodule
modulefoo(a,b,c);
input[3:0]a;
input[7:0]b;
input[15:0]c;
endmodule
modulebar(a,b,c);
outputa;
outputb;
outputc;
reg[3:0]a;
reg[7:0]b;
reg[15:0]c;
endmodule
Implicity-namedPorts ImplicitportsplusANSI-styledeclarationsmakesthis
cleaner,especiallyformoduleswithmanyports. moduletop;
wire[3:0]a;
wire[7:0]b;
wire[15:0]c;
foofoo1(
.*
);
barbar1(.*
);
endmodule
modulefoo(
input[3:0]a,
input[7:0]b,
input[15:0]c);
endmodule
modulebar(
outputreg[3:0]a,
outputreg[7:0]b,
outputreg[15:0]c);
endmodule
Implicity-namedPorts Portrenamingalsosupported.Allowsspecicportstobe
overriddenorrenamedasnecessary. moduletop;
wire[3:0]a;
wire[7:0]b;
wire[15:0]c;
foofoo1(.*);
barbar1(.*,
.other(c)
);
endmodule
modulefoo(
input[3:0]a,
input[7:0]b,
input[15:0]c);
endmodule
modulebar(
outputreg[3:0]a,
outputreg[7:0]b,
outputreg[15:0]
other
);
endmodule
Interfaces Forcommunicationamongmodules.Likeacollectionof
sharedvariables.
interface
simple_bus;
logicreq,gnt;
logic[7:0]addr,data;
logic[1:0]mode;
logicstart,rdy;
endinterface:simple_bus
moduletop;
logicclk=0;
simple_busmybus;
memorymem(mybus,clk);
cpucpu(.b(mybus),
.clk(clk));
endmodule
modulememory(
simple_bus
a,
inputbitclk);
always@(posedgeclk)
a.gnt<=a.req&avail;
...
endmodule
modulecpu(simple_busb,
inputbitclk);
...
endmodule
Interfaceswithimplicitports Evenmoresimple.Usethesamenamesandletthe
compilerdotherest.
interface
simple_bus;
logicreq,gnt;
logic[7:0]addr,data;
logic[1:0]mode;
logicstart,rdy;
endinterface:simple_bus
moduletop;
logicclk=0;
simple_busbus;
memorymem(.*);
cpucpu(.*);
endmodule
modulememory(
simple_busbus,
inputbitclk);
always@(posedgeclk)
bus.gnt<=bus.req&av;
...
endmodule
modulecpu(simple_busbus,
inputbitclk);
...
endmodule
Genericbundles Youcanleavetheexacttypeofaninterfaceunspeciedto
allowdifferentimplementations.Mustconnectexplicitly. interfacesimple_bus;
logicreq,gnt;
logic[7:0]addr,data;
logic[1:0]mode;
logicstart,rdy;
endinterface:simple_bus
moduletop;
logicclk=0;
simple_busbus;
memorymem(.*,
.bus(bus)
);
cpucpu(.*,
.bus(bus)
);
endmodule
modulememory(
interface
bus,
inputbitclk);
always@(posedgeclk)
bus.gnt<=bus.req&av;
...
endmodule
modulecpu(
interface
bus,
inputbitclk);
...
endmodule
Portsoninterfaces Interfacesaregroupsofsharedvariables.Portson
interfacescanbringconnectionsinorout. interfacebus(
inputbitclk,
outputbitbus_error
);
logicreq,gnt;
logic[7:0]addr,data;
logic[1:0]mode;
logicstart,rdy;
endinterface:bus
moduletop;
logicclk=0,bus_error;
busb(clk,bus_error);
memorymem(.*);
cpucpu(.*);
endmodule
modulememory(busb);
always@(posedge
b.clk
)
b.gnt<=b.req&av;
...
endmodule
modulecpu(busb);
always@(posedgeb.clk)
b.bus_error<=
cpu_error;
...
endmodule
Modportsininterfaces Awaytoconstrainsignaldirectionsininterfaces. interfacebus(
inputbitclk);
logicreq,gnt,rdy;
logic[7:0]addr,data;
modport
slave(
input
req
,addr,clk,
outputgnt
,rdy,
inoutdata);
modport
master(
outputreq,addr,
inputgnt,rdy,clk,
inoutdata)
endinterface:bus
moduletop;
logicclk=0;
busb(clk);
memorymem(.*);
cpucpu(.*);
endmodule
modulememory(
bus.slave
b);
always@(posedgebus.clk)
b.gnt
<=
b.req
&av;
...
endmodule
modulecpu(
bus.master
b);
...
endmodule
TasksandFunctionsinInterfaces interfacebus;
logicstart;
task
slaveRead(
inputlogic[7:0]addr);
...
endtask:slaveRead task
masterRead(
inputlogic[7:0]addr);
...
endtask:masterRead
modportslave(
importtask
slaveRead(
inputlogic[7:0]addr);
);
endinterface:bus
modulememory(interfaceb);
logic[7:0]addr;
always@(posedgeb.clk)
b.
slaveRead
(addr);
endmodule
moduleomnip(interfaceb);
always@(posedgeb.clk)
b. masterRead
(addr);
always@(posedgeb.clk)
b.
slaveRead
(addr);
endmodule
moduletop;
busb;
//caninvokeslaveReadonly memorym(b.slave); //canuseslaveRead,masterRead omnipo(b);
endmodule

Dynamically-sizedArrays Trulysoftware-likebehavior. moduledynamic_array;
bit[3:0]myarray
[]
;
//Createsnullreference
initialbegin
myarray=new[4];
//Allocatefour4-bitwords
//Doublethesizeofthearray,preservingitscontents
myarray=new[myarray.size()*2](myarray);
end
endmodule
AssociativeArrays Veryabstractnotion.LikemapsinC++,hashtablesin
Java,orassociativearraysinPerl,Python,Awk. moduleassociative_array;
typedefstructpacked{
inta;
logic[7:0]b;
}mykey_t;
intmyarray[mykey_t];
//new,emptyassociativearray
initialbegin
mykey_tkey1={-3,8'xFE};
//structureliteral
myarray[key1]=10;
if(myarray.exists(key1))
myarray[key1]=-5;
myarray.delete(key1);
end
endmodule
Queues Oftenusedtocommunicatebetweenprocesses. modulequeues;
intq[$]={2,4,8};
//initialcontents
intsq[$:15];
//maximumsizeis16
initialbegin
inte=q[0];
//®rstitem:2
e=q[$];
//lastitem:8
q={q,6};
//append:now2,4,8,6
q={e,q};
//insert:now8,2,4,8,6
q=q[1:$];
//remove:now2,4,8,6
q=q[1:$-1];
//delete®rst,last:now4,8
end
endmodule
ProcessManagement:join Forkstartsprocesses;jointerminateswhenallblocks
terminate. fork
begin
$display("0nshaveelapsed");
#20ns;
//delay
end
begin
#20ns;
$display("20nshaveelapsed");
#5ns;
end
join #5ns;
$display("30nshaveelapsed");
ProcessManagement:join
any
Forkstartsprocesses;join
anyterminateswhenanyofits
blocksterminate.
fork
begin
$display("0nshaveelapsed");
#20ns;
//delay
end
begin
#20ns;
$display("20nshaveelapsed");
#5ns;
end
join_any #5ns;
$display("25nshaveelapsed");
ProcessManagement:join
none
Forkstartsprocesses;join
noneterminatesimmediately,
leavingitsblocksrunning.
fork
begin
$display("0nshaveelapsed");
#20ns;
//delay
end
begin
#20ns;
$display("20nshaveelapsed");
#5ns;
end
join_none #5ns;
$display("5nshaveelapsed");
ProcessManagement:waitfork waitforkwaitsforallchildrentoterminate. taskwait_fork_demo;
fork
task1();
//starttask1andtask2concurrently
task2();
join_any
//terminateswheneithertask1ortask2does
fork
task3();
//starttask3andtask4concurrently
task4();
join_none; //task3andtask4andeithertask1ortask2running waitfork;
//waitforalltocomplete
endtask
ProcessManagement:disablefork disableforkterminatesallitschildren. taskwait_for_first(outputintadr);
fork
wait_device(1,adr);
//user-de®nedtaskthatwaits
wait_device(7,adr);
//allthreestartedconcurrently
wait_device(13,adr);
join_any
//terminatewhenonehasarrived
disablefork
;
//terminateothertwo
Processcontrol taskrun_n_jobs_and_terminate_after_first(intN);
process
job[1:N];
//Theprocesseswespawn
for(intj=1;j<=N;j++)
fork
automaticintk=j;
//foreachjob,kisitsnumber
begin
job[j]=
process::self
();
//recordwhoIam
...
//thejobitself
end
join_none
//spawnnextjobimmediately
for(intj=1;j<=N;j++)
wait(job[j]!=null);
//waitforjobstostart
job[1].await();//waitfor®rstjobto®nish
for(intk=1;k<=N;k++)begin
if(
job[k].status
!=
process::FINISHED
)
//ifnot®nished,
job[k].kill()
;
//killit
end
endtask

Semaphores Mutually-exclusivekeysinabucket.getblocksifnot
enoughkeysareavailable. semaphorewe_are_there=new;
//initializewithnokeys
taskdrive;
fork
begin
#100ns;
//delay100ns
we_are_there.put(1)
;
//putasinglekeyinthesemaphore
end
begin
$display("Arewethereyet?");
we_are_there.get(1)
;
//waitforakey
$display("Wemadeit");
end
join
endtask
Semaphoresandevents eventask,answered;
semaphoreanswer=new;
intwinner;
//onlyvalidafteranswer
taskgameshow;
fork
begin
//thehost
->ask
;
//Startthetwocontestants
answer.put(1);
//letthemcompete
@answered
;$display("%dwasfirst",winner);
end
begin
//contestantone
@ask
;
//waitforthequestion
think_about_answer();answer.get(1);
//trytoanswer®rst
winner=1;
->answered
;
//signaloursuccess
end
begin
//contestanttwo
@ask;
think_about_answer();answer.get(1);
winner=2;->answered;
end
join
//Doesthisbehaveproperly?
endtask
Mailboxes Possiblyboundedsemaphore-likequeues. mailbox#(string)mybox=new(2);
//capacitysettotwo
taskmailbox_demo;
fork
begin
mybox.put("firstletter");
$display("sentfirst");
mybox.put("secondletter");
$display("sentsecond");
mybox.put("thirdletter");
$display("sentthird");
end
begin
$display("got%s",mybox.get);
$display("got%s",mybox.get);
$display("got%s",mybox.get);
end
join
endtask
Prints
sentrst
sentsecond
gotrstletter
gotsecondletter
sentthird
gotthirdletter
Veri®cationFeatures
ConstrainedRandomVariables Manuallycreatingtestcasestediousanddifcult,yet
appearsnecessaryforfunctionalverication.
Currentbestpractice:Constrainedrandomtests.
SystemVeriloghasfeaturesforcreatingsuchtests.
ConstrainedRandomVariables classBus;
randbit[15:0]addr;
randbit[31:0]data;
constraint
world_align{addr[1:0]=2'b0;}
endclass
Busbus=new;
repeat(50)begin
if(bus.
randomize()
==1)
$display("addr=%16hdata=%h",
bus.addr,bus.data);
else
$display("overconstrained:nosatisfyingvalues
exist");
end
Addingconstraints classBus;
randbit[15:0]addr;
randbit[31:0]data;
constraint
world_align{addr[1:0]=2'b0;}
endclass
Busbus=new;
repeat(50)begin
if(bus.
randomize()with{addr[31]==0}
==1)
$display("addr=%16hdata=%h",
bus.addr,bus.data);
else
$display("overconstrained:nosatisfyingvalues
exist");
end
Layeringconstraints Constraintsinherited,canbeaddedinderivedclasses. classBus;
randbit[15:0]addr;
randbit[31:0]data;
constraint
world_align{addr[1:0]=2'b0;}
endclass
typdefenum{low,mid,high}AddrType;
classMyBus
extendsBus
;
randAddrTypeatype;
//Additionalrandomvariable
//Additionalconstraintonaddress:stillword-aligned
constraintaddr_range{
(atype==low)->addrinside{[0:15]};
(atype==mid)->addrinside{[16:127]};
(atype==high)->addrinside{[128:255]};
}
endclass
UsingConstraints Verypowerfulconstraintsolvingalgorithm. taskexercise_bus;
intres;
//Restricttolowaddresses res=bus.randomize()with{atype==low;}; //Restricttoparticularaddressrange res=bus.randomize()
with{10<=addr&&addr<=20};
//Restrictdatatopowersoftwo res=bus.randomize()with{data&(data-1)==0}; //Disablewordalignment bus.word_align.
constraint_mode(0)
;
res=bus.randomizewith{addr[0]||addr[1]};
//Re-enablewordalignment bus.word_align.
constraint_mode(1)
;
endtask

Othertypesofconstraints //Setmembershipconstraints randintegerx,y,z;
constraintc1{xinside{3,5,[9:15],[y:2*y],z};}
integerfives[0:3]={5,10,15,20};
randintegerv;
constraintc2{vinsidefives;}
//Distributionconstraints randintegerw; //makew1001/8oftime,2002/8,3005/8 constraintc3{wdist{100:=1,200:=2,300:=5};} //Implicationconstraints bit[3:0]a,b; //forcebto1whenais0 constraintc4{(a==0)->(b==1);}
Many,manymorefeatures Variablesthatstepthroughrandompermutations(randc)
If-then-elseconstraints
Algorithmicconstraintsoverarrayentries(foreach)
Constraintsamongmultipleobjects
Variableorderingconstraints(solve..before)
Staticconstraintscontrolledbyoneconstraint
mode()call
Functionsinconstraints
Guardedconstraints
pre-andpost-randomizefunctions
Randomvariabledisabling
Explicitrandomizationofarbitraryvariables
Randomsequencegenerationfromagrammar
CoverageChecks Oncewehavegeneratedourtests,howgoodarethey?
Currentbestpractice:monitoringandimprovingcoverage
Coverage:howmanycases,statements,values,or
combinationshavethetestcasesexercised?
Covergroup Denessomethingwhosecoverageistobechecked.
Createsbinsandtrackswhethervalueseverappeared.
//color:athree-valuedvariablewhosecoverageistobechecked enum{red,green,blue}
color
;
covergroup
g1@(posedgeclk);
//Sampleatposedgeclk
c:
coverpoint
color;
endgroup
g1g1_inst=new;
//Createthecoverageobject
Attheendofsimulation,reportswhethercolortookall
threeofitsvalues.
CrossCoverage Maywanttomonitorcombinationsofvariables. enum{red,green,blue}color;
bit[3:0]pixel_adr,pixel_offset;
covergroupg2@(posedgeclk);
Hue:coverpointpixel_hue;
Offset:coverpointpixel_offset;
//Consider(color,pixel
adr)pairs,e.g.,
//(red,3'b000),(red,3'b001),...,(blue,3'b111)
AxC:
cross
color,pixel_adr;
//Consider(color,pixel
hue,pixel
offset)triplets
//Creates3*16*16=768bins
all:
cross
color,Hue,Offset;
endgroup
g2g2_inst=new;
//Createawatcher
Covergroupinclasses Individualcoverageofeachobjectofaclass. classxyz;
bit[3:0]x;
inty;
bitz;
covergroupcov1@z;
//Ateverychangeofz,
coverpointx;
//samplex
coverpointy;
//andsampley.
endgroup
functionnew();
cov1=new;
//Createawatcher;variablecov1implicit
endfunction
endclass
Predicatedcoverage Maywanttoselectivelydisablecoverage: covergroupg4@(posedgeclk);
//checks0onlyifresetistrue coverpoints0iff(!reset);
endgroup
User-denedbins Mayonlywanttotrackcertainvaluesofavariable. bit[9:0]a;
//Takesvalues0±1023
covergroupcg@(posedgeclk);
coverpointa{
//placevalues0±63and65inbina binsa={[0:63],65}; //create65bins,onefor127,128,...,191 binsb[]={[127:150],[148:191]}; //createthreebins:200,201,and202 binsc[]={200,201,202}; //placevalues1000±1023inbind binsd={[1000:$]}; //placeallothervalues(e.g.,64,66,..,126,192,...)intheirownbin binsothers[]=default;
}
endgroup
CoveringTransitions Maywanttochecktransitions,notjustavariable'svalues. bit[3:0]a;
covergroupcg@(posedgeclk);
coverpointa{
//Placeanyofthesequences4!5!6,7!11,8!11,9!11,10!11,
//7!12,8!12,9!12,and10!12intobinsa.
binssa=(4=>5=>6),([7:9],10=>11,12); //Createseparatebinsfor4!5!6,7!10,8!10,and9!10 binssb[]=(4=>5=>6),([7:9]=>10); //Lookforthesequence3!3!3!3 binssc=3[*4]; //Lookforanyofthesequences5!5,5!5!5,or5!5!5!5 binssd=5[*2:4]; //Lookforanysequenceoftheform6!!6!!6
//whereªºrepresentsanysequencethatexcludes6
binsse=6[->3];
}
endgroup

Assertions Wehavegeneratedourtests,theydoareasonablejob
coveringthedesign,buthowdowendproblems?
Currentbestpractice:Addassertionstothedesignthat
checkforunwantedconditions.
Currently,themosteffectivewaytoreducedebugging
time:bugsfoundmorequickly,andeasiertoremedy.
Longusedinsoftware,growinguseinhardware.
Mainchallengeinhardware:assertingtemporalbehavior.
SystemVeriloghasconstructsspecicallyforchecking
sequencesofthings.
ImmediateAssertions Simplestassertionscheckanconditiononlywhenthey
areexecuted.
//Makesurereq1orreq2istrueifweareintheREQstate always@(posedgeclk)
if(state==REQ)
assert(req1||req2);
//Same,butreporttheerrorourselves always@(posedgeclk)
if(state==REQ)
assert(req1||req2)
else
$error("InREQ;req1||req2failed(%0t)",$time);
ConcurrentAssertions Concurrentassertionscheckapropertythatspanstime.
Datasampledataclockandobservedsequencechecked.
Forexample,sayweinsistthatackmustbeasserted
betweenoneandthreecyclesafterreqisasserted.
property
req_ack;
@(posedgeclk)
//Samplereq,ackatrisingclockedge
//Afterreqistrue,betweenoneandthreecycleslater,
//ackmusthaverisen.
req##[1:3]$rose(ack);
endproperty
//Assertthatthispropertyholds,i.e.,createachecker as_req_ack:
assertproperty
(req_ack);
ConcurrentAssertions Anotherexample:makesuretheaddressstrobeisnot
truefortwoconsecutivecycles. propertyno_two_astr;
@(posedgeclk)
//Unlessresetistrue,makesureastris
//nottruefortwocyclesinarow.
disableiff
(reset)not(astr
[*2]
);
endproperty
assertproperty(no_two_astr);
//Non-overlappingimplication|=>waitsacycle propertyno_two_astr2;
@(posedgeclk)
disableiff(reset)
(astr
|=>
!astr);
//Whenastristrue,astrisfalsenextcycle.
endproperty
assertproperty(no_two_astr2);
SequencesandProperties Sequencescanbedenedinisolationandused
elsewhere.
//Theown
bussignalgoeshighin1to5cycles,
//thenthebreqsignalgoeslowonecyclelater.
sequenceown_then_release_breq;
##[1:5]
own_bus
##1
!breq
endsequence
propertylegal_breq_handshake;
@(posedgeclk)
//Oneveryclock,
disableiff(reset)
//unlessresetistrue,
//oncebreqhasrisen,own
busshouldriseandbreqshouldfall.
$rose(breq)
|->
own_then_release_breq;
endproperty
assertproperty(legal_breq_handshake);
Sequences(partialsyntax) seq:=
exprExpressionoversignals
expr[*int-or-range]Consecutiverepetition
expr[=int-or-range]Non-consecutiverepetition
expr[->int-or-range]Gotorepetition
seq##int-or-rangeseq...Delaybetweensequences
seqorseqEithertrue
seqandseqBothtrue
seqintersectseqBothtrue,endsimultaneously
seqwithinseqSecondstarts/endswithinrst
Properties(partialsyntax) prop:=
seqSequence
proporpropEitherholds
propandpropBothhold
notpropDoesnothold
seq|->propPropholdswhensequenceends
seq|=>propPropholdscycleaftersequenceends
if(expr)prop
[elseprop]If-then-else
SystemVerilog:Summary Hugelanguagethatreectschangingdesign
methodologies:
Switch-levelcharge-transfermodeling(deprecated)
Gate-levelstructuralmodeling
RTLmodeling
High-levelsoftware-likemodeling
Assertions,randomsimulation,andcoverage
Willitsucceed? Maybe.
Substantialindustrialsupport(Cadence,Synopsys).
MoreofanincrementalchangethanSystemC.
Reasonable,fairlyclear,synthesizablesubset.
Verilog,withallitsaws,hasprovenitsworth.
Largelanguage,butstillfairlysuccinct.
Doesitsupporttherightsetofmethodologies?