Verilog And SystemVerilog Gotchas

3y ago
158 Views
23 Downloads
1.03 MB
23 Pages
Last View : 21d ago
Last Download : 1m ago
Upload by : Nixon Dill
Transcription

Verilog and SystemVerilogGotchas101 Common Coding Errors and How toAvoid Them

Stuart SutherlandDon MillsVerilog and SystemVerilogGotchas101 Common Coding Errors and How toAvoid Them Springer

StuartSutherlandSutherland HDL, Inc.Tualatin, ORDon MillsLCDM EngineeringChandler, AZUSAUSALibraryof CongressControl Number: 15-9Printedon acid-freepaper. 2007 SpringerScience 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, servicemarks and 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 1springer.com

DedicationTo my wonderful wife, LeeAnn, and my children, Ammon, Tamara, Hannah, Seth andSamuel- thankyoufor your patienceduringthe many longhours and late nightsyou toleratedwhile this book was beingwritten.Stu SutherlandPortland, OregonTo my wife and sweetheart GeriJean, and my children, Sara, Kirsten, Adam, Alex,Dillan, Donnelle, Grantand Gina- thanks to each ofyoufor thepatienceyou havehad withme as I have dealtwithdebugging manyofthesegotchason designs overtheyears.Don MillsChandler, Arizona

About the AuthorsMr. 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 providingcomprehensive expert training on the Verilog HDL, SystemVerilog and PLI.Stuart is a co-authorof the books "SystemVerilog f or 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 hasalso authored a number of technical papers on Verilog and SystemVerilog, whichare available at www.sutherland-hdl.com/papers. You can contact Stuart atstuart@sutherland-hdl.com.visit the authors webpage at www.sutherland-hdl.comMr. 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 theIEEE 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 atmills@lcdm-eng.comor don.mills@microchip.com.visit the author swebpage at www.lcdm-eng.com

AcknowledgmentsThe 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 for us.Shalom Bresticker of Intelalso suggested 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 onhow to improve the gotcha descriptions.Steve Golson of Trilobyte Systems provided a wonderful foreword to thisbookLastly, 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 ofContentsList of Gotchas. . . . . . . . . . . . . . . . . . . xvForewordby SteveGolson. . . . . . . . . . . . . 1Chapter 1:Introduction,What Is A Gotcha?3Chapter 2:Declaration and Literal Number Gotchas7Gotcha 1: Case sensitivity7Gotcha 2: Implicit net declarations10Gotcha 3: Default of l-bit internal nets13Gotcha 4: Single file versus multi-file compilation of unit declarations15Gotcha 5: Local variable declarations17Gotcha 6: Escapednames in hierarchical paths19Gotcha 7: Hierarchical references to automatic variables22Gotcha 8: Hierarchical references to variables in unnamedblocks25Gotcha 9: Hierarchical references to importedpackage items27Gotcha 10: Importingenumerated types from packages28Gotcha 11: Importing from multiplepackages29Gotcha 12: Default base of literal integers30Gotcha 13: Signedness of literal integers32Gotcha 14: Signed literal integerszero extend to their specifiedsize33Gotcha 15: Literal integer size mismatch in assignments35Gotcha 16: Filling vectors with all ones37Gotcha 17: Array literals versus concatenations38Gotcha 18: Port connectionrules39Gotcha 19: Back-driven ports43

