Verilog and SystemVerilog Gotchas - download.e-bookshelf.de · Verilog and SystemVerilog Gotchas...

23
Verilog and SystemVerilog Gotchas 101 Common Coding Errors and How to Avoid Them

Transcript of Verilog and SystemVerilog Gotchas - download.e-bookshelf.de · Verilog and SystemVerilog Gotchas...

Verilog and SystemVerilogGotchas101 Common CodingErrors and How toAvoid Them

Stuart SutherlandDon Mills

Verilog and SystemVerilogGotchas101 Common Coding Errors and How toAvoid Them

~ Springer

StuartSutherlandSutherland HDL, Inc.Tualatin, ORUSA

Don MillsLCDM EngineeringChandler, AZUSA

Libraryof CongressControlNumber: 2007926706

ISBN978-0-387-71714-2

Printedon acid-freepaper.

e-ISBN978-0-387-71715-9

© 2007SpringerScience+Business Media,LLCAll rights reserved. This work may not be translated or copied in whole or in part withoutthe writtenpermissionof the publisher(SpringerScience-BusinessMedia,LLC,233 SpringStreet,New York, NY 10013,USA),except for brief excerptsin connection with reviews orscholarly analysis. Use in connection with any form of information storage and retrieval,electronic adaptation, computer software, or by similar or dissimilar methodology nowknow or hereafter developed is forbidden. The use in this publication of trade names,trademarks, servicemarksand similar terms, even if they are not identifiedas such, is not tobe taken as an expression of opinion as to whether or not they are subject to proprietaryrights.

9 8 7 6 5 432 1

springer.com

Dedication

To my wonderful wife, LeeAnn, and my children, Ammon, Tamara, Hannah, SethandSamuel- thankyoufor yourpatienceduringthe many longhoursand latenightsyou toleratedwhile this bookwas beingwritten.

StuSutherlandPortland, Oregon

To my wifeandsweetheart GeriJean, and my children, Sara, Kirsten, Adam, Alex,Dillan, Donnelle, Grantand Gina- thanks to eachofyoufor thepatienceyou havehadwithme as I havedealtwithdebugging manyofthesegotchason designs overtheyears.

Don MillsChandler, Arizona

About the Authors

Mr. Stuart Sutherland is a member of the IEEE 1800 workinggroup that oversees both the Verilog and SystemVerilogstandards. He has been involved with the definition of theVerilog standard since its inception in 1993, and theSystemVerilog standard since work began in 200I. In addition,Stuart is the technical editor of the official IEEE Verilog andSystemVerilog Language Reference Manuals (LRMs). Stuart isan independent Verilog consultant, specializing in providing

comprehensive expert training on the Verilog HDL, SystemVerilog and PLI.Stuart is a co-authorof the books "SystemVerilog for Design", "Verilog-2001: AGuide to the New Features in the Verilog Hardware Description Language" andis the author of "The Verilog PLl Handbook", as well as the popular "VerilogHDL Quick Reference Guide" and"Verilog PLl QuickReference Guide". He hasalsoauthored a number of technical papers on Verilog and SystemVerilog, whichare available at www.sutherland-hdl.com/papers. You can contact Stuart [email protected].

visit the authorswebpage at www.sutherland-hdl.com

Mr. Don Mills has been involved in ASIC design since 1986.During that time, he has worked on morethan 30 ASIC projects.Don started using top-down design methodology in 1991(Synopsys Design Compiler 1.2). Don has developed andimplemented top-down ASIC design flows at several companies.His specialty is integrating tools and automating the flow. Donworks for Microchip Technology Inc. as an internalSystemVerilog and Verilog consultant. Don is a member of the

IEEE Verilog and System Verilog committees that are working on languageissues and enhancements. Don has authored and co-authored numerous papers,such as "SystemVerilog Assertions are for Design Engineers Too!" and "RTLCoding Styles that Yield Simulation and Synthesis Mismatches". Copies of thesepapers can be found at www.lcdm-eng.com.Mr. Mills can be reached [email protected] [email protected].

visit the authorswebpage at www.lcdm-eng.com

Acknowledgments

The authors express their sincere appreciation to the contributions of severalVerilog and SystemVerilog experts.

Chris Spear of Synopsys, Inc. suggested several of the verification relatedgotchas, provided the general descriptions of these gotchas, and ran countlesstests forus.

Shalom Bresticker of Intelalsosuggested several gotchas.

Jonathan Bromley of Doulos, Ltd., Clifford Cummings of Sunburst Design,Tom Fitzpatrick of Mentor Graphics, Steve Golson of Trilobyte Systems, GreggLahti of Microchip Technology, Inc. and Chris Spear of Synopsys, Inc. providedthorough technical reviews of this book, and offered invaluable comments onhowto improve the gotcha descriptions.

Steve Golson of Trilobyte Systems provided a wonderful foreword to thisbook

Lastly, we acknowledge and express our gratitude to our wives, LeeAnnSutherland and Geri Jean Mills, for meticulously reviewing this book forgrammar and punctuation. If any sucherrataremain in the book, it could onlybedue to changes we madeaftertheirreviews.

Table ofContents

List of Gotchas...•••.••..•....•••....•..•.•..•..••.....•...••..•.........••................•..•.........•..•.............•..... xv

Forewordby SteveGolson...••..•.......••...•......................•.....•...................•.................•..••................•.•.•. 1

Chapter 1:Introduction,What Is A Gotcha? 3

Chapter 2:Declaration and Literal Number Gotchas 7

Gotcha 1: Case sensitivity 7

Gotcha 2: Implicitnet declarations 10

Gotcha 3: Default of l-bit internal nets 13

Gotcha4: Single file versus multi-file compilation of $unit declarations 15

Gotcha 5: Local variable declarations 17

Gotcha6: Escapednames in hierarchical paths 19

Gotcha 7: Hierarchical references to automatic variables 22

Gotcha 8: Hierarchical references to variables in unnamedblocks 25

Gotcha9: Hierarchical references to importedpackage items 27

Gotcha 10: Importingenumerated types from packages 28

Gotcha 11: Importingfrom multiplepackages 29

Gotcha 12: Default base of literal integers 30

Gotcha 13: Signedness of literal integers 32

Gotcha 14: Signed literal integerszero extend to their specifiedsize 33

Gotcha 15: Literal integer size mismatch in assignments 35

Gotcha 16: Filling vectorswith all ones 37

Gotcha 17: Array literalsversusconcatenations 38

Gotcha 18: Port connectionrules 39

Gotcha 19: Back-driven ports 43

Table of Contents

Gotcha 20: Passing real (floating point)numbers through ports 46

Chapter 3:RTL Modeling Gotchas 49

Gotcha21: Combinational logicsensitivity listswith function calls 49

Gotcha22: Arrays in sensitivity lists 52

Gotcha23: Vectors in sequential logicsensitivity lists 54

Gotcha24: Operations in sensitivity lists 56

Gotcha25: Sequential logicblocks withbegin end groups 57

Gotcha26: Sequential logicblockswith resets 59

Gotcha 27: Asynchronous set/reset flip-flop for simulation and synthesis 60

Gotcha28: Blocking assignments in sequential procedural blocks 62

Gotcha29: Sequential logicthat requires blocking assignments 64

Gotcha30: Nonblocking assignments in combinational logic 66

Gotcha31: Combinational logicassignments in the wrongorder 70

Gotcha32: Casez/casex masksin caseexpressions 72

Gotcha33: Incomplete decision statements 74

Gotcha34: Overlapped decision statements 77

Gotcha35: Inappropriate use of unique casestatements 79

Gotcha36: Resetting 2-statemodels 82

Gotcha 37: Lockedstatemachines modeled with enumerated types 84

Gotcha38: Hidden design problems with4-statelogic 86

Gotcha39: Hiddendesign problems using2-statetypes 88

Gotcha40: Hidden problems with out-of-bounds arrayaccess 90

Gotcha 41: Out-of-bounds assignments to enumerated types 92