Table of ContentsGotcha 20: Passing real (floating point)numbers through ports46Chapter 3:RTL Modeling Gotchas49Gotcha21: Combinational logicsensitivity lists with function calls49Gotcha22: Arrays in sensitivity lists52Gotcha23: Vectors in sequential logic sensitivity lists54Gotcha24: Operations in sensitivity lists56Gotcha25: Sequential logicblocks with begin end groups57Gotcha26: Sequential logicblockswith resets59Gotcha 27: Asynchronous set/reset flip-flop for simulation and synthesis60Gotcha28: Blocking assignments in sequential procedural blocks62Gotcha29: Sequential logic that requires blocking assignments64Gotcha30: Nonblocking assignments in combinational logic66Gotcha31: Combinational logicassignments in the wrongorder70Gotcha32: Casez/casex masks in case expressions72Gotcha33: Incomplete decision statements74Gotcha34: Overlapped decision statements77Gotcha35: Inappropriate use of unique case statements79Gotcha36: Resetting 2-statemodels82Gotcha 37: Lockedstate machines modeled with enumerated types84Gotcha38: Hidden design problems with 4-statelogic86Gotcha39: Hiddendesign problems using2-statetypes88Gotcha40: Hidden problems with out-of-bounds arrayaccess90Gotcha 41: Out-of-bounds assignments to enumerated types92Gotcha 42: Undetected sharedvariables in modules94Gotcha43: Undetected sharedvariables in interfaces and packages96Chapter 4:Operator Gotchas99Gotcha 44: Assignments in expressions99Gotcha 45: Self-determined versuscontext-determined operators101Gotcha46: Operation size and sign extension in assignment statements105Gotcha47: Signedarithmetic rules108xii

Table of ContentsGotcha 48: Bit-select and part-select operations111Gotcha 49: Increment, decrement and assignment operators112Gotcha 50: Pre-increment versuspost-increment operations113Gotcha 51: Modifying a variable multiple times in one statement115Gotcha52: Operator evaluation short circuiting116Gotcha53: The not operator( ! ) versus the invertoperator( -- )118Gotcha54: Arraymethod operations119Gotcha 55: Array method operations on an array subset.121Chapter 5:General Programming Gotchas123Gotcha56: Verifying asynchronous and synchronous reset at time zero123Gotcha57: Nestedif else blocks128Gotcha 58: Evaluation of equality with 4-statevalues129Gotcha 59: Eventtriggerrace conditions131Gotcha60: Using semaphores for synchronization134Gotcha 61: Usingmailboxes for synchronization137Gotcha 62: Triggering on clocking blocks139Gotcha 63: Misplaced semicolons after decision statements140Gotcha 64: Misplaced semicolons in for loops 142Gotcha65: Infinitefor loopsGotcha 66: Lockedsimulation due to concurrent for loops144145Gotcha 67: Referencing for loop control variables147Gotcha68: Defaultfunction returnsize148Gotcha69: Task/function arguments with defaultvalues150Gotcha70: Continuous assignments with delays cancel glitches151Chapter 6:Object Oriented and Multi-Threaded Programming Gotchas153Gotcha 71: Programming statements in a class153Gotcha 72: Using interfaces with object-oriented testbenches155Gotcha 73: All objects in mailbox comeout with the samevalues157Gotcha 74: Passing handles to methods using inputversus ref arguments158Gotcha 75: Constructing an array of objects159xiii

Table of ContentsGotcha 76: Statictasks and functions are not re-entrant160Gotcha 77: Staticversus automatic variable initialization162Gotcha 78: Forkedprogramming threads needautomatic variables164Gotcha 79: Disable fork kills too manythreads166Gotcha 80: Disabling a statement blockstopsmorethan intended168Gotcha 81: Simulation exitsprematurely, beforetestscomplete171Chapter 7:Randomization, Coverage and Assertion Gotchas173Gotcha 82: Variables declared withrand are not getting randomized173Gotcha 83: Undetected randomization failures175Gotcha 84: assertoffcoulddisable randomization177Gotcha 85: Boolean constraints on more than two random variables179Gotcha 86: Unwanted negative values in random values181Gotcha 87: Coverage reports default to groups, not bins182Gotcha 88: Coverage is always reported as 0%184Gotcha 89: The coverage reportlumps all instances together186Gotcha 90: Covergroup argument directions are sticky187Gotcha 91: Assertion pass statements execute with a vacuous success188Gotcha 92: Concurrent assertions in procedural blocks190Gotcha 93: Mismatch in assert else statements192Gotcha 94: Assertions that cannot faiI.193Chapter 8:Tool Compatibility Gotchas195Gotcha 95: Defaultsimulation timeunits and precision195Gotcha 96: Package chaining198Gotcha 97: Random number generator is not consistent across tools200Gotcha 98: Loading memories modeled with always latchlalways ff202Gotcha 99: Non-standard language extensions204Gotcha 100:Array literals versus concatenations206Gotcha 101 :Module portsthat passfloating pointvalues (realtypes)208Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209xiv