Gotcha 42: Undetected sharedvariables in modules 94

Gotcha43: Undetected sharedvariables in interfaces and packages 96

Chapter 4:Operator Gotchas 99

Gotcha 44: Assignments in expressions 99

Gotcha 45: Self-determined versuscontext-determined operators 101

Gotcha46: Operation sizeand sign extension in assignment statements 105

Gotcha47: Signedarithmetic rules 108

xii

Table of Contents

Gotcha 48: Bit-select and part-select operations 111

Gotcha 49: Increment, decrement and assignment operators 112

Gotcha 50: Pre-increment versuspost-increment operations 113

Gotcha 51: Modifying a variable multiple times in one statement 115

Gotcha52: Operator evaluation shortcircuiting 116

Gotcha53: The not operator( ! ) versus the invertoperator( -- ) 118

Gotcha54: Arraymethod operations 119

Gotcha 55: Arraymethod operations on an arraysubset. 121

Chapter 5:General Programming Gotchas 123

Gotcha56: Verifying asynchronous and synchronous reset at time zero 123

Gotcha57: Nestedif else blocks 128

Gotcha 58: Evaluation of equality with4-statevalues 129

Gotcha 59: Eventtriggerrace conditions 131

Gotcha60: Usingsemaphores for synchronization 134

Gotcha 61: Usingmailboxes for synchronization 137

Gotcha 62: Triggering on clocking blocks 139

Gotcha 63: Misplaced semicolons afterdecision statements 140

Gotcha 64: Misplaced semicolons in for loops ~ 142

Gotcha65: Infinitefor loops 144

Gotcha 66: Lockedsimulation due to concurrent for loops 145

Gotcha 67: Referencing for loopcontrol variables 147

Gotcha68: Defaultfunction returnsize 148

Gotcha69: Task/function arguments with defaultvalues 150

Gotcha70: Continuous assignments with delays cancel glitches 151

Chapter 6:Object Oriented and Multi-Threaded Programming Gotchas 153

Gotcha 71: Programming statements in a class 153

Gotcha 72: Using interfaces with object-oriented testbenches 155

Gotcha 73: All objects in mailbox comeout with the samevalues 157

Gotcha 74: Passing handles to methods using inputversus ref arguments 158

Gotcha 75: Constructing an arrayof objects 159

xiii

Table of Contents

Gotcha 76: Statictasksand functions are not re-entrant 160

Gotcha 77: Staticversus automatic variable initialization 162

Gotcha 78: Forkedprogramming threads needautomatic variables 164

Gotcha 79: Disable forkkills too manythreads 166

Gotcha 80: Disabling a statement blockstopsmorethan intended 168

Gotcha 81: Simulation exitsprematurely, beforetestscomplete 171

Chapter 7:Randomization, Coverage and Assertion Gotchas 173

Gotcha 82: Variables declared withrandare not getting randomized 173

Gotcha 83:Undetected randomization failures 175

Gotcha 84: $assertoffcoulddisable randomization 177

Gotcha 85: Boolean constraints on more than tworandom variables 179

Gotcha 86: Unwanted negative values in random values 181

Gotcha 87: Coverage reports default to groups, not bins 182

Gotcha 88: Coverage is always reported as 0% 184

Gotcha 89: The coverage reportlumps all instances together 186

Gotcha 90: Covergroup argument directions are sticky 187

Gotcha 91: Assertion passstatements execute witha vacuous success 188

Gotcha 92: Concurrent assertions in procedural blocks 190

Gotcha 93: Mismatch in assert else statements 192

Gotcha 94: Assertions that cannot faiI. 193

Chapter 8:Tool Compatibility Gotchas 195

Gotcha 95: Defaultsimulation timeunitsand precision 195

Gotcha 96: Package chaining 198

Gotcha 97: Random number generator is not consistent across tools 200

Gotcha 98: Loading memories modeled withalways_latchlalways_ff 202

Gotcha 99: Non-standard language extensions 204

Gotcha 100:Array literals versus concatenations 206

Gotcha 101 :Module portsthat passfloating pointvalues (real types) 208

Index •.••••..••.•..•••.••..•.•••••••••••••..••.••••.•....•••..•.••..••.••••.••.•..•..••.......•...•••.•.••.•.••..•••....•••..•...••. 209

xiv

List ofGotchas

Gotcha 1: 7The names in my code look correct and worked in my VHDL models, butVerilog/System Verilog gets errors about "undeclared identifiers ''.

Gotcha 2: 10A typo in my design connections was not caught by the compiler, and onlyshowedup as afunctional problemin simulation.

Gotcha 3: 13In my netlist, only bit zero ofmy vectorports get connected.

Gotcha 4: 15My models compile OK, and the modelsfrom anothergroup compile OK; butwhencompiledtogether, I get errorsaboutmultiple declarations.

Gotcha 5: 17I get compilation errorson my localvariable declarations, but the declarationsyntax is correct.

Gotcha 6: 19I get weird compiler errors when I try to reference a design signal with anescapednamefrom my testbench.

Gotcha 7: 22I get compilation errorswhenmy testbench tries toprint outsomesignalsin mydesign, but othersignalscan beprinted withouta problem.

Gotcha 8: 25With Verilog, my testbench couldprintout localvariables in a begin endblock,but with SystemVerilog I get compilation errors.

Gotcha 9: 27My design can use importedpackage itemsjust fine, but my testbench cannotaccess the itemsfor verification.

Gotcha 10: 28I importedan enumerated typefrom a package, but I cannot access the labelsdefinedby the enumerated type.

Gotcha 11: 29I get errorswhenI try to wildcardimportmultiplepackages, but I can wildcardimporteachpackageseparately withoutany errors.

Listof Gotchas

Gotcha 12: 30Some branches ofmy case statement are neverselected, even with the correctinputvalues.

Gotcha 13: 32My lncrementor modelsometimes gets incorrect values when I increment usinga literal1 'b1.

Gotcha 14: 33When I specifya signed, sized literalinteger with a negative value, it does notsign extend.

Gotcha 15: 35When I assign a 4-bit negative value to an 8-bit signed variable, it is not signextended.

Gotcha 16: 37I can use a literal integerto set all bits to Z on a vectorofany size, but when Iuse the samesyntaxto set all bits to 1, I get a decimal 1 instead.

Gotcha 17: 38The wrongvalues arestoredwhenI assign a listofvalues to a packedarrayorstructure.

Gotcha 18: 39My design doesn't workcorrectly when I connect all the modules together, buteachmodule workscorrectly by itself.

Gotcha 19: 43I declaredmy port as an input, and software tools let me accidentally use theport as an output, without any errors or warnings.

Gotcha 20: 46I cannotfind a way topass realvalues from onemodule to anotherusingeitherVerilog or System Veri/og.

Gotcha 21: 49My combinational logic seemedto simulate OK, but after synthesis, the gate­levelsimulation doesnot matchthe RTLsimulation.

Gotcha 22: 52I need my combinational logic block to be sensitive to all elements ofa RAMarray, but the sensitivity list won't triggerat the correcttimes.

Gotcha 23: 54My always block is supposedto triggeron anypositiveedge in a vector, but itmisses mostedges.

xvi

Listof Gotchas

Gotcha 24: 56My sensitivity list should trigger on any edge of a or b, but it misses somechanges.

Gotcha 25: 57The clocked logic in my sequential block gets updated, even when no clockoccurred.

Gotcha 26: 59Someofthe outputs ofmy sequential logicdo not get reset.

Gotcha 27: 60When I code an asynchronous set/reset D-type flip-flop following synthesiscodingrules, mysimulation results are sometimes wrong.

Gotcha 28: 62Myshift register sometimes doesa double shift in one clockcycle.

Gotcha 29: 64I'm following the recommendations for using nonblocking assignments insequential logic, butI still haveraceconditions in simulation.

Gotcha 30: 66MyRTLsimulation locksup and timestopsadvancing.

Gotcha 31: 70Simulation ofmygate-level combinational logicdoesnotmatch RTLsimulation.