List ofGotchasGotcha 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 onlyshowed up as afunctional problemin simulation.Gotcha 3:In my netlist, only bit zero ofmy vectorports get connected.13Gotcha 4:15My models compile OK, and the modelsfrom anothergroup compile OK; butwhen compiledtogether, I get errorsabout multiple declarations.Gotcha 5:17I get compilation errorson my local variable 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 to print out somesignalsin mydesign, but othersignals can be printed withouta problem.Gotcha 8:25With Verilog, my testbench couldprint out localvariables in a begin end block,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 GotchasGotcha 12:30Some branches ofmy case statement are never selected, even with the correctinputvalues.Gotcha 13:32My lncrementor modelsometimes gets incorrect values when I increment usinga literal 1 'b1.Gotcha 14:33When I specify a 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 samesyntax to set all bits to 1, I get a decimal 1 instead.Gotcha 17:38The wrongvalues are storedwhenI assign a list ofvalues to a packedarrayorstructure.Gotcha 18:39My design doesn't workcorrectly when I connect all the modules together, buteach module 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 real values from one module to anotherusingeitherVerilog or System Veri/og.Gotcha 21:49My combinational logic seemed to simulate OK, but after synthesis, the gatelevelsimulation does not matchthe RTL simulation.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 any positive edge in a vector, but itmisses most edges.xvi

Listof GotchasGotcha 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:Some ofthe outputs ofmy sequential logicdo not get reset.59Gotcha 27:60When I code an asynchronous set/reset D-type flip-flop following synthesiscodingrules, my simulation results are sometimes wrong.Gotcha 28:My shift register sometimes does a double shift in one clockcycle.62Gotcha 29:64I'm following the recommendations for using nonblocking assignments insequential logic, butI still haverace conditions in simulation.Gotcha 30:My RTL simulation locksup and timestops advancing.66Gotcha 31:70Simulation ofmygate-level combinational logicdoesnotmatch RTLsimulation.Gotcha 32:72Mycasexstatement is takingthewrongbranch whenthereis an errorin thecaseexpression.Gotcha 33:74Myfull case, parallel case decision statement simulatedas I expected, but thechip does not work.Gotcha 34:Oneofmy decision branches nevergets executed.77Gotcha 35:79I am using unique case everywhere to help trap design bugs but my synthesisresults are not whatI expected.Gotcha 36:My design fails to reset thefirst time in RTL simulation.82Gotcha 37:My state machine modellocksup in its start-up state.84xvii

Listof GotchasGotcha 38:86There was a problemdeep insidethe logicofmy design, but it neverpropagatedto moduleboundaries.Gotcha 39:88Some majorfunctional bugs in my design did not show up until after synthesis,whenI ran gate-levelsimulations.Gotcha 40:90A design bug causedreferences 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.Gotcha 43:96Variables in my package keep changing at unexpected times and to unexpectedvalues.Gotcha 44:99I need to do an assignment as part ofan if condition, but cannot get my code tocompile.Gotcha 45:101In some operations, my data is sign extendedand in other operations it is notsign extended, and in yet other operations 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, and nowit only does unsignedaddition.Gotcha 48:111All my data typesare declaredas signed, andI am referencing the entiresignedvectors in my operations, yet I still get unsignedresults.Gotcha 49:112I'm usingthe operatorfor my counter; thecountervalueis correct, butothercode that reads the countersees the wrongvalue.xviii