Gotcha 32: 72Mycasexstatement is takingthewrongbranch whenthereis anerrorinthecaseexpression.

Gotcha 33: 74Myfull_case, parallel_case decision statement simulatedas I expected, but thechipdoesnot work.

Gotcha 34: 77Oneofmy decision branches nevergets executed.

Gotcha 35: 79I am using uniquecase everywhere to help trap design bugs but my synthesisresults are not whatI expected.

Gotcha 36: 82My design fails to reset thefirst time in RTL simulation.

Gotcha 37: 84Mystate machine modellocksup in its start-up state.

xvii

Listof Gotchas

Gotcha 38: 86There wasaproblemdeep insidethe logicofmy design, but it neverpropagatedto moduleboundaries.

Gotcha 39: 88Some majorfunctional bugs in my design did not show up untilaftersynthesis,whenI ran gate-levelsimulations.

Gotcha 40: 90A design bugcausedreferences to nonexistent memoryaddresses, but therewasno indication ofa problem in RTL simulation.

Gotcha 41: 92My enumerated state machine variables have values that don't exist in theenumerated definition.

Gotcha 42: 94My RTL model output changes values when it shouldn't, and to unexpectedvalues.

Gotcha43: 96Variables in mypackagekeepchanging at unexpected timesand to unexpectedvalues.

Gotcha 44: 99I need to do an assignment as part ofan ifcondition, but cannot get my code tocompile.

Gotcha 45: 101In some operations, my data is sign extendedand in other operations it is notsign extended, and inyet otheroperations it is not extendedat all.

Gotcha 46: 105I declared my outputs as signed types, but my design is still doing unsignedoperations.

Gotcha 47: 108MysignedaddermodelworkedperfectlyuntilI addeda carry-in input, andnowit only does unsignedaddition.

Gotcha 48: 111All my data typesaredeclaredas signed, andI am referencing theentiresignedvectors in my operations, yet I still get unsignedresults.

Gotcha 49: 112I'm usingthe ++operatorfor mycounter; thecountervalueis correct, butothercode that reads the countersees the wrongvalue.

xviii

Listof Gotchas

Gotcha 50: 113My while loop is supposedto execute 16 times, but it exits after 15 times, eventhough the loopcontrolvariable has a valueof16.

Gotcha 51: 115When I have multiple operations on a variable in a single statement. I getdifferent results from different simulators.

Gotcha52: 116I am callingafunction twice in a statement, but sometimes onlyoneofthecallsis executed.

Gotcha 53: 118My ifstatement witha not-true condition did not execute when I wasexpectingit to.

Gotcha 54.' 119I get the wrongresult when I sum all the values ofan array using the built-in.summethod

Gotcha 55: 121I get the wronganswerwhenI sum specific arrayelements in an array.

Gotcha 56.' 123Sometimes my design resets correctly at time zero, and sometimes it fails toreset.

Gotcha 57: 128My else branch ispairingup with the wrongifstatement.

Gotcha 58: 129My testbench completely misses problems on design outputs, even though it istestingthe outputs.

Gotcha59: 131I'm using the event data type to synchronize processes, but sometimes when Itriggeran event, thesensingprocessdoes not activate.

Gotcha 60: 134Myprocesses arenotsynchronizing thewayI expectedusingsemaphores. Evenwhen therearewaitingprocesses, someotherprocessgets to runaheadofthem.

Gotcha 61: 137My mailbox works atfirst, and thenstartsgettingerrorsduringsimulation.

Gotcha 62: 139I cannotget my testprogram to waitfor a clocking blockedge.

xix

Listof Gotchas

Gotcha 63: 140Statements in my i/O decision execute, evenwhen the condition is not true.

Gotcha 64: 142Myfor loop only executes one time.

Gotcha 65.' , " " .. , , 144Myfor loopneverexits. When the loopvariable reaches the exit value, the loopjust starts over again.

Gotcha 66.' 145When I run simulation, myfor loopslock up or do strangethings.

Gotcha 67: , 147My Verilog code no longercompiles after I convertmy Verilog-style for loopsto a SystemVerilog style.

Gotcha 68: , 148Myfunction only returns the leastsignificant bit ofthe return value.

Gotcha 69.' , , 150I get a syntax error when I try to assign my task/function input arguments adefaultvalue.

Gotcha 70.' , , " 151Some delayedoutputsshow up with continuous assignments and others do not.

Gotcha 71: , , ,., , .. , .. "", ",." .. , .153Someprogramming code in an initialprocedurecompiles OK, but whenI movethe code to a class definition, I get compilation errors.

Gotcha 72.' , 155I get a compilation error whenI try to use a class object to create test valueswhenthe testbench connects to the design usingan interface.

Gotcha 73.' , ,." , , , " .. 157My codecreatesrandom objectvaluesandputs themintoa mailbox, but all theobjectscomingout ofthe mailboxhave the same value.

Gotcha 74.' "."" , , ", .. , ,., , .. ,., ,., 158My methodconstructs and initializes an object, but I can neversee the object'svalue.

Gotcha 75: " , " .. , , .. , 159I declaredan arrayofobjects, butget a syntaxerrorwhenI try to construct thearray.

Gotcha 76: , , , ,. 160My task worksOKsometimes, butgets bogusresults other times.

xx

Listof Gotchas

Gotcha 77.' 162The variables in my testbench do not initialize correctly.

Gotcha 78.' , , 164When I fork offmultiple tests, I get incorrect results, but each test runs OK byitself.

Gotcha 79.' , 166When I execute a disable fork statement, sometimes it kills threads that areoutside the scopecontaining the disable fork statement.

Gotcha 80.' , 168When I try to disable a statement block in one thread, it stops the block in allthreads.

Gotcha 81.' , 171Mysimulation exitsprematurely, beforeI call Sfinish, and while sometestsarestill running.

Gotcha 82.' 173Someofmy class variables are notgettingrandomized, even though theyweretaggedas rand variables.

Gotcha 83: , , 175My class variables do not get random values, even though I called therandomize function.

Gotcha 84.' 177I used an assertion to detect randomization failures, and now nothing getsrandomized during reset.

Gotcha 85.' , 179When I specifyconstraints on morethantworandom variables, I don't get whatI expect.

Gotcha 86: , 181I amgettingnegative values in my random values, whereI onlywantedpositivevalues,

Gotcha 87.' .. , 182I've definedspecificcoverage bins insidemy covergroup to track coverage ofspecificvalues, but thereportonlyshowsthecoverage oftheentirecovergroup.

Gotcha 88: 184I defined a covergroup, but the group always has 0% coverage in the coverreport.

xxi

Listof Gotchas

Gotcha 89: 186I haveseveralinstances ofa covergroup, but thecoverage reportlumps them alltogether.

Gotcha 90: 187Sometimes the call to my covergroup constructor doesnot compile.

Gotcha 91: 188My assertion pass statement executed, even though I thought thepropertywasnot active.

Gotcha 92: "" , , 190My assertion pass statements are executing, even when the procedural codedoes not execute the assertion.

Gotcha 93: " , , .. ,.,., 192My assertion fail statement executes when the assertion succeeds instead offails.

Gotcha 94.' , , " , .. , , 193I have an assertion propertywith an open-ended delay in the consequent, anddoesn'tfail when it should.

Gotcha 95: ,." , , " .. ,." , , 195My design outputs do not change at the sametime in different simulators.

Gotcha 96,' , , , 198My packages compile fine on all simulators, but my design that uses thepackages will onlycompile on somesimulators.

Gotcha 97: , 200I cannotrepeatmy constrained random testson different tools.

Gotcha 98: , ,., , 202When I use System Verilog, some simulators will not let me load my memorymodels using$readmemb.

Gotcha 99: , , , 204MySystem Verilog codeonlyworks on one vendor's tools.

Gotcha 100: , , 206Sometoolsrequire onesyntaxfor arrayliterals. Othertoolsrequirea differentsyntax.