List of GotchasGotcha 50:113My while loop is supposedto execute 16 times, but it exits after 15 times, eventhough the loop controlvariable 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 onlyone ofthe callsis executed.Gotcha 53:118My if statement with a not-true condition did not execute when I was expectingit to.Gotcha 54.'119I get the wrong result when I sum all the values of an array using the built-in.summethodGotcha 55:I get the wronganswerwhenI sum specific array elements in an array.121Gotcha 56.'123Sometimes my design resets correctly at time zero, and sometimes it fails toreset.Gotcha 57:My else branch is pairingup with the wrong if statement.128Gotcha 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, the sensingprocessdoes not activate.Gotcha 60:134Myprocesses are not synchronizing the wayI expectedusingsemaphores. Evenwhen thereare waitingprocesses, someotherprocessgets to runaheadofthem.Gotcha 61:137My mailbox works atfirst, and thenstartsgettingerrorsduringsimulation.Gotcha 62:I cannotget my testprogram to waitfor a clocking block edge.xix139

List of GotchasGotcha 63:140Statements in my i/O decision execute, even when the condition is not true.Gotcha 64:Myfor loop only executes one time.142Gotcha 65.',"" . ,,144Myfor loop never exits. When the loop variable reaches the exit value, the loopjust starts over again.Gotcha 66.'When I run simulation, myfor loops lock up or do strange things.145Gotcha 67:,147My Verilog code no longercompiles after I convertmy Verilog-style for loopsto a System Verilog style.Gotcha 68: ,Myfunction only returns the leastsignificant bit ofthe return value.148Gotcha 69.',,150I get a syntax error when I try to assign my task/function input arguments adefault value.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 when I try to use a class object to create test valueswhen the testbench connects to the design usingan interface.Gotcha 73.' ,,.",,," . 157My code createsrandom objectvaluesandputs them into a 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 syntax error whenI try to construct thearray.Gotcha 76:,,,My task works OK sometimes, butgets bogusresults other times.xx,. 160

List of GotchasGotcha 77.'The variables in my testbench do not initialize correctly.162Gotcha 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 scope containing 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 some testsarest

an independent Verilog consultant, specializing in providing comprehensive expert training on the Verilog HDL, SystemVerilog and PLI. Stuart is a co-authorof thebooks "SystemVerilogfor Design", "Verilog-2001: A Guide to theNewFeatures in the Verilog Hardware Description Language" and

Related Documents:

SystemVerilog is a superset of another HDL: Verilog –Familiarity with Verilog (or even VHDL) helps a lot Useful SystemVerilog resources and tutorials on the course project web page –Including a link to a good Verilog tutori

SystemVerilog is a superset of Verilog -The SystemVeriog subset we use is 99% Verilog a few new constructs -Familiarity with Verilog (or even VHDL) helps but is not necessary SystemVerilog resources and tutorials on the course "Assignments" web page. Spring 2018 :: CSE 502

Verilog-A HDL Overview 1.1 Overview This Verilog-A Hardware Description Language (HDL) language reference manual defines a behavioral language for analog systems. Verilog-A HDL is derived from the IEEE 1364 Verilog HDL specification. This document is intended to cover the definition and semantics of Verilog-A HDL as proposed by Open Verilog .

Verilog code thinks it is calling a native Verilog task or function Using the SystemVerilog DPI – Verilog code can directly call C functions – Verilog code can dire

SimVision User Guide—For information about using SimVision Verilog Simulation User Guide—For information about simulating Verilog designs irun User Guide—For information about using the irun utility. SystemVerilog in Simulation Introduction to SystemVerilog in Simulation

verification IP that may exist in Verilog, SystemVerilog, VHDL, e or SystemC. Topics include: . (used here to refer to Verilog, SystemVerilog or VHDL code) DUT Device Under Test Tb Testbench . the first FSM int

Verilog PLI Tutorial ? : 20% Complete What's new in Verilog 2001? : 50% Complete Verilog Quick Reference. Verilog in One Day : This tutorial is in bit lighter sense, with humor, So take it cool and enjoy. INTRODUCTION Introduction. Verilog is a HARDWARE DESCRIPTION LANGUAGE (HDL). A hardware

9 MATHEMATICS - Week 1 Lesson 2: Properties of Operations Learning Objectives: Students will be able to simplify computations with integers, fractions and decimals by using the associative and commutative properties of addition and multiplication, and