Gotcha 101.' , , ,. 208Some SystemVeriiog tools allowme to declare my inputports as real (floatingpoint), but othertoolsdo not.

xxii

Forewordby Steve Golson

Some people collectbaseball cards, old car magazines, or maybe rubber duckies.

I collectVerilog books.

It started back in 1989 with a looseleaf copy of "Gateway VERILOG-XLReference Manual Version I.5a" in a three-ring binder. Verilog was a bit simplerback then-it's hard to believe we actually designed chipsusingonlyone typeofprocedural assignment (nonblocking assigns were not part of the language yet).Andwe ran our simulations on a VAX, or maybe a fancy Apollo workstation.

SincethenI'vebought prettymuchevery Verilog bookthat camealong. I'vegot afew synthesis books, and I'll pick up an occasional VHDL reference or maybe atext on the history of hardware description languages, but mostly it's Verilog.Dozens and dozens of booksabout Verilog.

There'sa funny thingaboutmostof these books though. AfterI leaf through thema few times, they sit on the shelf. I admitthat it looks pretty impressive onceyouhave an entire bookcase filled with Verilog books, but the discerning visitor willnotice how fresh and newtheyall are. Unused. Unread. Useless.

I'm often disappointed to find very little information which is useful for thepracticing engineer. What I'm looking for is a book I can use every day, a bookthat will helpme get my chipout the door, on timeand working.

StuandDonhavewritten sucha book. I've known these guysfor manyyears, andthey have probably forgotten more Verilog than I've ever known. They havedistilled their collective knowledge into this helpful and extremely useful book.Readit and you won'tbe disappointed.

If you are an old hand at Verilog try to pick out all the Gotchas that you havefound the hard way. Smile and say to yourself "Oh yeah, I remember gettingcaught by that one!"

Those of you who are new to Verilog and SystemVerilog, welcome aboard!Here's your chance to learn from two of the leading experts in the field. And ifyou ever have a chance to take a training class from either of these gentlemen,don'thesitate to signup. I guarantee you won't regret it.

2 Verilog andSystemVeriiog Gotchas

Ohby the way, my favorite Gotcha is "Gotcha 65: Infinite for loops". Why? Well,I builta chipwiththatbug in it. Believe me,when a modeling errorcauses you tohave broken silicon, you never forget why it happened. Back then I didn't havethis book to help me, but you do! Keep this bookcloseat hand, refer to it often,andmayall yourmodels compile andall your loops terminate.

Steve GolsonTrilobyte Systems

http://www.trilobyte.com

Chapter 1Introduction,

What Is A Gotcha?

This chapter defines what a "gotcha" is, and why programming languagesallowgotchas. For the curious, the chapteralsoprovides a briefhistoryof the

Verilog and SystemVerilog standards. The topics presented in this chapterinclude:

• Whatare Verilog and SystemVerilog

• The definition of a gotcha

• A brief description of the Verilog and SystemVerilog standards

What are Verilog and SystemVerilog?

The terms "Verilog" and "SystemVerilog" are sometimes a source of confusionbecause the terms are not used consistently in the industry. For the purposes ofthis book,"Verilog" and SystemVerilog are used as follows:

Verilog is a Hardware Description Language (HDL). It is a specializedprogramming language used to model digital hardware designs and, to a limitedextent, to write test programs to exercise thesemodels.

SystemVerilog is a substantial set of extensions to the Verilog HDL. A primarygoal of these extensions is to enablemodeling and verifying larger designs withmorecompact code. By itself, SystemVerilog is not a complete language; it is justa set of additions to the base Verilog language.

4

What is a Gotcha?

Verilog and SystemVeriiog Gotchas

A programming "gotcha" is a language feature, which, if misused, causesunexpected-and, in hardware design, potentially disastrous-behavior. Theclassic example in the C language is having an assignment within a conditionalexpression, suchas:

if (day=15) /* GOTCHA! assigns value of 15 to day, then */do_mid_month_payroll; /* if day is non-zero, do a payroll */

Most likely, what the programmer intended to code is if (a==b) instead of if

(a=b). The results are very different! This classic C programming Gotcha is nota syntax error; the code is perfectly legal. However, the code probably does notproduce the intended results. If the coding erroris not detected before a product isshipped, a simple bug like this couldleadto serious ramifications in a product.

Just like any programming language, Verilog, and the SystemVerilog extensionsto Verilog, have gotchas. Thereare constructs in Verilog and SystemVerilog thatcan be used in ways that are syntactically correct, but yield unexpected orundesirable results. Some of theprimary reasons Verilog and SystemVerilog havegotchas are:

• Inheritance of C and C++ gotchasVerilog and SystemVerilog leverage the general syntax and semantics of theC and C++ languages. Verilog and SystemVerilog inherit the strengths ofthese powerful programming languages, but they also inherit many of thegotchas of C and C++. (Which raises the question, can the common C cod­ing error such as if (day= 15) be made in Verilog/SystemVerilog? Theanswercan be found in Gotcha 44 on page99.)

• Loosely typedoperations

Verilog and SystemVerilog are loosely typed languages. As such, operationscan be performed on any data type, and underlying language rules take careof how operations should be performed. If a design or verification engineerdoes not understand these underlying language rules, then unexpectedresults can occur.

• Allowance to model goodandbad designs

An underlying philosophy of Verilog and SystemVerilog is that engineersshould be allowed to model and prove both what works correctly in hard­ware, and what will not work in hardware. In order to legally model hard­ware that does not work, the language must also permit unintentionalmodeling errorswhenthe intent is to model designs thatworkcorrectly.

Chapter 1: Introduction, What Is A Gotcha?

The Verilog and SystemVerilog standards

5

Veri/og is an international standard Hardware Description Language. The officialstandard is IEEE Std 1364-2005 Verilog Language ReferenceManual (LRM),commonly referred to as ((Veri/og-2005". The Verilog standard defines a rich setof programming and modeling constructs specific to representing the behavior ofdigital logic. The Verilog Hardware Description Language was first created in1984. Verilog was designed to meet the needs of engineering in the mid 1980s,when a typical design was under 50,000 gates and ICs were based on 3 microntechnology. As digital design size and technologies changed, Verilog evolved tomeet new design requirements. Verilog was first standardized by the IEEE in1995 (IEEE Std 1364-1995). In 2001, The IEEE released the Verilog-2001standard (IEEE Std 1364-2001) which enhanced Verilog in several ways, suchassynthesizable signed arithmetic on any vector size and re-entrant tasks andfunctions. TheIEEE updated theVerilog standard in 2005, but no major modelingenhancements were added in this version. Instead, all enhancements to Verilogwere documented in a separate standard, SystemVerilog.

System Verilog is a standard set of extensions to the Verilog-2005 Standard. Theseextensions are documented in a separate standard, IEEE Std 1800-2005SystemVerilog Language Reference Manual, commonly referred to as"SystemVeri/og-2005". The SystemVerilog extensions enable writingsynthesizable models that are continuously increasing in size and complexity, aswell as verifying these multi-million gate designs. SystemVerilog addsto Verilogfeatures from the SUPERLOG, VERA C, C++, and VHDL languages, along withOVA and PSL assertions. SystemVerilog was first developed by Accellera, aconsortium of companies that do electronic design and companies that provideElectronic Design Automation (EDA) tools. Accellera released a preliminaryversion of the extensions to Verilog in 2002, called SystemVerilog 3.0 (3.0 toshowthat SystemVerilog was the nextgeneration of Verilog, where Verilog-1995was the first generation and Verilog 2001 was the second generation). In 2003,Accellera released SystemVerilog 3.1 and in 2004 SystemVerilog 3.la. This latterAccellera standard was thensubmitted to the IEEE for full standardization.

The original intent was for the IEEE to fold the Accellera SystemVerilogextensions into the Verilog standard. At the insistence of EDA companies,however, the IEEE made the decision to temporarily keep the SystemVerilogextensions in a separate document to make it easier for EDA companies toimplement theextensive set of newfeatures in theirVerilog tools.