Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
233 views
Verilog
VLSI BASIC LANGUAGE ---- VERILOG
Uploaded by
shabbir470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Verilog For Later
Download
Save
Save Verilog For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
100%
(1)
100% found this document useful (1 vote)
233 views
Verilog
VLSI BASIC LANGUAGE ---- VERILOG
Uploaded by
shabbir470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Verilog For Later
Carousel Previous
Carousel Next
Save
Save Verilog For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 319
Search
Fullscreen
Copyright © 2003 Sun Microsystems, Inc. 2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A. Allrights reserved. This product or documents protected by copyrightand distributed under licenses restricting its use, copying, distribution and decompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Portions of this product may be derived from the UNIX® system and from the Berkeley 4.3 BSD system, licensed from the University of California, Third-party software, including font technology in this product, is protected by copyright and licensed from Sun's Suppliers. RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 and FAR 2.227-19. ‘The product described in this manual may be protected by ane or more U.S. patents, foreign patents, or pending applications TRADEMARKS Sun, Sun Microsystems, the Sun logo, and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and may be protected as trademarks in other countries. UNIX is.a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. OPEN LOOK is a registered trademark of Novell, Inc. PostScript and Display PostScript are trademarks of Adobe Systems, Inc. Verilog is a registered trademark of Cadence Design Systems, Inc. Verilog-XL is a trademark of Cadence Design Systems, Inc. VCS is a trade- mark of Viewlogic Systems, Inc. Magellan is a registered trademark of Systems Science, Inc. VirSim is a trademark of Simulation Technologies, Inc. Signalscan is a trademark of Design Acceleration, Inc. All other product, service, or company names mentioned herein are claimed as trademarks and trade names by their respective companies All SPARC trademarks, including the SCD Compliant Logo, are trademarks or registered trade- marks of SPARC International, Inc. in the United States and may be protected as trademarks in other countries. SPARCcenter, SPARCcluster, SPARCompiler, SPARCdesign, SPARC811, SPAR- Cengine, SPARCprinter, SPARCserver, SPARCstation, SPARCstorage, SPARCworks, micro- SPARC, microSPARC-Il, and UltraSPARC are licensed exclusively to Sun Microsystems, Inc. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsys- tems, Inc. The OPEN LOOK™ and Sun™ Graphical User Interfaces were developed by Sun Microsystems, Inc, for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox te the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUI's and otherwise comply with Sun's written license agreements. X Window System is a trademark of X Consortium, Inc.Copyright x The publisher offers discounts on this book when ordered in bulk quantities. For more information, contact: Corporate Sales Department, Prentice Hall PTR, One Lake Street, Upper Saddle River, NJ 07458. Phone: 800-382-3419; FAX: 201- 236-7141. E-mail:
. Production supervisor: Wil Mara Cover designer: Nina Scuderi Cover design director: Jemy Votta Manufacturing manager: Alexis R. Heyat-Long Acquisitions editor: Gregory G. Doench Printed in the United States of America 10987654321 SunSoft Press A Prentice Hall Title Dedication Ta Anu, Adiiya, and Sabi, Thank you for everything To our faites, Thank you for your constant encouragement and support.xi About the Author Samir Palnitkar is currently the President of Jamba Systems, Inc., a leading ASIC design and ver- ification services company which specializes in high-end designs for microprocessor, networking, and communications applications. Mr. Palnitkar is a serial entrepreneur. He was the founder of Integrated Intellectual Property, Inc., an ASIC company that was acquired by Lattice Semiconductor, Inc. Later he founded Obongo, Inc., an e-commerce software firm that was acquired by AOL Time Warmer, Inc. Mr. Palnitkar holds a Bachelor of Technology in Electrical Engineering from Indian Institute of Tech- nology, Kanpur, a Master's in Electrical Engineering from University of Washington, Seattle, and an MBA degree from San Jose State University, San Jose, CA. Mr. Palnitkar is a recognized authority on Verilag HDL, modeling, verification, logic synthesis, and EDA-based methodologies in digital design. He has worked extensively with design and verification on various successful microprocessor, ASIC, and system projects. He was the lead developer of the Verilog framework for the shared memory, cache coherent, multiprocessor architecture, popu- larly known as the UltraSPARC Port Architecture, defined for Sun's next generation UltraSPARC- based desktop systems. Besides the UltraSPARC CPU, he has worked on a number of diverse design and verification projects at leading companies including Cisco, Philips, Mitsubishi, Matorola, National, Advanced Micro Devices, and Standard Microsystems. Mr. Painitkar was also a leading member of the group that first experimented with cycle-based simulation technology on joint projects with simulator companies. He has extensive experience with a variety of EDA tools such as Verilag-NC, Synopsys VCS, Specman, Vera, System Verilog, Syn- opsys, SystemC, Verplex, and Design Data Management Systems. Mr. Palnitkar is the author of three US patents, one far a novel method to analyze finite state ma- chines, a second for work on cycle-based simulation technology and a third(pending approval) for a unique e-commerce tool. He has also published several technical papers. In his spare time, Mr. Palnitkar likes to play cricket, read books, and travel the worldxii List of Figures Figure 1-1 Typical Design Flow Figure 2-1 Top-down Design Methadology Figure 2-2 Bottom-up Design Methodology Figure 2-3 Ripple Carry Counter Figure 2-4 T-flipflop Figure 2-5 Design Hierarchy Figure 2-6 Stimulus Block Instantiates Design Black Figure 2-7 Stimulus and Design Blocks instantiated in a Dummy Top-Level Module Figure 2-8 Stimulus and Output Waveforms Figure 3-1 Example of Nets Figure 4-1 Components of a Verilog Module Figure 4-2 SR Latch Figure 4-3 lO Ports for Top and Full Adder Figure 4-4 Port Connection Rules Figure 4-5 Design Hierarchy for SR Latch Simulation Figure 5-1 Basic Gates Figure 5-2 Buf and Not Gates Figure 5-3 Gates Bufif and Natif Figure 5-4 4-to-1 Multiplexer Figure 5-5 Logic Diagram for Multiplexer Figure 5-6 1-bit Full Adder Figure 5-7 4-bit Ripple Carry Full Adder Figure 8-8 Module D Figure 5-9 Waveforms for Delay Simulation Figure 6-1 Delays Figure 6-2 4-bit Ripple Carry Counter Figure 6-3 T-flipflop Figure 6-4 Negative Edge-Triggered D-flipflop with Clear Figure 6-5 Master-Slave JK-flipflop Figure 6-6 4-bit Synchronous Counter with clear and count_enable Figure 7-1 FSM for Traffic Signal Controller Figure 9-1 Debugging and Analysis of Simulation with VCD File Figure 10-1 Distributed Delay Figure 10-2 Lumped DelayList of Figures xiii Figure 10-3 Pin-to-Pin Delay Figure 10-4 Parallel Connection Figure 10-5 Full Connection Figure 10-6 Setup and Hold Times Figure 10-7 Delay Back-Annotation Figure 11-1 NMOS and PMOS Switches Figure 11-2 CMOS Switch Figure 11-3 Bidirectional Switches Figure 11-4 Gate and Switch Diagram for Nor Gate Figure 11-5 2-to-1 Multiplexer, Using Switches Figure 11-6 CMOS flipflop Figure 11-7 CMOS Inverter Figure 12-1 Parts of UDP Definition Figure 12-2 4-to-1 Multiplexer with UDP Figure 12-3 Level-Sensitive Latch with clear Figure 12-4 Edge-Sensitive D-flipflop with clear Figure 13-1 PLI Interface Figure 13-2 General Flow of PLI Task Addition and Invecation Figure 13-3 Conceptual Internal Representation of a Module Figure 13-4 2-to-1 Multiplexer Figure 13-5 Internal Data Representation of 2-to-1 Multiplexer Figure 13-6 Role of Access and Utility Routines Figure 14-1 Designer's Mind as the Logic Synthesis Too! Figure 14-2 Basic Computer-Aided Logic Synthesis Process Figure 14-3 Multiplexer Description Figure 14-4 Logic Synthesis Flow from RTL to Gates Figure 14-5 Area vs. Timing Trade-off Figure 14-6 Gate-Level Schematic for the Magnitude Comparator Figure 14-7 Horizontal Partitioning of 16-bit ALU Figure 14-8 Vertical Partitioning of 4-bit ALU Figure 14-9 Parallelizing the Operation of an Adder Figure 14-10 Finite State Machine for Newspaper Vending Machine Figure 14-11 Gate-Level Schematic for the Vending Machine Figure 15-1 Traditional Verification Flow Figure 15-2 Architectural Modeling Figure 15-3 Components of a Functional Verification Environment Figure 15-4 Interaction between HVL and Verilog Simulators Figure 15-5 Hardware Acceleration Figure 15-6 Hardware Emulation Figure 15-7 Assertion Checks Figure 15-8 Formal Verification Flow Figure 15-9 Semi-formal Verification Flow Figure 15-10 Equivalence CheckingList of Figures xiv Figure F-1 FIFO Input/Output Ports Figure F-2 DRAM Input/Output Portsxv Table 3-1 Value Levels Table 3-2 Strength Levels Table 3-3 Special Characters Table 3-4 String Format Specifications Table 5-1 Truth Tables for And/Or Gates Table 5-2 Truth Tables for Buf/Not Gates Table 5-3 Truth Tables for Bufif/Notif Gates Table 6-1 Operator Types and Symbols Table 6-2 Equality Operators Table 6-3 Truth Tables for Bitwise Operators Table 6-4 Operator Precedence Table 8-1 Tasks and Functions Table 11-1 Logic Tables tor NMOS and PMOS Table 11-2 Strength Reduction by Resistive Switches Table 11-3 Delay Specification on MOS and CMOS Switches Table 11-4 Delay Specification for Bidirectional Switches Table 12-1 UDP Table Shorthand Symbols Table 13-1 Specifications for $my_stop_finish Table 14-1 Verilog HDL Constructs for Logic Synthesis Table 14-2 Verilog HDL Operators for Logic Synthesis Table A-1 Strength Levels Table B-1 Handle Routines Table 8-2 Next Routines ‘Table 8-3 Value Change Link Routines Table B-4 Fetch Routines Table 8-5 Utility Access Routines Table B-6 Modify Routines Table B-7 Get Calling Task/Function Information ‘Table 8-8 Get Argument List Information Table 8-9 Get Parameter Values Table B-10 Put Parameter Values Table 8-11 Monitor Parameter Value Changes Table B-12 Synchronize Tasks Table B-13 Long Arithmetic List of TablesList of Tables xvi Table B-14 Display Messages Table B-15 Miscellaneous Utility Routines Table 8-16 Housekeeping Tasksxvii List of Examples Example 2-1 Module Instantiation Example 2-2 lilegal Module Nesting Example 2-3 Ripple Carry Counter Tap Block Example 2-4 Flipflop T_FF Example 2-5 Flipflop D_F Example 2-6 Stimulus Block Example 2-7 Output of the Simulation Example 3-1 Example of Register Example 3-2 Signed Register Declaration Example 3-3 $display Task Example 3-4 Special Characters Example 3-5 Monitor Statement Example 3-6 Stop and Finish Tasks Example 3-7 ‘define Directive Example 3-8 ‘include Directive Example 4-1 Components of SR Latch Example 4-2 List of Ports Example 4-3 Port Declarations Example 4-4 Port Declarations for DFF Example 4-5 ANSI C Style Port Declaration Syntax Example 4-6 Illegal Port Connection Example 4-7 Connection by Ordered List Example 4-8 Hierarchical Names Example 5-1 Gate Instantiation of And/Or Gates Example 5-2 Gate Instantiations of Buf/Not Gates Example 5-3 Gate instantiations of Bufif/Notif Gates Example 5-4 Simple Array of Primitive Instances Example 5-5 Verilog Description of Multiplexer Example 5-6 Stimulus for Multiplexer Example 5-7 Verilog Description for 1-bit Full Adder Example 5-8 Verilog Description for 4-bit Ripple Carry Full Adder Example 5-9 Stimulus for 4-bit Ripple Carry Full Adder Example 5-10 Types of Delay Specification Example 5-11 Min, Max, and Typical Delay ValuesList of Examples xviii Example 5-12 Verilog Definition for Module D with Delay Example 5-13 Stimulus for Module D with Delay Example 6-1 Examples of Continuous Assignment Example 6-2 4-to-4 Multiplexer, Using Logic Equations Example 6-3 4-to-1 Multiplexer, Using Conditional Operators Example 6-4 4-bit Full Adder, Using Dataflow Operators Example 6-5 4-bit Full Adder with Garry Lookahead Example 6-6 Verilog Code for Ripple Counter Example 6-7 Verilog Code for T-flipflop Example 6-8 Verilog Code for Edge-Triggered D-flipflop Example 6-9 Stimulus Module for Ripple Counter Example 7-1 initial Statement Example 7-2 Initial Value Assignment Example 7-3 Combined Port/Data Declaration and Variable Initialization Example 7-4 Combined ANSI C Port Declaration and Variable Initialization Example 7-5 always Statement Example 7-8 Blocking Statements Example 7-7 Nonblocking Assignments Example 7-8 Nonblocking Statements to Eliminate Race Conditions Example 7-9 Implementing Nonblocking Assignments using Blocking Assignments Example 7-10 Regular Delay Control Example 7-11 Intra-assignment Delays Example 7-12 Zero Delay Control Example 7-13 Regular Event Control Example 7-14 Named Event Control Example 7-15 Event OR Control (Sensitivity List) Example 7-16 Sensitivity List with Comma Operator Example 7-17 Use of @* Operator Example 7-18 Conditional Statement Examples Example 7-19 4-to-1 Multiplexer with Case Statement Example 7-20 Case Statement with x and z Example 7-21 casex Use Example 7-22 While Loop Example 7-23 For Loop Example 7-24 Repeat Loop Example 7-25 Forever Loop Example 7-26 Sequential Blocks Example 7-27 Parallel Blocks Example 7-28 Nested Blocks Example 7-29 Named Blocks Example 7-30 Disabling Named Blocks Example 7-31 Bit-wise Xor of Two N-bit Buses Example 7-32 Generated Ripple AdderList of Examples xix Example 7-33 Parametrized Multiplier Using Generate Conditional Example 7-34 Generate Case Example Example 7-35 Behavioral 4-to-1 Multiplexer Example 7-36 Behavioral 4-bit Counter Description Example 7-37 Traffic Signal Controller Example 7-38 Stimulus for Traffic Signal Controller Example 8-1 Syntax for Tasks Example 8-2 Input and Output Arguments in Tasks Example 8-3 Task Definition using ANSI C Style Argument Declaration Example 8-4 Direct Operation on reg Variables Example 8-5 Re-entrant (Automatic) Tasks Example 8-6 Syntax for Functions Example 8-7 Parity Calculation Example 8-8 Function Definition Using ANSI C Style Argument Declaration Example 8-9 Left/Right Shifter Example 8-10 Recursive (Automatic) Functions Example 8-11 Constant Functions Example 8-12 Signed Functions Example 9-1 D-Flipflop with Procedural Continuous Assignments Example 9-2 Defparam Statement Example 9-3 ANSI C Style Parameter Declaration Example 9-4 Module Instance Parameter Values Example 9-5 Conditional Compilation Example 9-6 Conditional Execution with $test$plusargs Example 8-7 Conditional Execution with $valueSplusargs Example 9-8 Time Scales Example 9-9 File Descriptors Example 9-10 Displaying Hierarchy Example 9-11 Strobing Example 9-12 Random Number Generation Example 9-13 Generation of Positive and Negative Numbers Example 9-14 Initializing Memory Example 9-15 VCD File System Tasks Example 10-1 Distributed Delays. Example 10-2 Lumped Delay Example 10-3 Pin-to-Pin Delay Example 10-4 Paraliel Connection Example 10-5 Full Connection Example 10-8 Specparam Example 10-7 Conditional Path Delays Example 10-8 Path Delays Specified by Rise, Fall and Turn-off Values Example 10-9 Path Delays with Min, Max, and Typical Values Example 11-1 instantiation of NMOS and PMOS SwitchesList of Examples Xx Example 11-2 Instantiation of a CMOS Switch Example 11-3 instantiation of Bidirectional Switches Example 11-4 Switch-Level Verilog for Nor Gate Example 11-5 Switch-Level Verilog Description of 2- Example 11-6 CMOS Inverter Example 11-7 CMOS flipflop Example 12-1 Primitive udp_and Example 12-2 ANSI C Style UDP Declaration Example 12-3 Primitive udp_or Example 12-4 Instantiation of udp Pri Example 12-5 Verilog Description of 4-to-1 Multiplexer with UDP Example 12-6 Stimulus for 4-to-1 Multiplexer with UDP Example 12-7 Verilog Description of Level-Sensitive UDP Example 12-8 ANSI C Style Port Declaration for Sequential UDP Example 12-9 Negative Edge-Triggered D-tlipflop with clear Example 12-10 T-flipflop with UDP Example 12-11 instantiation of T_FF UDP in Ripple Counter Example 13-1 Verilog Description of 2-to-1 Multiplexer Example 13-2 PLI Routine to get Module Port List Example 13-3 PL! Routine to Monitor Nets for Value Changes Example 13-4 Consumer Routine for VCL Example -4 Multiplexer itives Example 13-5 User C Routine my_stop_finish Using Utility Routines Example 14-1 RTL for Magnitude Comparator Example 14-2 Gate-Level Description for the Magnitude Comparator Example 14-3 Stimulus for Magnitude Comparator Example 14-4 Simulation Library Example 14-5 Output from Simulation of Magnitude Comparator Example 14-6 RTL Description for Newspaper Vending Machine FSM Example 14-7 Optimized Gate-Level Netlist for Newspaperoxi Foreword From a modest beginning in early 1984 at Gateway Design Automation, the Verilog hardware de- scription language has become an industry standard as a result of extensive use in the design of integrated circuit chips and digital systems. Verilog came into being as a proprietary language sup- ported by a simulation environment that was the first to support mixed-level design representations comprising switches, gates, RTL, and higher levels of abstractions of digital circuits. The simulation environment provided a powerful and uniform method to express digital designs as well as tests that were meant to verify such designs. There were three key factors that drove the acceptance and dominance of Verilog in the market- place. First, the introduction of the Programming Language Interface (PL!) permitted users of Verilog to literally extend and customize the simulation environment. Since then, users have exploited the PLI and their success at adapting Verilog to their environment has been a real winner for Verilog. The second key factor which drove Verilog's dominance came fram Gateways paying close attention to the needs of the ASIC foundries and enhancing Verilog in close partnership with Motorola, Na- tional, and UTMC in the 1987-1989 time-frame. The realization that the vast majority of logic sim- ulation was being done by designers of ASIC chips drove this effort. With ASIC foundries blessing the use of Verilog and even adopting it as their internal sign-off simulator, the industry acceptance of Verilog was driven even further. The third and final key factor behind the success of Verilog was the introduction of Verilog-based synthesis technology by Synopsys in 1987. Gateway licensed its proprietary Verilog language to Synopsys for this purpose. The combination of the simulation and synthesis technologies served to make Verilog the language of choice for the hardware designers. The arrival of the VHDL (VHSIC Hardware Description Language), along with the powerful alignment of the remaining EDA vendors driving VHDL as an IEEE standard, led to the placement of Verilog in the public domain. Verilog was inducted as the IEEE 136d standard in 1995. Since 1995, many enhancements were made to Verilog HDL based on requests from Verilog users. These changes were incorporated into the latest IEEE 1364-2001 Verilog standard. Today, Verilog has become the language of choice for digital design and is the basis for synthesis, verification, and place and route technologies. Samir's book is an excellent guide to the user of the Verilog language. Not only does it explain the language constructs with a rich variety of examples, it also goes into details of the usage of the PLI and the application of synthesis technology. The topics in the book are arranged logically and flow very smoothly. This book is written from a very practical design perspective rather than with a focus simply on the syntax aspects of the language. This second edition of Samir's book is unique in two ways. Firstly, it incorporates all enhancements described in IEEE 1364-2001 standard. This ensures that the readers of the book are working with the latest information on Verilog. Secondly, a new chapter has been added on advanced verification techniques that are now an integral part of Verilog-based methodolagies. Knowledge of these tech- niques is critical to Verilog users who design and verify multi-million gate systems.Foreword xxii | can still remember the challenges of teaching Verilog and its associated design and verification methodologies to users. By using Samir's book, beginning users of Verilog will become productive sooner, and experienced Verilog users will get the latest in a convenient reference book that can refresh their understanding of Verilog. This book is a must for any Verilog user. Prabhu Goel Fosmer President of Gateway Design Automationxxiii Preface During my earliest experience with Verilog HDL, | was looking for a book that could give me a ‘jump start” on using Verilog HDL. | wanted ta learn basic digital design paradigms and the necessary Verilog HDL constructs that would help me build small digital circuits, using Verilog and run simu- lations. After | had gained some experience with building basic Verilog models, | wanted to learn to use Verilog HDL to build larger designs. At that time, | was searching for a book that broadly dis- cussed advanced Verilog-based digital design concepts and reafdigital design methodologies. Fi- nally, when | had gained enough experience with digital design and verification of real IC chips, though manuals of Verilog-based products were available, from time to time, | felt the need for a Verilog HDL book that would act as a handy reference. A desire to fill this need led to the publication of the first edition of this book. Ithas been more thansix years since the publication of the first edition. Many changes have occurred during these years. These years have added to the depth and richness of my design and verification experience through the diverse variety of ASIC and microprocessor projects that I have successfully completed in this duration. | have also seen state-of-the-art verification methodologies and tools evolve to a high level of maturity. The IEEE 1364-2001 standard for Verilog HDL has been approved. The purpose of this second edition is to incorporate the IEEE 1364-2001 additions and introduce to Verilog users the latest advances in verification. | hope to make this edition a richer learning expe- rience for the reader. This book emphasizes breadth rather than depth. The book imparts to the reader a working knowl- edge of a broad variety of Verilog-based topics, thus giving the reader a global understanding of Verilog HDL-based design. The book leaves the in-depth coverage of each topic to the Verilag HDL language reference manual and the reference manuals of the individual Verilog-based products. This book should be classified not only as a Verilog HDL book but, more generally, as a digital design book. It is important to realize that Verilog HDL is only a tool used in digital design. It is the means to an end—the digital IC chip. Therefore, this book stresses the practical design perspective more than the mere language aspects of Verilog HDL. With HDL-based digital design having become a necessity, no digital designer can afford to ignore HDLs. Who Should Use This Book The book is intended primarily for beginners and intermediate-level Verilog users. However, for advanced Verilog users, the broad coverage of topics makes it an excellent reference book to be used in conjunction with the manuals and training materials of Verilog-based products. The book presents a logical progression of Verilog HDL-based topics. It starts with the basics, such as HDL-based design methodologies, and then gradually builds on the basics to eventually reach advanced topics, such as PLI or logic synthesis. Thus, the book is useful to Verilog users with varying levels of expertise as explained below. + Students In logic design courses at universitiesPreface xxiv Part 1 of this book is ideal for a foundation semester course in Verilog HDL-based logic design. Students are exposed to hierarchical modeling concepts, basic Verilog constructs and modeling techniques, and the necessary knowledge to write small models and run simulations. + New Verilog users In the industry Companies are moving to Verilog HDL- based design. Part 1 of this book is a perfect jump start for designers who want to orient their skills toward HDL-based design. + Users with basic Verilog knowledge who need to understand advanced concepts Part 2 of this book discusses advanced concepts, such as UDPS, timing simulation, PLI, and logic synthesis, which are necessary for graduation from small Verilog models to larger designs. + Verllog experts All Verilog topics are covered, from the basics modeling constructs to advanced topics like PLIs, logic synthesis, and advanced verification techniques. For Verilog experts, this book is a handy reference ta be used along with the /EEE Standard Verilog Hardware Deseription Language reference manual. The material in the book sometimes leans toward an Application Specific Integrated Circuit (ASIC) design methodology. However, the concepts explained in the book are general enough to be ap- plicable to the design of FPGAs, PALs, buses, boards, and systems. The book uses Medium Scale Integration (MSI) logic examples to simplify discussion. The same concepts apply to VLSI designs. How This Book Is Organized This book is organized into three parts. Part 1, Basic Verllog Topics, covers all information that a new user needs to build small Verilog madels and run simulations. Note thatin Part 1, gate-level modeling is addressed before behavioral madeling. | have chosen to do so because | think that it is easier for a new user to see a 1-1 correspondence between gate-level circuits and equivalent Verilog descriptions. Once gate-level madeling is understood, a new user can move to higher levels of abstraction, such as data flow madeling and behavioral modeling, without losing sight of the fact that Verilog HDL is a language for digital design and is not a programming language. Thus, a new user starts off with the idea that Verilog is a language for digital design. New users who start with behavioral modeling often tend to write Verilog the way they write their C programs. They sometimes lose sight of the fact that they are trying to represent hardware circuits by using Verilog. Part 1 contains nine chapters Part 2, Advanced Verllog Topics, contains the advanced concepts a Verilog user needs to know to graduate from small Verilog models to larger designs. Advanced topics such as timing simulation, switch-level modeling, UDPs, PLI, lagic synthesis, and advanced verification techniques are cov- ered. Part 2 contains six chapters. Part 3, Appendices, contains information useful as a reference. Useful information, such as strength- level modeling, list of PLI routines, formal syntax definition, Verilog tidbits, and large Verilog exam- ples is included. Part 3 contains six appendices Conventions Used in This Book Table PR-1 describes the type changes and symbols used in this book. Table PR-t. Typographic Conventions Typeface or Symbol Description Examples AaBbCel23 Keywords, system tasks and compiler directives thatareapartef and, nand, $display, ‘define Verilog HDL. daBbCe 123 Emphasis ceil characterization, instantiation Names of signals, moclules, ports, et. fillets, DPF. outPreface XW A few other conventions need to be clarified. + Inthe book, use of Verilog and Verilog HDL refers to the “Verilog Hardware Description Lan- guage.” Any reference to a Verilog-based simulator is specifically mentioned, using words such as Verilog simulator or trademarks such as Verilog-XL or VCS. + The word designeris used frequently in the book to emphasize the digital design perspective. However, it is a general term used to refer to a Verilog HDL user or a verification engineerxxv Acknowledgments The first edition of this book was written with the help of a great many people who contributed their energies to this project. Following were the primary contributors to my creation: Yohn Sanguinetti, Stuart Sutherland, Clifford Cummings, Robert Emberley, Ashutosh Mauskar, Jack McKeown, Dr. Arun Somani, Dr. Michael Ciletti, Larry Ke, Sunil Sabat, Cheng-I Huang, Maqsoodu! Mannan, Ashok Mehta, Dick Herlein, Rita Glover, Ming-Hwa Wang, Subramanian Ganesan, Sandeep Aggarwal, Albert Lau, Samir Sanghani, Kitan Buch, Anshuman Saha, Bill Fuchs, Babu Chitukuri, Ramana Kalapatapu, Karin Ellison and Rachel Borden. | would like to start by thanking all those people once again. For this second edition, | give special thanks to the following people who helped me with the review process and provided valuable feedback: Anders Nordstrom Stefen Boyd Clifford Cummings Harry Foster Yatin Trivedi Rajeev Madhavan John Sanguinetti Dr. Arun Somani Michael McNamara Berend Ozceri Shrenik Mehta Mike Meredith ASIC Consultant Boyd Technology Sunburst Design Verpiex Systems Magma Design Automation Magma Design Automation Forte Design Systems lowa State University Verisity Design Cisco Systems Sun Microsystems Forte Design Systems Lalso appreciate the help of the following individuals:Part 1. Basic Verilog TopicsChapter 1. Overview of Digital Design with Verilog HDL Evolution of Computer-Aided Digital Design Digital circuit design has evolved rapidly over the last 25 years. The earliest digital circuits were designed with vacuum tubes and transistors. Integrated circuits were then invented where logic gates were placed on a single chip. The first integrated circuit (IC) chips were SSI (Small Scale integration) chips where the gate count was very small. As technologies became sophisticated designers were able to place circuits with hundreds of gates on a chip. These chips were called MSI (Medium Scale Integration) chips. With the advent of LSI (Large Scale Integration), designers could put thousands of gates on a single chip. At this point, design processes started getting very com- plicated, and designers felt the need to automate these processes. Electronic Design Automation (EDA)' techniques began te evolve. Chip designers began to use circuit and logic simulation tech- niques to verify the functionality of building blocks of the order of about 100 transistors. The circuits were still tested on the breadboard, and the layout was done on paper or by hand on a graphic computer terminal. With the advent of VLSI (Very Large Scale Integration) technology, designers could design single chips with more than 100,000 transistors. Because of the complexity of these circuits, it was not possible to verify these circuits on a breadboard. Computer-aided techniques became critical for verification and design of VLSI digital circuits. Computer programs to do automatic placement and routing of circuit layouts also became popular. The designers were now building gate-level digital circuits manually on graphic terminals. They would build small building blocks and then derive higher-level blocks from them. This process would continue until they had built the top-level block, Logic simulators came into existence to verify the functionality of these circuits before they were fabricated on chip. As designs got larger and mare complex, logic simulation assumed an important role in the design process. Designers could iron out functional bugs in the architecture before the chip was designed further. Emergence of HDLs For a lang time, programming languages such as FORTRAN, Pascal, and C were being used to describe computer programs that were sequential in nature. Similarly, in the digital design field, designers felt the need for a standard language to describe digital circuits. Thus, Mardware De- scription Languages (HDLs) came into existence. HDLs allowed the designers to model the con- "The earlier editian of the book used the term GAD taals. Technically. the team Computer-Aided Design (CAB) tools refers to back-end tools Inst parform functions relatad to place and raute, and layout of the chip . The term Computer-Aided Engineering (CAE) tools reters to tools that are used for front-end processes such HDL simulation, logic synthesis, and imming analysis. Designers used the lerms CAD and CAE intarenangeably. Today, the tarm Electronic Dasign Automation is used for both CAD and CAE. For tha sake of simplicity, m this book, we will afer to all design tools as EDA tools,Overview of Digital Design with Verilog HDL 3 currency of processes found in hardware elements. Hardware description languages such as Ver- jeg HDL and VHDL became popular. Verilog HDL originated in 1983 at Gateway Design Automa- tion. Later, VHDL was developed under contract from DARPA. Both Verilog® and VHDL simulators to simulate large digital circuits quickly gained acceptance from designers. Even though HDLs were popular for logic verification, designers had to manually translate the HDL- based design into a schematic circuit with interconnections between gates. The advent of logic synthesis in the late 1980s changed the design methodology radically. Digital circuits could be de- scribed at a register transfer level (RTL) by use of an HDL. Thus, the designer had to specify how the data flows. between registers and how the design processes the data. The details of gates and their interconnections to implement the circuit were automatically extracted by logic synthesis tools from the RTL description Thus, logic synthesis pushed the HDLs into the forefront of digital design. Designers no longer had to manually place gates to build digital circuits. They could deseribe complex circuits at an abstract level in terms of functionality and data flow by designing those circuits in HDLs. Logic synthesis tools would implement the specified functionality in terms of gates and gate interconnections. HDLs also began to be used for system-level design. HDLs were used for simulation of system boards, interconnect buses, FPGAs (Field Programmable Gate Arrays), and PALs (Programmable Array Logic). A common approach is to design each IC chip, using an HDL, and then verify system functionality via simulation Today, Verilog HDL is an accepted IEEE standard. In 1995, the original standard IEEE 1364-1995 was approved. IEEE 1364-2001 is the latest Verilog HDL standard that made significant improve- ments to the original standard. Typical Design Flow A typical design flow for designing VLSI IC circuits is shown in Figure 1-1. Unshaded blocks show the level of design representation; shaded blocks show processes in the design flow.Overview of Digital Design with Verilog HDL 4 Design Specification Behavioral Description Functional Verification and Testing y Logic Synthesis/ Timing Verification |__| Gate-Level Netlist v Logical Verification and Testing t Floor Planning Automatic Place and Route ’ Physical Layout a, Layout Verification Implementation Figure 1-1. Typical Design Flow The design flow shown in Figure 1-1 is typically used by designers who use HDLs. In any design, specifications are written first. Specifications describe abstractly the functionality, interface, and overall architecture of the digital circuit to be designed. At this point, the architects do not need to think about how they will implement this circuit. A behavioral description is then created to analyze the design in terms of functionality, performance, compliance to standards, and other high-level issues. Behavioral descriptions are often written with HDLs.2 The behavioral description is manually converted to an RTL description in an HDL. The designer has to describe the data flow that will implement the desired digital circuit. From this point onward, the design process is done with the assistance of EDA tools. 2New EDA toola have emerged to simulate behavioral descriptions of cireults. These tools combine the powerful concepts from HDLs and ‘abject oriented languages such as C++. These tools can be used instead of wring behavioral descriptions in Verlag HDL.Overview of Digital Design with Verilog HDL 5 Logic synthesis tools convert the RTL description to a gate-level netlist. A gate-level netlist is a description of the circuit in terms of gates and connections between them. Logie synthesis tools ensure that the gate-level netlist meets timing, area, and power specifications. The gate-level netlist is input to an Automatic Place and Route tool, which creates a layout. The layoutis verified and then fabricated on a chip. Thus, most digital design activity is concentrated on manually optimizing the RTL description of the circuit. After the RTL description is frozen, EDA tools are available to assist the designer in further processes. Designing at the RTL level has shrunk the design cycle times from years toa few months. Itis also possible to do many design iterations in a short period of time. Behavioral synthesis tools have begun to emerge recently. These tools can create RTL descriptions from a behavioral or algorithmic description of the circuit. As these tools mature, digital circuitdesign will become similar to high-level computer programming. Designers will simply implement the al- gorithm in an HDL ata very abstract level. EDA tools will help the designer convert the behavioral description to a final IC chip. It is important to note that, although EDA tools are available to automate the processes and cut design cycle times, the designer is still the person who controls how the tool will perform. EDA tools are alsa susceptible to the *“G/GO : Garbage In Garbage Out phenamenon. If used improperly, EDA tools will lead to inefficient designs. Thus, the designer still needs to understand the nuances of design methodologies, using EDA tools to obtain an optimized design Importance of HDLs HDLs have many advantages compared to traditional schematic-based design. + Designs can be described ata very abstract level by use of HDLs. Designers can write their RTL description withaut choosing a specific tabrication technology. Logic synthesis tools can auto- matically convert the design to any fabrication technology. If a new technology emerges, de- signers do not need to redesign their circuit. They simply input the RTL description to the logic synthesis tool and create a new gate-level netlist, using the new fabrication technology. The logic synthesis tool will optimize the circuit in area and timing for the new technology. + By describing designs in HDLs, functional verification of the design can be done early in the design cycle, Since designers work at the RTL level, they can optimize and modify the RTL description until it meets the desired functionality. Most design bugs are eliminated at this point. This cuts down design cycle time significantly because the probability of hitting a functional bug ata later time in the gate-level netlist or physical layout is minimized. + Designing with HDLs is analogous to computer programming. A textual description with com- ments is an easier way to develop and debug circuits. This also provides a concise represen- tation of the design, compared to gate-level schematics. Gate-level schematics are almost in- comprehensible for very complex designs. HDL-based design is here to stay. With rapidly increasing complexities of digital circuits and in- creasingly sophisticated EDA tools, HDLs are now the dominant method for large digital designs. No digital circuit designer can afford to ignore HDL-based design Popularity of Verilog HDL Verilog HDL has evolved as a standard hardware description language. Verilog HDL offers many useful features New tools and languages focused an veriieation have emerged in the past few years. Thase languages are better sulted far functional verification. However, for logic design, HDLs continue as the preferred choice,Overview of Digital Design with Verilog HDL 6 + Verilog HDL is a general-purpose hardware description language that is easy to learn and easy to use. It is similar in syntax to the C programming language. Designers with C programming ‘experience will find it easy to learn Verilog HDL. + Verilog HDL allows different levels of abstraction to be mixed in the same model. Thus, a de- signer can define a hardware model in terms of switches, gates, RTL, or behavioral code. Also, a designer needs to learn only one language for stimulus and hierarchical design. + Most popular logic synthesis tools support Verilog HDL. This makes it the language of choice for designers. + All fabrication vendors provide Verilog HDL libraries for postlogic synthesis simulation. Thus, designing a chip in Verilog HDL allows the widest choice of vendors. + The Programming Language Interface (PL!) is a powerful feature that allows the user to write custom C code to interact with the internal data structures of Verilog. Designers can customize a Verilog HDL simulator to their needs with the PLI. Trends in HDLs The speed and complexity of digital circuits have increased rapidly. Designers have responded by designing at higher levels of abstraction. Designers have to think only in terms of functionality. EDA tools take care of the implementation details. With designer assistance, EDA tools have become sophisticated enough to achieve a close-to-optimum implementation. The most popular trend currently is to design in HDL at an RTL level, because logic synthesis tools can create gate-level netlists from RTL level design. Behavioral synthesis allowed engineers to design directly in terms of algorithms and the behavior of the circuit, and then use EDA tools te do the translation and optimization in each phase of the design. However, behavioral synthesis did not gain widespread acceptance. Today, RTL design continues to be very popular. Verilag HDL is also being constantly enhanced to meet the needs of new verification methodologies. Formal verification and assertion checking techniques have emerged. Formal verification applies formal mathematical techniques to verify the correctness of Verilog HDL descriptions and to estab- lish equivalency between RTL and gate-level netlists. However, the need to describe a design in Verilog HDL will not go away. Assertion checkers allow checking to be embedded in the RTL code. This is a convenient way to do checking in the most important parts of a design. New verification languages have also gained rapid acceptance. These languages combine the par- allelism and hardware constructs from HDLs with the object oriented nature of C++. These lan- guages also provide support for automatic stimulus creation, checking, and coverage. However, these languages do not replace Verilog HDL. They simply boost the productivity of the verification process. Verilog HDL is still needed to describe the design For very high-speed and timing-critical circuits like microprocessors, the gate-level netlist provided by logic synthesis tools is not optimal. In such cases, designers often mix gate-level description directly into the RTL description to achieve optimum results. This practice is oppasite to the high- level design paradigm, yet it is frequently used for high-speed designs because designers need to squeeze the last bit of timing out of circuits, and EDA tools sometimes prove to be insufficient to achieve the desired results. Anather technique that is used far system-level design is a mixed bottom-up methodology where the designers use either existing Verilog HDL modules, basic building blocks, or vendor-supplied core blocks ta quickly bring up their system simulation. This is done to reduce development costs and compress design schedules. For example, consider a system that has a CPU, graphics chip, VO chip, and a system bus. The GPU designers wauld build the next-generation CPU themselvesOverview of Digital Design with Verilog HDL 7 at an RTL level, but they would use behavioral models for the graphics chip and the VO chip and would buy a vendor-supplied model for the system bus. Thus, the system-level simulation for the CPU could be up and running very quickly and long before the RTL descriptions for the graphics chip and the I/O chip are completed.Chapter 2. Hierarchical Modeling Concepts Before we discuss the details of the Verilog language, we must first understand basic hierarchical modeling concepts in digital design. The designer must use a "good" design methodology to do efficient Verilog HDL-based design. In this chapter, we discuss typical design methodologies and illustrate how these concepts are translated to Verilog. A digital simulation is made up of various components. We talk abaut the components and their interconnections. Learning Objectives + Understand top-down and bottom-up design methodologies for digital design. + Explain differences between modules and module instances in Verilog. + Describe four levels of abstraction—behavioral, data flow, gate level, and switch level—to rep- resent the same module. + Describe components required for the simulation of a digital design. Define a stimulus block and a design block. Explain two methods of applying stimulus. Design Methodologies There are two basic types of digital design methodologies: a top-down design methodology and a bottom-up design methodology. In a top-down design methodology, we define the top-level block and identify the sub-blocks necessary to build the top-level block. We further subdivide the sub- blocks until we come to leaf cells, which are the cells that cannot further be divided. Figure 2-1 shows the top-down design process. Top-level 7 * a sub- sub- block 3 block 4 leaf leaf leat leaf leaf leaf cell cell cell cell cell cell cell Figure 2-1. Top-down Design Methodology In a bottom-up design methodology, we first identify the building blocks that are available to us. We build bigger cells, using these building blocks. These cells are then used for higher-level blocks until we build the tap-level block in the design. Figure 2-2 shows the bottom-up design processHierarchical Modeling Concepts 9 Top-level macro macro macro | mac cell 2 cell 3 cell 4 leat leat leat cell cell cell Figure 2-2. Bottom-up Besign Methodology Typically, a combination of top-down and bottom-up flows is used. Design architects define the specifications of the top-level block. Logic designers decide how the design should be structured by breaking up the functionality into blocks and sub-blocks. Al the same time, circuit designers are designing optimized circuits for leaf-level cells. They build higher-level cells by using these leaf cells. The flow meets at an intermediate point where the switch-level circuit designers have created a library of leaf cells by using switches, and the logic level designers have designed from top-down until all modules are defined in terms of leaf cells, To illustrate these hierarchical modeling concepts, let us consider the design of a negative edge- triggered 4-bit ripple carry counter described in Section 2.2, 4-bit Ripple Carry Counter 4-bit Ripple Carry Counter The ripple carry counter shown in Figure 2-3 is made up of negative edge-triggered toggle flipflaps (7_F8). Each of the T_FFs can be made up from negative edge-triggered D-tlipflops (D_FF) and verters (assuming q_baroutput is not available on the O_FF), as shown in Figure 2-4. Ripple 0 3 Carry q ql 2 4 Counter jp Sg ee Se 4 I I | 4. q q | clock ——-C)) 7 _FF LoS 7 EF > T_EF| | | +f 12 tff3 I | | | | ! Teset T | eee eee See ee ee ee ee 4 Figura 2-3. Ripple Camy CounterHierarchical Modeling Concepts 10 T_FF poo | <4 1 0 0 0 0 1 clock =—o) | 0 1 0 | 0 0 0 ——— reset Figure 2-4. T-fiptop Thus, the ripple carry counter is built in a hierarchical fashion by using building blocks. The diagram for the design hierarchy is shawn in Figure 2-5. pple Carry ‘ounte DIFF) | tener ate liveries DIFF] | merter D_FF gate gate Figure 2-5. Besign Hierarchy In a top-down design methodology, we first have to specify the functionality of the ripple carry coun- ter, which is the top-level block. Then, we implement the counter with 7_FFS. We build the 7_FFs from the B_FF and an additional inverter gate. Thus, we break bigger blacks into smaller building sub-blocks until we decide that we cannot break up the blacks any further. A bottom-up methodology flows in the opposite direction. We combine small building blocks and build bigger blocks; e.g., we could build 2 FF from and and or gates, or we could build a custom D_FF from transistors. Thus, the bottom-up flow meets the top-down flow at the level of the DF. Modules We now relate these hierarchical modeling concepts to Verilog. Verilog provides the concept of a module. A module is the basic building block in Verilog. A module can be an element or a collection of lower-level design blocks. Typically, elements are grouped into modules to provide common functionality thatis used at many places in the design. A module provides the necessary functionality to the higher-level block through its port interface (inputs and outputs), but hides the internal impie- mentation. This allows the designer to modify module internals without affecting the rest of the design.Hierarchical Madeling Concepts 1 In Figure 2-5, ripple carry counter, T_FF, D_#F are examples of modules. In Verilog, a module is declared by the keyword module. A corresponding keyword endmodule must appear at the end of the module definition. Each module must have a madule_name, which is the identifier for the madule, and a module_terminal_list, which describes the input and output terminals of the module. module
module / NESTING endmodule Components of a Simulation Once a design block is completed, it must be tested. The functionality of the design block can be tested by applying stimulus and checking results. We call such a block the stimulus block. Itis good practice to keep the stimulus and design blocks separate. The stimulus block can be written in Verilog. A separate language is not required to describe stimulus. The stimulus block is also commonly called a test bench. Different test benches can be used to thoroughly test the design block Two styles of stimulus application are possible. In the first style, the stimulus block instantiates the design block and directly drives the signals in the design block. In Figure 2-6, the stimulus block becomes the top-level block. It manipulates signals cand reset, and it checks and displays output signal ¢. (Stimulus Block) clk reset (Design Block) Ripple Carry Counter Figure 2-8, Stimulus Block instantiates Design Block The second style of applying stimulus is to instantiate both the stimulus and design blocks in a top- level dummy module. The stimulus block interacts with the design block only through the interface. This style of applying stimulus is shown in Figure 2-7. The stimulus module drives the signals d_clkand d_resel, which are connected to the signals cikand resefin the design block. Italso checks and displays signal ¢_g, which is connected to the signal q in the design block. The function of top- level block is simply to instantiate the design and stimulus blocks.Hierarchical Modeling Concepts 14 Top-Level Block d_clk clk Stimulus Block — d_reset Design Block Ripple Carry Counter reset Figure 2-7. Stimulus and Design Blocks instantiated in a Dummy Top-Level Module Either stimulus style can be used effectively. Example To illustrate the concepts discussed in the previous sections, let us build the complete simulation of a ripple carry counter. We will define the design block and the stimulus block. We will apply stimulus to the design block and monitor the outputs. As we develop the Verilog models, you do not need to understand the exact syntax of each construct at this stage. At this point, you should simply try to understand the design process. We discuss the syntax in much greater detail in the later chapters. Design Block We use a top-down design methodology. First, we write the Verilog description of the top-level design block (Example 2-3), which is the 2 counter (see Section 2.2, 4-b Ripple rry Counter). Example 2-3. Ripple Carry Counter Top Block module ripe: teria, clk, reset); t (3:0) 4 ut clk, reset; /4 instances of the module TFF are created. che lO), reser); rele, 26 endaedule In the above module, four instances of the module 7_FF (T-flipflop) are used. Therefore, we must now define (Example 2-4) the internals of the module 7_FF, which was shown in Figure 2-4Hierarchical Modeling Concepts 15 Example 2-4. Fliptop T_FF module T_FE(q, clk, reseths output a; ik, resets d, clk, reset); i Uf not is 4 Verdleg-provided ps Since 7_FF instantiates D_FF, we must now define (Example 2-5) the internals of module D_FF. We assume asynchronous reset for the O_FFF. Example 2-5. Fiipitop DF / module D_FF with aynchvonous reset module D_FE(q, d, elk, reget}; output ai 4, clk, reset: rea qi / Lots of new constructs. Ignore the £ tonality of the trate on how the design block ie bu! t dns top-down fagnion. always @(posedge reset ar negedge clk) if (reget) @ ce L*bO; else a eadacdule All modules have been defined down to the lowest-level leaf cells in the design methodology. The design block is now complete. Stimulus Block We must now write the stimulus block to check if the ripple camy counter design is functioning correctly. In this case, we must control the signals c/k and resetso that the regular function of the ripple carry counter and the asynchronous reset mechanism are both tested. We use the waveforms shown in Figure 2-8 to test the design. Waveforms for clk, reset, and 4-bit output q are shown. The cycle time for cikis 10 units; the resetsignal stays up from time 0 to 15 and then goes up again from time 195 to 205. Qutput g counts from 0 to 15. clk L LI uA w= | | y wn C XXX CX IECO) Figure 2-8. Stimulus and Quieut Waveforms We are now ready to write the stimulus block (see Example 2-6) that will create the above wave- forms. We will use the stimulus style shown in Figure 2-6. Do not worry about the Verilog syntax at this point. Simply concentrate on how the design block is instantiated in the stimulus block.Hierarchical Madeling Concepts 16 Example 2-6. Stimulus Block module stimulus; reg clkr keg veset; e130] 4 7d Snatantiate the design Block ripple, er rliq, clk, reset); J control 1 that drives the deeign bleck. Cyele time = 10 elk ~ 1'bO; //eet elk te 0 always #5 clk = ~c1ke units le clk every 5 tin reset signal that drives the design block t ia asserted Fram 0 to 20 and fom 200 ta 220. = 1b; #15 reset = 1'B0; #1E0 reset - Lbiy #1 eeset ~ 1'b0; 420 $finisn; //terminate the simulation end f/ Monitor the oupute Smonitor ($time, endmedule Once the stimulus block is completed, we are ready to run the simulation and verify the functional correctness of the design block. The output obtained when stimulus and design blocks are simulated is shown in Example 2-7. Example 2-7. Ouiput of the Simulation a- 0 Summary In this chapter we discussed the following concepts.Hierarchical Madeling Concepts 17 + Two kinds of design methodologies are used for digital design: top-down and bottom-up. A combination of these two methodologies is used in today’s digital designs. As designs become very complex, it is important to follow these structured approaches to manage the design proc- ess. + Modules are the basic building blocks in Verilog. Modules are used in a design by instantiation. An instance of a module has a unique identity and is different from other instances of the same module. Each instance has an independent copy of the internals of the module. It is important to understand the difference between modules and instances + There are two distinct components in a simulation: a design block and a stimulus block. A stim- ulus block is used to test the design block. The stimulus block is usually the top-level block. ‘There are two different styles of applying stimulus to a design block. + The example of the ripple carry counter explains the step-by-step process of building all the blocks required in a simulation This chapter is intended to give an understanding of the design process and how Verilag fits into the design process. The details of Verilag syntax are not important at this stage and will be dealt with in later chapters. Exercises 4: An interconnect switch (/5) contains the following components, a shared memory (MEM), a sys- tem controller (SC) and a data crossbar (Xbar) a. Define the modules MEM, SC, and Xbar, using the module/endmodule keywords. You do not need to define the internals. Assume that the modules have no terminal lists. b. Define the module /S, using the module/endmodule keywords. Instantiate the madules MEM, SC, Xbarand call the instances mem, scf, and xbar1, respectively. You do not need to define the internals. Assume that the module /S has no terminals c. Define a stimulus block (Top), using the module/endmodule keywords. Instantiate the design block /S and call the instance /s7. This is the final step in building the simulation environment. 2: A 4-bit ripple carry adder (Ripple_Add) contains four 1-bit full adders (FA). a. Define the module FA. Do not define the internals or the terminal list. b. Define the module Ripple_Add. Do not define the internals or the terminal list. instantiate four full adders of the type FA in the module Aipple_Addand call them f20, fat, fa2, and 3.18 Chapter 3. Basic Concepts In this chapter, we discuss the basic constructs and conventions in Verilog. These conventions and constructs are used throughout the later chapters. These conventions provide the necessary frame- work for Verilog HDL. Data types in Verilog model actual data storage and switch elements in hard- ware very closely. This chapter may seem dry, but understanding these concepts is a necessary foundation for the successive chapters. Learning Objectives + Understand lexical conventions for operators, comments, whitespace, numbers, strings, and identifiers. + Define the logic value set and data types such as nets, registers, vectors, numbers, simulation time, arrays, parameters, memories, and strings. + Identify useful system tasks for displaying and monitoring information, and for stopping and finishing the simulation. + Learn basic compiler directives to define macros and include files. Lexical Conventions The basic lexical conventions used by Verilog HDL are similar to those in the C programming lan- guage. Verilog contains a stream of takens. Tokens can be comments, delimiters, numbers, strings, identifiers, and keywords. Verilog HDL is a case-sensitive language. All keywords are in lowercase. Whitespace Blank spaces (|6) , tabs (| and newlines (In) comprise the whitespace. Whitespace is ignored by Verilog except when it separates tokens. Whitespace is not ignored in strings. Comments Comments can be inserted in the code for readability and documentation. There are two ways to write comments. A one-line comment starts with *// “ Verilog skips from that point to the end of line. A multiple-liné comment starts with */* "and ends with “*/*. Multiple-line comments cannot be nested. However, one-line comments can be embedded in multiple-line comments. a= b G8 cr ff This de @ one-line commen ultiple Line This le J* am 4ilegal */ comment * * This te //a Legal commentBasic Concepts 19 Operators Operators are of three types: unary, binary, and temary. Unary operators precede the operand. Binary operators appear between two operands. Temary operators have two separate operators that separate three operands. ashy isa or. bis the operand an btee: ff te ie operator. b and c perands a-b2c: 4; // 2: 48 ternary operator. b, ¢ and d are operands Number Specification There are two types of number specification in Verilog: sized and unsized. Sized numbers Sized numbers are represented as
'
.
is written only in decimal and specifies the number of bits in the number. Legal base formats are decimal (‘dor 2), hexadecimal (4 ar ‘H), binary (’b or 'B) and octal (‘0 or ‘O). The number is specified as consecutive digits fram 0, 7, 2. 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f Only a subset of these digits is legal for a particular base. Upperease letters are legal for number specification a A 16-bit deeinal number Unsized numbers Numbers that are specified without a
specification are decimal numbers by default. Numbers that are written without a
specification have a default number of bits that is simu- lator- and machine-specific (must be at least 32). 23086 // This is a $2-bie decimal by defaut thea // Tha is 4 32-bit hexadeed: X or Z values Verilog has two symbols for unknown and high impedance values. These values are very important for madeling real circuits. An unknown value is denoted by an x. A high impedance value is denoted by z umber; 4 32"be // Th pedance nu An x or & sets four bits for a number in the hexadecimal base, three bits far a number in the octal base, and one bit for a number in the binary base. If the most significant bit of a number is 0, x, or z, the number is automatically extended to fill the most significant bits, respectively, with 0, x, or z. This makes it easy to assign x or z to whole vector. If the most significant digit is 1, then itis also zero extended. Negative numbers Negative numbers can be specified by putting a minus sign before the size for a constant number. Size constants are always positive. It is illegal to have a minus sign between
and
. An optional signed specifier can be added for signed arithmetic.Basic Concepts 20 “6143 // B-bic negat -8'sd3 // Used far performing signed integer math a'a-2 // Illegal specstleario: e number stored as 2'8 Lement of 3 Underscore characters and question marks An underscore character "_" is allowed anywhere in a number except the first character. Underscore characters are allowed only to improve readability of numbers and are ignored by Verilog. A question mark "2" is the Verilog HDL alternative for z in the context of numbers. The ? is used to enhance readability in the casex and casez statements discussed in Chapter 7, where the high impedance value is a don't care condition. (Note that ? has a different meaning in the context of user-defined primitives, which are discussed in Chapter 12, User-Defined Primitives.) LO // Use of underline characters foe veadabiliey nt of a a Strings A string is a sequence of characters that are enclosed by double quotes. The restriction on a string is that it must be contained on a single ling, that is, without a carriage return. It cannot be on multiple lines. Strings are treated as a sequence of one-byte ASCII values. sueLie leg Waela" // de a aveing "a fet {/ ie a etxing Identifiers and Keywords Keywords are special identifiers reserved to define the language constructs. Keywords are in low- ercase. A list of all keywords in Verilog is contained in Appendix C, Listof Keywords, System Tasks, and Compiler Directives. Identifiers are names given to objects so that they can be referenced in the design. Identifiers are made up of alphanumeric characters, the underscore (__), or the dollar sign (¢ ). Identifiers are case sensitive. Identifiers start with an alphabetic character or an underscore. They cannot start with a digit or a $ sign (The § sign as the first character is reserved for system tasks, which are explained later in the book). reg value; // req is @ keyword; velue is an identifier ak; f/ inp is a keyword, 21 an iden Escaped Identifiers Escaped identifiers begin with the backslash (\) character and end with whitespace (space, tab, or newline). All characters between backslash and whitespace are processed literally. Any printable ASCII character can be included in escaped identifiers. Neither the backslash nor the terminating whitespace is considered to be a part of the identifier. Data Types This section discusses the data types used in Verilog.Basic Concepts 24 Value Set Verilog supports four values and eight strengths to model the functionality of real hardware. The four value levels are listed in Table 3-1 Table 3-1. Value Levels Value Level Condition in Hardware Circuits a Logie zero, false condition 1 Logie one, tras condition x Unknown logic value z High impedance, In addition to logic values, strength levels are often used to resolve conflicts between drivers of different strengths in digital circuits. Value levels 0 and 1 can have the strength levels listed in Table 3-2. Tablo 3.2, Strength Lovels strength Level Type Degree supply Driving strongest strong, Driving A pull Driving lange Storage weak Driving medium Storage small Storage highs High Impedance weakest If two signals of unequal strengths are driven on a wire, the stronger signal prevails. For example, if two signals of strength strong1 and weak0 contend, the result is resolved as a strong]. If two signals of equal strengths are driven on a wire, the result is unknown. If two signals of strength strongl and streng0 conflict, the resultis an x. Strength levels are particularly useful for accurate madeling of signal contention, MOS devices, dynamic MOS, and other law-level devices. Only trireg nets can have storage strengths large, medium, and sma11. Detailed information about strength modeling is provided in Appendix A, Strength Modeling and Advanced Net Definitions. Nets Nets represent connections between hardware elements. Just as in real circuits, nets have values continuously driven on them by the outputs of devices that they are connected to. In Figure 3-1 net ais connected to the output of and gate g7. Net a will continuously assume the value computed at the output of gate g7, which is b& o. b c Figure 3-1. Example of NetsBasic Concepts 22 Nets are declared primarily with the keyword wire. Nets are one-bit values by default unless they are declared explicitly as vectors. The terms wire and net are often used interchangeably. The default value of a net is 2 (except the trireg net, which defaults to x ). Nets get the output value of their drivers. If a net has no driver, it gets the value z by d- 1'bO; // Net dis fixed ta logic val wa et fort Note that netis not a keyword but represents a class of data types such as wire, wand, wor, tri, triand, trior, trireg, etc. The wire declaration is used most frequently. Other net declarations are discussed in Appendix A, Strength Modeling and Advanced Net Definitions. Registers Registers represent data storage elements. Registers retain value until another value is placed anto them. Do not confuse the term registersin Verilog with hardware registers built from edge-triggered flipflops in real circuits. In Verilog, the term registermerely means a variable that can hold a value. Unlike a net, a register does not need a driver. Verilog registers do not need a clock as hardware registers do. Values of registers can be changed anytime in a simulation by assigning a new value to the register. Register data types are commonly declared by the keyword reg. The default value for a reg data type is x. An example of how registers are used is shown Example 3-1 Example 3-1. Example of Register reg reget; // declare a variable reset that can hold ite value asteuct will be discussed lates begin 2 100 Eile units vese Registers can also be declared as signed variables. Such registers can be used for signed arith- metic. Example 3-2 shows the declaration of a signed register. Example 3-2. Signed Register Dectaration reg aigned [64:0] mz /# integer 1; // 42 bit atgnea Vectors Nets or reg data types can be declared as vectors (multiple bit widths). If bit width is not specified, the default is scalar (41-bit) s of 32-bit width. reg clock; reg [0:40] a" / or register, virtual address 41 bi Vectors can be declared at [Aigh# :/ow#or [lows : highs, but the left number in the squared brackets is always the most significant bit of the vector. In the example shown above, bit 0 is the most sig- nificant bit of vector virtual_addr. Vector Part Select For the vector declarations shown above, it is possible to address bits or parts of vectors.Basic Concepts 23 busa[7] // ble #7 of vector bu bus [2:0] // Three least 5 // uaieg bus (0:2) is 11h ecause the significant bLt should #/ alvays be o: a range specificatian ¥ addr [0:1] // Iwo most significant bits of vector virtual_edde v iable Vector Part Select Another ability provided in Verilog HDI is to have variable part selects of a vector. This allows part selects to be put in for loops to select various parts of the vector. There are two special part-select operators: Fsstarting_bit>+:width] - part-select increments from starting bit [
-.width}- part-select decrements from starting bit The starting bit of the part select can be varied, but the width has to be constant. The following example shows the use of variable vector part select: eq [255:0) datal; /fLitele endian notation reg [0:255) dataz; //Big endian notation reg 17:0] byter fling 4 variable part select, one can choose parts byte - datal(a1-:8); //startiag bit - 31, width -@ -» data(31:24) @ = datal[20+:8); //etarting Bit = 24, wideh m8 => data( 31:2 ¢ - data2(31-:8}; //starting bit ~ 31, width a -» data[24:31) byte ~ data2(2d+:8]; //etartiag Bit ~ 24, wideh ~@ ~> daea( 24:32) //The starting bit can also be a variable. The width hag fhe be constant. Therefore, one can use the variable part select /An @ loop te 2 ect ali bytes of the vector fox (j-Os j
fSequence Hay, 0 -. (2582248) /Oan initialize a part of the vector faral{(bytetumes)+:8) = 8'bO; ¢/I£ byrewum = 1, clear @ bite [15:8 Integer , Real, and Time Register Data Types Integer, real, and time register data types are supported in Verilog. Integer An integer is a general purpose register data type used for manipulating quantities. Integers are declared by the keyword integer. Although itis possible to use reg as a general-purpose variable, it is more convenient to declare an integer variable for purposes such as counting. The default width for an integer is the host-machine word size, which is implementation-specific but is at least 32 bits. Registers declared as data type req store values as unsigned quantities, whereas integers store values as signed'quantities. integer counter; // general purpose variable used as a counter. counter ~ -1; // A negative one is stored in the counter Real Real number constants and real register data types are declared with the keyword real. They can be specified in decima/ notation (e.g., 3.14) or in scientific notation (e.g., 366, which is 3 x 10°). Real numbers cannot have a range declaration, and their default value is 0. When a real value is assigned to an integer, the real number is rounded off to the nearest integer.Basic Concepts 24 // Define a real variable called delta jelta = 4e10; // delta is assigned in scientiric notation delta ~ 2.13; // delta is assigned a v end integer 4; // Define an integer 4 Jf 4 gets the value 2 (rounded value of 2.13) Verilog simulation is done with respect to simulation time. A special time register data type is used in Verilog ta store simulation time. A time variable is declared with the keyword time. The width for time register data types is implementation-specific but is at least 64 bits.The system function $time is invoked to get the current simulation time. fe_sim_time; // Define @ time variable save_eim tine save gim time = stimer // Save the current simulation time Simulation time is measured in terms of simulation seconds. The unit is denoted by s, the same as real time. However, the relationship between real time in the digital circuit and simulation time is left to the user. This is discussed in detail in Section 9.4, Time Scales, Arrays Arrays are allowed in V 9 for reg, integer, time, real, realtime and vecfor register data types. Multi-dimensional arrays can also be declared with any number of dimensions. Arrays of nets can also be used to connect ports of generated instances. Each element of the array can be used in the same fashion as a scalar or vector net. Arrays are accessed by
{
] . For multidimensional arrays, indexes need to be provided for each dimension. integer count (0:77 // An array of @ count variaples reg bacl (31:0)? // Array ef 32 one-bit boolean register variables tine chk peiat[1:100}7 // Array of 10D time checkpoint varlables eg [4:0] port_4d{0:7]; // Arcay of @ port_ider each port_id is $ bits « integer matrix[4:0] [02255]; /f Two dimensi errey of integers req [63:0] array 4d [1520)[7:0] [720] [28820]? //Four dimengional a wise [7:0] ware 5:0]; // Declave an array of 8 bit vector wire wire woarrayl[7:0)[5:0]7 // Declare an array of single bit wires Itis important not to confuse arrays with net or register vectors. A vector is a single element that is bits wide. On the other hand, arrays are multiple elements that are 7-bit or bits wide. Examples of assignments to elements of arrays discussed above are shown below count ($1 = 0; paint time check point va. port_id[3] = / Reset ird element (a S-bit value) of port_id array. matrix(1](0] = 335597 // Set value of element indexed by [1] [0] te 33559 array_¢d[0) {0} [0] [0] {15:0) = sClear bit 0 of register faccesaed by indices [0] [01 [01 port_id = Tilegal eyntax - attempt to write the entire array nateix [2] = @ [1] 00] -- (1) 1285] # Thlegal systax - attenBasic Concepts 25 Memories In digital simulation, one often needs to model register files, RAMs, and ROMs. Memories are mod- eled in Verilog simply as a one-dimensional array of registers. Each element of the array is known as an element or word and is addressed by a single array index. Each word can be one or more bits. It is important to differentiate between rr 1-bit registers and one mbit register. A particular word in memory is obtained by using the address as a memory array subscript. veg memIble [021023]; // Memory mewibit with 1K 1-Bit words reg [7:0] membyte(0:1023) // Memory menbyte with 1K a-pit words (hytest byte [$12] // Fetches 1 byte word wi ae adder Parameters Verilog allows constants to be defined in a module by the keyword parameter. Parameters cannot be used as variables. Parameter values for each module instance can be overridden individually at compile time. This allows the module instances to be customized. This aspect is discussed later. Parameter types and sizes can also be defined fines a constant port_id es width of cache Line ange fer parameter parameter port_id = 5 parameter cache_line_w parameter gigned (15:0) Module definitions may be written in terms of parameters. Hardcoded numbers should be avoided. Parameters values can be changed at module instantiation or by using the defparam statement, which is discussed in detail in Chapter 9, Useful Modeling Techniques. Thus, the use of parameters makes the module definition flexible. Module behavior can be altered simply by changing the value of a parameter. Verilog HDL local parameters (defined using keyword 1ocalparam -) are identical to parameters except that they cannot be directly modified with the defparam statement or by the ordered or named parameter value assignment. The localparam keyword is used to define parameters when their values should not be changed. For example, the state encoding for a state machine can be defined using localparam. The state encoding cannot be changed. This provides protection against inadvertent parameter redefinition. localperan statel ~ 4*b0001, = 4%90010, state3 = 4'b0100, abated ~ 4" Strings Strings can be stored in reg. The width of the register variables must be large enough to hold the string. Each character in the string takes up & bits (1 byte). If the width of the register is greater than the size of the string, Verilog fills bits to the left of the string with zeros. If the register width is smaller than the string width, Verilog truncates the leftmost bits of the string. It is always safe to declare a string that is slightly wider than necessary Declave a variable that ds 18 bytes wide stored la"; // String in variable lo Verileg War Special characters serve a special purpose in displaying strings, such as newline, tabs, and dis- playing argument values. Special characters can be displayed in strings only when they are prece- ded by escape characters, as shown in Table 3-3Basic Concepts 26 Table 3-9. Special Characters Escaped Characters Character Displayed in newline t tab % \o00 Character written in 1-3 octal digits System Tasks and Compiler Directives In this section, we introduce two special concepts used in Verilog: system tasks and compiler di- rectives System Tasks Verilog provides standard system tasks for certain routine operations. All system tasks appear in the form $
. Operations such as displaying on the screen, monitoring values of nets, stopping, and finishing are done by system tasks. We will discuss only the most useful system tasks. Other tasks are listed in Verilog manuals provided by your simulator vendor or in the /EEE Standard Verilog Hardware Description Language specification Displ information $di splay is the main system task for displaying values of variables or strings or expressions. This is one of the most useful tasks in Verilog, Usage: $display/(p?, p2, p3......, pn), pt, p2, p3,..., prcan be quoted strings or variables or expressions. The format of $display is very similar to print¢ in G. A $di splay inserts a newline at the end of the string by default. A §dis- play without any arguments produces a newline. Strings can be formatted using the specifications listed in Table 3-4. For more detailed specifica- tions, see /EEE Standard Verilog Hardware Description Language specification Table 3-4. String Format Specifications Format Display ad or YE) Display variable in decimal hla 0 Display variable in binary Display string Display variable in hex Display ASCII character Display hierarchical name (no argument required) Display strength Display variable in octal Sit or%T Display in current time format we or %E Display real number in scientific format (eg. 3¢10) for %F Display real number in decimal format (e., 2.13) Stag or Display real number in scientific or decimal, whichever is shorterBasic Concepts a7 Example 3-3 shows some examples of the $display task. If variables contain x or z values, they are printed in the displayed string as “x” or "z Example 3-3. Sdisplay Task /Display the str Sdisplay ("Hello Veriiog Wo: == Hello Verilog wor ng in quotes m1 ay value of current cimation time 230 Sdigplay ($time) ; =~ 230 ey value of di-bit virtual address ireadoaodic at time 200 D:40] virtwal_adde; Sdisplay ("At time ¥d virtual address ie an", $time, virtual_addr) > == At time 200 virtual addze: igepogo0o1e ay value of port_id 5 in binary veg [4:0] pore tay Sdigplay ("ID af the port 42 4b", part say; -- ID of the port is 00102 Display x characters /Display value af d-bit bus 10xx (signal contention) in binary veg [3:0] bu fdisplay("Bus value és tb", bus) -- Bus value Le lOxx ‘Display the hierarchical name of instance pi instantiated under ythe highest-level medule called top. No argument 1e required. This ‘Ag a userul ceaturer display ("This ateiag 1s displayed from 4m level of hieraveny") j == Thig etring ie dieplayed from top.pl level of nierareny Special characters are discussed in Section 3.2.9, Strings. Examples of displaying special charac- ters in strings as discussed are shown in Example 3-4. Example 3-4. Special Characters sDisplay special ehavacters, newline and 4 Sdisplay("Thie ie a \n multiline string with a ¥t sian"); -- This dea + multiline gtring with a & eigen /Display ethee special chavacters Monitoring information Verilog provides a mechanism to monitor a signal when its value changes. This facility is provided by the monitor task Usage. Smonitor(p1,p2,p33.,.....pN); The parameters £1, p2, ... , pn can be variables, signal names, or quoted strings. A format similar to the $disp1ay task is used in the $monitor task. $monitor continuously monitors the values of the variables or signals specified in the parameter list and displays all parameters in the list whenever the value of any one variable or signal changes. Unlike $display, monitor needs to be invoked only once. Only one monitoring list can be active at a time. If there is more than one $monitor statement in your simulation, the last $monitor statement will be the active statement. The earlier $monitor statements will be overridden. Two tasks are used to switch monitoring on and off. Usage. $monitoron;Basic Concepts 28 Smonitorese: The $monitoron tasks enables monitoring, and the $moni torof £ task disables monitoring during a simulation. Monitoring is turned on by default at the beginning of the simulation and can be con- trolled during the simulation with the §monitoron and $monitorof€ tasks. Examples of moni- toring statements are given in Example 3-5. Note the use of $time in the $monitor statement. Example 3-5. Monitor Statement fiManitor time and value of the signals clock and reset fOlock baggies every 5 tine unite and eeset goes dows at LO tine units beain Gmonitar (Stine, Value of signals clock ~ th reset ~ ab", clock, resety; Partial output of the monitor statement: alue of signals clock = 0 reset = 1 ef signals clock ~ 1 reset - 1 Value f signals clock - 0 eeset - 0 Stopping and finishing in a simulation The task $stop is provided to stop during a simulation, Usage: Sstop; The $stop task puts the simulation in an interactive mode. The designer can then debug the design from the interactive mode. The §stop task is used whenever the designer wants to suspend the simulation and examine the values of signals in the design The $£inish task terminates the simulation. Usage: $finish: Examples of $stop and $£inish are shown in Example 3-6. Example 3-8. Stap and Finish Tasks {Stop at time 100 sn the simulation and examine ene cesuLes Yu the simulation at time 100 dnd 4/ to be explained later. time - 0 begin clack = 0; -4; eimulat tine = 100 at time ~ 1000 1 sf This will auapend ¢ sh; #/ This will termine Compiler Directives Compiler directives are provided in Verilog. All compiler directives are defined by using the “
construct. We deal with the two most useful compiler directives. “define The ‘define directive is used to define text macros in Verilog (see Example 3-7). The Verilog compiler substitutes the text of the macro wherever it encounters a *
. This is similar to the #define construct in C. The defined constants or text macros are used in the Verilog code by preceding them with a * (back tick)Basic Concepts 29 Example 9-7. ‘define Directive that defines default wor in the cede fdeeine 2 liag. A Setop Will be eubetituted wherever "S appears ‘define § Sstep; fdecine a £ bo eteing ‘de. b register ae "Wt reg327 ‘include The ~inelude directive allows you to include entire contents of a Verilog source file in another Verilog file during compilation. This works similarly to the #incfude in the C programming language. This directive is typically used to include header files, which typically contain global or commonly used definitions (see Example 3-8) Example 3-8. i f tneiude t which contains declarations in the log code in File design.w> Two other directives, “ifdef and ‘timeseale, are used frequently. They are discussed in Chap- ter 9, Usefut Modeling Techniques. Summary We discussed the basic concepts of Verilog in this chapter. These concepts lay the foundation for the material discussed in the further chapters + Verilog is similar in syntax te the C programming language . Hardware designers with previous C programming experience will find Verilag easy to learn + Lexical conventions for operators, comments, whitespace, numbers, strings, and identifiers were discussed + Various data types are available in Verilog. There are four logic values, each with different strength levels. Available data types include nets, registers, vectors, numbers, simulation time, arrays, memories, parameters, and strings. Data types represent actual hardware elements very closely. + Verilog provides useful system tasks to do functions like displaying, monitoring, suspending and finishing a simulation. + Compiler directive * define is used to define text macros, and ~incLude is used to include ‘other Verilog files. xercises 4: Practice writing the following numbers: a. Decimal number 123 as a sized 8-bit number in binary. Use _ for readability. b. A 16-bit hexadecimal unknown number with all x'sBasic Concepts 30 Gs d. A 4-bit negative 2 in decimal . Write the 2's complement form for this number. An unsized hex number 7234. 2: Are the following legal strings? If not, write the correct strings. a b. cy 4. “This is a string displaying the % sign” “out = int + in?” ‘Please ring a bell 007" “This is a backslash | characterin” 3; Are these legal identifiers? a. b. c. qa. system? treg $lateh execs Declare the following variables in Verilog: = seo 7029 An 8-bit vector net called 4_in. A 32-bit storage register called adavess, Bit 31 must be the most significant bit. Set the value of the register to a 32-bit decimal number equal to 3. An integer called count. A time variable called snap_shot. ‘An array called delays. Array contains 20 elements of the type integer. A memory MEM containing 286 words of 64 bits each. A parameter cache_size equal to 512. hat would be the output/effect of the following statements? latch = 4012; $display(*The current value of latch = %bln", latch). in.reg = 32; $monitor(Stime, "In register value = %bIn’, in_reg[2-0)), ‘define MEM_SIZE 1024 $display("The maximum memory size is %h", MEM_SIZE),34 Chapter 4. Modules and Ports In the previous chapters, we acquired an understanding of the fundamental hierarchical modeling concepts, basic conventions, and Verilog constructs. In this chapter, we take a closer loak at mod- ules and ports from the Verilog language point of view. Learning Objectives + Identify the components of a Verilog module definition, such as module names, port lists, pa- rameters, variable declarations, dataflow statements, behavioral statements, instantiation of other modules, and tasks or functions. + Understand how to define the port list for a module and declare it in Verilog + Describe the port connection rules in a module instantiation + Understand how to connect parts to external signals, by ordered list, and by name. + Explain hierarchical name referencing of Verilog identifiers. Modules We discussed how a module is a basic building block in Chapter 2, Hierarchical Modeling Con- cepts. We ignored the internals of modules and concentrated on how modules are defined and instantiated. In this section, we analyze the internals of the module in greater detail A module in Verilog consists of distinct parts, as shown in Figure 4-1Modules and Ports 32 Module Name, Port List, Port Declarations (if ports present) Parameters (optional), Declarations of wires, Data flow statements regs and other variables (assign) Instantiation of lower always and initial blocks, level modules All behavioral statements go in these blacks Tasks and functions endmodule statement Figure 4-1. Components of a Veriiog Module A module definition always begins with the keyword module. The module name, port list, port dec- Jarations, and optional parameters must come first in a module definition. Part list and port decia- rations are present only if the module has any ports to interact with the external environment.The five components within a module are: variable dectarations, dataflow statements, instantiation of lower modules, behavioral blocks, and tasks or functions. These components can be in any order and at any place in the module definition. The endmodule statement must always come last in a module definition. All components exceptmedule, module name, and endmodule are optional and can be mixed and matched as per design needs. Verilog allows multiple modules to be defined in a single file. The modules can be defined in any order in the file. To understand the components of a module shown above, let us consider a simple example of an SR fatch, as shown in Figure 4-2Modules and Ports 33 eT Sbar (set) RBar Qbar (reset) ro | | | | | | | | | Figure 4-2. SR Latch The SR Jatchhas Sand Ras the input ports and Qand Qbaras the output ports. The SR /atchand its stimulus can be modeled as shown in Example 4-1 Example 4-1. Components of SR Latch / Thie example (1lustrates the different components ef a mi / Module name and port 2ist fateh module (G, @bar, Shar, Roar); late lawer-level modules / In this case, dnetantéate Verilog primitive mand gates Mires are connected in a cross-coupled fashion. + Oba: ry Rbary Ob; edule gtatement imodule / Module name and port List }/ Stimulus madule module Top; / Declarations af wire, veg, and other variables wire q, qbar: reg set, resetr 4 / Feed inverted set and rese! SR. tate lawer-1 modules lates this cage, instantiate rch mi(g, qhar, ~set, ~resetys oral block, initial tor(stime, “ set ~ tb 45 reaet = 45 reaet ~ #5 set a;Modules and Ports 34 end f andmodule state endmodu Notice the following characteristics about the modules defined above: + Inthe SR /atch definition above , notice that all components described in Figure 4-1 need not be present in a module. We do not find variable declarations, dataflow (assign) statements, or behavioral blocks (always of initial). + However, the stimulus block for the SR latch contains module name, wire, reg, and variable declarations, instantiation of lower level madules, behavioral block (initial), and endmod- ule statement but does not contain port list, port deciarations, and data flow (assign) state- ments + Thus, all parts except module, module name, and endmodule are optional and can be mixed and matched as per design needs. Ports Ports provide the interface by which a module can communicate with its environment. For example, the input/output pins of an IC chip are its ports. The environment can interact with the module only through its ports. The internals of the module are not visible to the environment. This provides a very powerful flexibility to the designer. The internals of the module can be changed without affecting the environment as long as the interface is not modified. Ports are also referred to as terminals. List of Ports A module definition contains an optional list of ports. If the module does not exchange any signals with the environment, there are no ports in the list. Consider a 4-bit full adder that is instantiated inside a top-level module Top. The diagram for the input/output ports is shown in Figure 4-3 Top a full adder b—P| (4-bit) fulladdt = |— c_out \—= sum c_in ——pm| Figure 4-3. 110 Ports for Top and Full Adder Notice that in the abave figure, the module 7op is a top-level module. The module fulladd4 is in- stantiated below Top. The module fulladd4 takes input on ports a, 6, and c_in and produces an output on ports sum and ¢_out. Thus, module fulladd4 performs an addition for its environment. The module Top is a top-level module in the simulation and does not need to pass signals to or receive signals from the environment. Thus, it does not have a list of ports. The module names and port lists for both module declarations in Verilog are as shown in Example 4-2.Modules and Ports 35 Example 4-2. List of Ports cout, a by et ef ports, tap-Lovel module in Port Declaration All ports in the list of ports must be declared in the module. Ports can be declared as fallows: Verilog Keyword Type of Port input Input port output Output port inout Bidirectional part Each port in the port list is defined as input, output, or inout, based on the direction of the port signal. Thus, for the example of the fulladad in Example 4-2, the port declarations will be as shown in Example 4-3. Example 4-3. Port Declarations module fulladda(oum, © out, ay by Begin port ai output (3:0) a, be eclaratione section shadule inteenals> Note that all port declarations are implicitly declared as wire in Verilog. Thus, if a port is intended to be a wize, itis sufficient to declare it as output, input, or inout, Input or inout ports are normally declared as wires. However, if output ports hold their value, they must be declared as reg. For example, in the definition of DFF, in Example 2-5, we wanted the output gto retain its value until the next clock edge. The port declarations for DFF will look as shown in Example 4-4 Example 4-4. Port Declarations for DEF module OFF (g, d, clk, reset) ourput qi reg / QUEpUE PoE q holds values therefore Lt ared ag reg 4, clk, resete Ports of the type input and inout cannot be declared as reg because reg variables store values and input ports should not store values but simply reflect the changes in the external signals they are connected to Note that the module fulladdd in Example 4-3 can be declared using an ANSI C style syntax to specify the ports of that module. Each declared port provides the complete information about the port. Example 4-5 shows this alternate syntax. This syntax avoids the duplication of naming the ports in both the module definition statement and the module port list definitions. If a portis declared but no data type is specified, then, under specific circumstances, the signal will default to a wire data type.Modules and Ports 36 Example 4-5. ANSI C Style Part Declaration Syntax module fulladdd {output zeg [3 my output vag ¢_outy input [3:0] 8, by //wire by derauit input cin); //wire by dete endaodule Port Connection Rules One can visualize a port as consisting of two units, one unit that is /aternafto the module and another that is exferna/to the module. The internal and external units are connected. There are rules gov- erning port connections when modules are instantiated within other modules. The Verilog simulator complains if any port connection rules are violated. These rules are summarized in Figure 4-4 inout output >] reg or net reg or net net Figure 4-4. Port Connection Rules Inputs Internally, input ports must always be of the type net. Externally, the inputs can be connected toa variable which is a reg or a net. Outputs internally, outputs ports can be of the type reg or nef. Externally, outputs must always be connected to a net. They cannot be connected to a reg. Inouts Internally, inout ports must always be of the type wet. Externally, inout ports must always be con- nected to a net. Width mate! ig It is legal to connect internal and external items of different sizes when making inter-module port connections. However, a warning is typically issued that the widths da net matchModules and Ports 37 Unconnected ports Verilog allows ports to remain unconnected. For example, certain output ports might be simply for debugging, and you might not be interested in connecting them to the external signals. You can let a port remain unconnected by instantiating a module as shown below fulladda £40 (sum, , . By CIM); // Output poxt out ts uneoan Example of illegal port connection To illustrate port connection rules, assume that the module “uv/ade4 in Example 4-3 is instantiated in the stimulus block Top. Example 4-6 shows an illegal port connection Example 4-6. illegal Port Connection module Top; /Daclare connection v. reg [3:0]A,B; netantiate fullad: fulladdd fa0(SUM, COUT, A, By Liegal ¢ tien because output port eum in module fulladas is connected toe register variable SUM in module Top. imodule This problem is rectified if the variable SUMis declared as a net (wire). Connecting Ports to External Signals There are two methods of making connections between signals specified in the module instantiation and the ports in a module definition. These two methods cannot be mixed. These methods are discussed in the following sections. Connecting by ordered list Connecting by ordered list is the most intuitive method for most beginners. The signals to be con- nected must appear in the module instantiation in the same order as the ports in the port list in the madule definition. Once again, consider the module fulladd defined in Example 4-3. To connect signals in module Top by ordered list, the Verilog code is shown in Example 4-7. Notice that the external signals SUM, C_OUT, A, B, and C_IN appear in exactly the same order as the ports sum, €_out, a, b, and c_imin module definition of fulladd4. Exampie 4-7. Connection by Ordered List fodule Top; }/Peclare connection variables Ingtaatiate fulladdd, eall it Signals are connected to ports in o T, hy By x (by position) Tihs fulladdd fa_ordered (SUM,Modules and Ports 38 module internale> endmedule Connecting ports by name For large designs where modules have, say, 50 ports, remembering the order of the ports in the madule definition is impractical and error-prone. Verilog provides the capability to connect external signals to ports by the port names, rather than by position. We could connect the ports by name in Example 4-7 abave by instantiating the module fullado’4, as follows. Note that you can specify the port connections in any order as long as the port name in the module definition correctly matches the external signal. fulladdd fa_bynam Note that only those ports that are to be connected to external signals must be specified in port connection by name. Unconnected ports can be dropped. For example, if the port ¢ out were to be kept unconnected, the instantiation of fulladdd would look as follows. The port c_outis simply drop- ped fram the port list pyname and eon SUM), .b(B) ati) Anather advantage of connecting ports by name is that as long as the port name is not changed, the order of parts in the port list of a module can be rearranged without changing the port connections in module instantiations. Hierarchical Names We described earlier how Verilog supports a hierarchical design methodology. Every module in- stance, signal, or variable is defined with an identifier. A particular identifier has a unique place in the design hierarchy. Hierarchical name referencing allows us to denote every identifier in the design hierarchy with a unique name. A hierarchical names a list of identifiers separated by dots (".") for each level of hierarchy. Thus, any identifier can be addressed trom any place in the design by simply specifying the complete hierarchical name of that identifier. The top-level module is called the roof module because it is not instantiated anywhere. It is the starting point. To assign a unique name to an identifier, start from the top-level module and trace the path along the design hierarchy to the desired identifier. To clarify this process, let us consider the simulation of SR latch in Example 4-1. The design hierarchy is shown in Figure 4-5.Modules and Ports 39 stimu (root level) ml (SR_lateh) qe qbar set, reset (variables) Q, Qbar sR (signals) Figure 4-5. Design hierarchy for SR Latch Simulation al (nand) a2 (nand For this simulation, stimulus is the top-level module. Since the top-level module is not instantiated anywhere, it is called the roof module. The identifiers defined in this module are q, qbar, set, and reset. The root module instantiates m7, which is a module of type SR_fateh. The module m7 in- stantiates nand gates af and #2. Q, Qbar, S, and R are port signals in instance m1. Hierarchical name referencing assigns a unique name to each identifier. To assign hierarchical names, use the module name for root module and instance names for all module instances below the root module. Example 4-8 shows hierarchical names for all identifiers in the above simulation. Notice that there is a dot (.) for each level of hierarchy from the roofmodule to the desired identifier. Examplo 4-8. Hierarchical Names slua stimulus .qbar stimulus. reset atimalus.mt.g Each identifier in the design is uniquely specified by its hierarchical path name. To display the level of hierarchy, use the special character %rm in the $di splay task. See Table 3-4, String Format Specifications, for details. Summary In this chapter, we discussed the following aspects of Verilog + Module definitions contain various components. Keywords medule and endmoedule are man- datory. Other components—portilst, port declarations, variableand signal declarations, dataflow statements, behavioral blocks, lower-level module instantiations, and tasks or functions—are ‘optional and can be added as needed + Ports provide the module with a means to communicate with other modules or its environment. A module can have a port list. Ports in the port list must be declared as input, output, or inout. When instantiating a module, port connection rules are enforced by the Verilog simula- tor. An ANSI C style embeds the port declarations in the module definition statement. + Ports can be connected by name or by ordered list. + Each identifier in the design has a unique hierarchical name. Hierarchical names allow us to address any identifier in the design from any other level of hierarchy in the designModules and Ports 40 Exercises 4; What are the basic components of a module? Which components are mandatory? 2; Does a module that does not interact with its environment have any I/O ports? Does it have a port list in the module definition? 3: A 4-bit parallel shift register has I/O pins as shown in the figure below. Write the module definition for this module shift_reg. Include the list of ports and port declarations. You do not need to show the intemals. reg_in —— | [3:0] | reg_out i [3:0] 4: Declare a top-level module stimulus. Define REG_IN (4 bit) and CLK (1 bit) as reg register variables and REG_OQUT(4 bit) as wire. Instantiate the module shift_regand call it sr7. Connect the ports by ordered list. 8: Connect the ports in Step 4 by name. 6; Write the hierarchical names for variables REG_IN, CLK, and REG_OUT. 7: Write the hierarchical name for the instance sr7. Write the hierarchical names for its ports clack and reg_in44 Chapter 5. Gate-Level Modeling In the earlier chapters, we laid the foundations of Verilog design by discussing design methodolo- gies, basic conventions and constructs, modules and port interfaces. In this chapter, we get into modeling actual hardware circuits in Verilog. We discussed the four levels of abstraction used to describe hardware. In this chapter, we discuss a design at a low level of abstraction—gate level. Most digital design is now done at gate level or higher levels of abstraction. At gate level, the circuit is described in terms of gates (e.g., and, nand). Hardware design at this level is intuitive for a user with a basic knowledge of digital logic design because it is possible to see a one-to-one correspondence between the logic circuit diagram and the Verilog description. Hence, in this book, we chose to start with gate-level modeling and move to higher levels of abstraction in the succeeding chapters. Actually, the lowest level of abstraction is swifch-(transistor-} level modeling. However, with designs getting very complex, very few hardware designers work at switch level. Therefore, we will defer switch-level modeling to Chapter 11, Swifch-Level Modeling, in Part 2 of this book. Learning Objectives: + Identify logic gate primitives provided in Verilog + Understand instantiation of gates, gate symbols, and truth tables for ana/orand buf/nottype gates + Understand how to construct a Verilog description from the logic diagram of the circuit. + Describe rise, fall, and turn-off delays in the gate-level design. + Explain min, max, and typ delays in the gate-level design. Gate Types A logic circuit can be designed by use of lagic gates. Verilog supports basic logic gates as predefined primitives. These primitives are instantiated like modules except that they are predefined in Verilog and do not need a module definition. All logic circuits can be designed by using basic gates. There are two classes of basic gates: and/or gates and Sufinot gates. And/Or Gates And/or gates have one scalar output and mutig/e scalar inputs. The first terminal in the list of gate terminals is an qutputand the other terminals are inputs. The output of a gate is evaluated as soon as one of the inputs changes. The andr gates available in Verilog are shown below. The corresponding logic symbols for these gates are shown in Figure 5-1. We consider gates with two inputs. The output terminal is denoted by out. input terminals are denoted by /f and i2.Gate-Level Modeling 42 — : — : iz—4 a ie— = and and if : if : i2 out i2 Ou! or nor i1 i i1 : i2 os i2 oe xor xnor Figure §-1. Basie Gates These gates are instantiated to build logic circuits in Verilog. Examples of gate instantiations are shown below. In Example 5-1, for all instances, OUT is connected to the output out, and /N/ and IN2 are connected to the two inputs /7 and /2 of the gate primitives. Note that the instance name does not need to be specified for primitives. This lets the designer instantiate hundreds of gates without giving them a name More than two inputs can be specified in a gate instantiation. Gates with more than two inputs are instantiated by simply adding more input ports in the gate instantiation (see Example 5-1). Verilog automatically instantiates the appropriate gate. Example 5-1. Gate instantiation of And/Or Gates IT, INL, TN21 / baste gate insta and a INI, NZ) hand nai (OUT, INL, IN2)< or or1 (OUT, TMi, 7 nor nari (QUT, INL, IN2)< or xL(QUT, INI, xnar mx (OUT, INI 2); m2): 2 input Nz, INGD; and (GUT, INI, IN2); // legal gate The truth tables for these gates define how outputs for the gates are computed from the inputs. Truth tables are defined assuming two inputs. The truth tables for these gates are shown in Table 5-1. Gutputs of gates with more than two inputs are computed by applying the truth table iteratively.Gate-Level Modeling 43 il il and|g ) x 2 mand gg | xz o/o 9 0 06 aja 14 lox x 2 11° 2 ti}) Oo x x x{O x x x x|/lo ox x z|o x x x z/1 ox x x ill ox |g 1 x 2 nor |g | x 2 0 Ix x oft x toot 0 2 ty iz 1)? x][x ol ox x x|x 0 x zlx to x x zlx 0 x x il il xor tox mor] g | x # 0 1x O}1 @ « x , 0 x a! a rjo te x x x ox 8 x] xox x x & XxX x zlx x x x Figure 5-1. Truth Tables fer And/Or Gates Buf/Not Gates Bufinot gates have one scalar input and one or more scalar outputs. The last terminal in the port list is connected to the input. Other terminals are connected to the outputs. We will discuss gates that have one input and one output. Two basic buf/not gate primitives are provided in Verilog, but nat The symbols for these logic gates are shown in Figure 5-2 in out in out buf not Figure $-2. Buf and Not Gates These gates are instantiated in Verilog as shown Example 5-2. Notice that these gates can have multiple outputs but exactly one input, which is the last terminal in the port list.Gate-Level Modeling 44 Example §-2. Gate instantiations of ButNot Gates }/ basic gate instantiations. buf b1(OUTL, IN)? ot ni (OUTL, IN); Moxe than two outpute buf bi_2out (OUT1, OUT2, IN)s Legal / gate instal out ingtance name not (OUT2, IN); gate instantia The truth tables for these gates are very simple. Truth tables for gates with one input and one output are shown in Table 5-2. buf | in out not | in out 1 I 0 x x x % % Figure §-2. Truth Tables for BubNat Gates Bufifinotif Gates with an additional control signal on buf and not gates are also available. noviea noice These gates propagate only if their control signal is asserted. They propagate if their contro! signal is deasserted. Symbols for bufif/notifare shown in Figure 5-3. in out in r O out ctrl ctrl bufifl notifl in out in out etrl eer bufifo notif) Figure 5-3. Gates Bufif and Noll The truth tables for these gates are shown in Table 5-3.Gate-Level Modeling 45 bufifl}o 1 ox 2 Figure 5-3. Truth Tables for Buff Nolif Gates These gates are used when a signal is to be driven only when the control signal is asserted. Such a situation is applicable when multiple drivers drive the signal. These drivers are designed to drive the signal on mutually exclusive control signals, Example 5-3 shows examples of instantiation of bufif and notif gates. Example 5-3. Gate instantiations of BufitNatit Gates //Instantiatien af burif gates. bufier b1 (out, Lay ctely; bufied bo (out, in, ctrl /Tngtantiatien af actif gates OLSE1 ni (out, in, ctrl} AOLSED nO [out, in, ctrl); Array of Instances There are many situations when repetitive instances are required. These instances differ from each other only by the index of the vector to which they are connected. To simplify specification of such instances, Verilog HDL allows an array of primitive instances to be defined.’ Example 5-4 shows an example of an array of instances Example §-4. Simple Away of Primitive Instances OUT, Iwi, IN2s f bagic gate instantiations nand #_gate(7:0] (OUT, INI, IN2); ia is equivaieat to the following @ Lastantiati: gated (cUT[O}, INL{O}, IN2[0]}; vgatel(OUT(Z}, INL(1}, IN2(1]); gate2 (QUT(2], INL(2], gate3(cuT(3), INL{3], IN2 ‘Refer to the IEEE Standare Vamiog Hardware Deserption Language document for detaliad iMrmation on the ute of an array af instances.Gate-Level Modeling 46 714), gates (GUT[S], 7 gateé(cun[6], 1 et (QuT(7], IML Examples Having understood the various types of gates available in Verilog, we will discuss a real example that illustrates design of gate-level digital circuits. Gate-level multiplexer We will design a 4-f-1 multiplexerwith 2 select signals. Multiplexers serve a useful purpose in logic design. They can connect two or more sources to a single destination. They can also be used to implement boolean functions. We will assume for this example that signals s7 and sO do not get the value x or z. The I/O diagram and the truth table for the multiplexer are shown in Figure 5-4. The lv Q diagram will be useful in setting up the port list for the multiplexer. i0 —| i sl sO out il —s| 4to-l | out 0 0 10 2 —e! Mux Fi 0 1 I 33> — 1 0 12 4 } 1 1 13 sl 80 Figure 6-4. 4-lo-1 Multiplexer We will implement the logic for the multiplexer using basic logic gates. The logic diagram for the multiplexer is shown in Figure 5-5.Gate-Level Modeling 47 eee ee Figure 5-5. Logic Diagram for Muitiplexer out The logic diagram has a one-to-one correspondence with the Verilog description. The Verilog de- seription for the multiplexer is shown in Example 5-5. Two intermediate nets, sOn and sin, are create, hey are complements of input signals s7 and sd. Internal nets yO, y1, y2, y3 are also required, Note that instance names are not specified for primitive gates, not, and, and ox. Instance names are optional for Verilog primitives but are mandatory for instances of user-defined modules. Example 5-5. Verilog Description of Multiptexer f Module G=te-1 multiplexer fy the 1/0 diagras module muxé te 1 (our, 10, 41, Port declarations from the 40, i1, 42, 435 si, 80; }/ Internal wire declarations Wize ein, 20a; wire yO, yls y2) y37 / Geeta ala and son signals not (sing #1) not (s0n, 39); wi, 41, and (y2, 12, 31, and (v3, 13, 21, / s-input oF gate ine er (out, yO, yl, y2, y- pdule Fort list ig taken 42, £3, 91, 1/9 diagram 20): exactly fromGate-Level Modeling 48 This multiplexer can be tested with the stimulus shown in Example 5-6. The stimulus checks that each combination of select signals connects the appropriate input to the output. The signal OU/7- PUTis displayed one time unit after it changes. System task §moni tor could also be used to display the signals when they change values Example 5-6. Stimulus for Multiplexer }/ Define the etimulue module (ne portsh nodule stimulus; }/ Declare variables te be cone! y to inpuee reg ING, IN1, INz, 1N3; zeq $1, 80; }/ Declare output wire wize ouTPU / Inatantéare the multiplexer muxd_to_1 mymux(QUTPUT, INO, INI, IN2, IN3, St, S0)+ f Stimulate the Snpute f Define the stimulus module {no ports} et input lines - 1; IN2 ~ 0; IN2- 1; TN2 - #1 Sdigplay ("IMO 8b, INL= th, INI" eb, IN3e wa", IMO, IMI, IN2,WI)s f choose TNO Si = 0; 50 = ai Sdisplay ("Sl - $b, S¢- th, OUTPUT - tb \n", $1, $0, OUTPUT}: / choose 1M SL so- 4; * aay("SL = tb, SO = th, OUTPUT = @b Yn", SL, SO, OUTPUT): f encase 1N2 Sls 1; 50 = 0; #2 Sdiapiay ("SL - 80 - 4B, OUTPUT - a \AY, SL, $0, OUTPUT); Uf choose 1N3 Sl = 1; 80-1; 4 fay ("SL = 8b, 80 = %b, OUTPUT = #b \n", SL, $0, OUTPUT): endmodule The output of the simulation is shown below. Each combination of the select signals is tested. IND- 1, INI- 0, TN2- 2, $1 - 0, 50 ~ 0, oUTPUT - 1 sls uTPUT = o sl=1, 50- UTPUT = 1 - 2, QUTPUT 4-bit Ripple Carry Full Adder In this example, we design a 4-bit full adder whose port list was defined in Section 4.2.1, List of Ports. We use primitive logic gates, and we apply stimulus to the 4-bit full adder to check function ality . Far the sake of simplicity, we will implement a ripple carry adder. The basic building block is a 1-bit full adder. The mathematical equations for a 1-bit full adder are shown below. sum =(a@ b@ cin)Gate-Level Modeling 43 cout= (#b) + cinia & b) The logic diagram for a 1-bit full adder is shown in Figure 5-6 sum c_out Figure 5-6. 1-bit Full Adder This logic diagram for the 1-bit full adder is converted to a Verilog description, shawn in Example 5-7. Example 5-7. Verilog Deseripiion for 1-bit Full Adder / Define @ 1-bLt nodule fulladd (sum, ¢_ow 11 ad vor (gum, 91, © iniy and (¢2, #1, cin} wor (cout, 02, el): endasdule A 4-bit ripple carry full adder can be constructed from four 1-bit full adders, as shown in Figure 5-7. Notice that fa0, fa1, fa2, and fa3 are instances of the module fulladd (1-bit full adder) a[0] b{0} afty BU a2] b[2] a[3] >(3) a | | | full | cy full | ¢2 full | 65 fall | | cout cine) adder |e adder | ——Be}_adder |e adder |} ]7— be | fa fal fa2 fa3 eee J ES | = Ls y sum[0] sum{1] sum[2] sum[3] Figure 8-7. 4-bit Ripple Cary Full AdderGate-Level Modeling 50 This structure can be translated to Verilog as shown in Example 5-8. Note that the port names used ina 1-bit full adder and a 4-bit full adder are the same but they represent different elements. The element sunrin a 1-bit adder is a scalar quantity and the element sum in the 4-bit full adder is a 4- bit vector quantity. Verilog keeps names local to a module. Names are not visible outside the module unless hierarchical name referencing is used. Also note that instance names must be specified when defined modules are instantiated, but when instantiating Verilog primitives, the instance names are optional. Example 5-8. Verilog Description or 4-btt Ripple Carty Full Adder / Dating & 4-bit £u21 adder module fulladdd (eum, e_aut, / Ingtantiate four fulladd fa0(sum(D}, cl, al fulladd fal(eum(1}, 62, [1], B(1], fulladd taz(sum[2}, c3, af21, bl21, c2) Fulladd fa3(sum(3], cout, 3/3], b[3}e ©: endmodule Finally, the design must be checked by applying stimulus, as shown in Example 5-9. The module stimulus stimulates the 4-bit full adder by applying a few input combinations and monitors the results. Example 5-9. Stimutus for 4-bit Riopte Carry Fult Adder / Define the stisulue (tep level module module stimulus; f/ Set up variables eq 13:0] Ae / Inst the 4-bit full adde: LL ke PR: culladda R, By CIN): / Set up the monitoring fer the eignal values begin Smonitor(stime," A= tb, Cau ab, SuM= $b\n7 Hh) end / Stimulate inpute begin Aa IN = Ltho? 45Gate-Level Modeling 54 asa end Im = 1'L: endmodule The output of the simulation is shawn below. , B-g000, ¢_IN- UT- a, SUM- 9000 OUT d, sum 0121 po11, B-a100, C_IN- 4, --- he 0010, B=0101, Gate Delays Until now, we described circuits without any delays (i.¢., zero delay). In real circuits, logic gates have delays associated with them. Gate delays allow the Verilog user to specify delays through the logic circuits. Pin-to-pin delays can also be specified in Verilog. They are discussed in Chapter 10, Timing and Delays. Rise, Fall, and Turn-off Delays. There are three types of delays from the inputs to the output of a primitive gate. Rise delay The rise delay is associated with a gate output transition ta a 1 from another value. 1 0, xorg trise Fall delay The fall delay is assaciated with a gate output transition to a 0 from another value. 1, xorz 0 t_fallGate-Level Modeling 52 Turn-off delay The turn-off delay is associated with a gate output transition to the high impedance value (z) from another value Ifthe value changes to x, the minimum of the three delays is considered. Three types of delay specifications are allowed. If only one delay is specified, this value is used for all transitions, If fwo delays are specified, they refer to the rise and fall delay values. The turn-off delay is the minimum of the two delays. If all three delays are specified, they refer to rise, fall, and turn-off delay values. If no delays are specified, the default value is zero, Examples of delay spec- ification are shown in Example 5-10 Example 5-10. Types of Delay Specification all transitions HY Delay of a and (delay ¢ ) and Tues-of , fail_val, Examples of delay specification are shown below. 6) a2 (0 #(3,4,5) tur Min/Typ/Max Values. Verilog provides an additional level of control tor each type of delay mentioned above. For each type of delay—rise, fall, and turn-off—three values, mun, typ, and max, can be specified. Any one value can be chosen at the start of the simulation. Min/typ/max values are used to model devices whose delays vary within a minimum and maximum range because of the IC fabrication process variations. Min value The min value is the minimum delay value that the designer expects the gate to have Typ val The typ value is the typical delay value that the designer expects the gate to have. Max value The max value is the maximum delay value that the designer expects the gate to have. Min, typ, or max values can be chosen at Verilog run time. Method of choosing a min/typ/max value may vary for different simulators or operating systems. (For Verilog-XL™, the values are chosen by specifying options +maxdelays, +typdelays, and +mindelays at run time. If no option is speci- fied, the typical delay value is the default). This allows the designers the flexibility of building three delay values for each transition into their design. The designer can experiment with delay values without modifying the design. Examples af min, typ, and max value specification for Verilog-XL are shown in Example 5-11.Gate-Level Modeling 53 Example §-11. Min, Max, and Typical Delay Values H/ One delay yf Af smindelaye, f Le +typdelay: (1 $6 saxdelays, delay~ € 5:6) al(aut, 41, 12) / tae delays / if ¢mindelays, rises 3, fall= 5, tur = min(3,5) 7 Af +typdelays, rises 4, fall 6, tur = min(4,6) f Le smaxdelays, rleem 5 1 tue = min(s,7) and ¥(3:4:5, 526:7) adiout, 41, 12) / Three delays eae delays, rise~ / Le +typdelaye, rises fy AC +maxdelays, rises a, 4:4:5, apd ¥(223 Examples of invoking the Verilog-XL simulator with the command-line options are shown below. Assume that the module with delays is declared in the file fest. v. Avake einula with maximum delay > warileg test.v smaxdelaye /Anvoke simulation with windnua delay > varileg test.v smindelays /Anveke simulation with typieal delay > verdiog .v +typdelays Delay Example Let us consider a simple example to illustrate the use of gate delays to model timing in the logic circuits. A simple module called Dimplements the following logic equations: out= (ab) +e The gate-level implementation is shown in Madue D (Figure 5-8). The module contains two gates with delays of 5 and 4 time units. D a a i ra | i * TT] # Se | | out c | | | oo ee ees Figure 5-8. Module D The module Dis defined in Verilog as shown in Example 5-12. Example 5-12. Verilog Definition for Module D with Delay / Deting 4 sinple combination acdule called D module D {out, a, by dF / 1/0 port declarationsGate-Level Modeling arby ce te primitive gates to build tne #15} alle, a, b)7 //Delay of § on gate al or ¥(4) ot(out, ey Delay of 4 on gate oL endmodule This module is tested by the stimulus file shown in Example 5-13. Example 5-13. Stimulus for Module D with Delay / Stimulus (top-level module) module stimulus; rea A, By wise OUT: / Tnatantiare the moc Ddit our, A, B, /f Stimulate the capue nigh the simulation at 40 time units begin A= 1'bO; Be 1'nOz Ce LtBOF 4 Lely Be 1'B1; Ce LBL; #10 Ae Ptbi; Be 1'bO; CH 1'bO; 420 Seinieh end endmodule 54 The waveforms from the simulation are shown in Figure 5-9 to illustrate the effect of specifying delays on gates. The waveforms are not drawn to scale. However, simulation time at each transition is specified below the transition. 4. The outputs Eand OUT are initially unknown, 2. Attime 10, after A, 8, and Call transition to 1, OUT transitions to 1 after a delay of 4 time units and E changes value to 1 after 5 time units. 3. Attime 20, Band Ctransition to 0. Echanges value to 0 after 5 time units, and OU transitions to 0, 4 time units after E changesGate-Level Modeling 55 ' 1 T 1 A Lt | I | A rt | I tt | I | c rt I | It i 1 I E _Xxx | | 4 l | QUT_XXXXXAX] bf) | 7 1 a 1 ' ' TimeQ 5 910 1415 20 28 29 Figure 5.9. Waveforms for Delay Simulation tis a useful exercise to understand how the timing for each transition in the above waveform cor- responds to the gate delays shown in Modute D. Summary In this chapter, we discussed how to model gate-level logic in Verilog. We also discussed different aspects of gate-level design + The basic types of gates are and, or, xor, buf, and not. Each gate has a logic symbol, truth table, and a corresponding Verilog primitive. Primitives are instantiated like modules except that they are predefined in Verilog. The output of a gate is evaluated as soon as one of its inputs changes. + Arrays of built-in primitive instances and user-defined modules can be defined in Verilog. + For gate-level design, start with the logic diagram, write the Verilog description for the lagic by using gate primitives, provide stimulus, and look at the output. Two design examples, a 4-to-1 multiplexer and a 4-bit full adder, were discussed. Each step of the design process was ex- plained. + Three types of delays are associated with gates: sise, fall, and furn-off Verilog allows specifi- cation of one, two, or three delays for each gate. Values of rise, fall, and turn-off delays are computed by Verilog, based on the one, fwo, or three delays specified. + For each type of delay, a minimum, typical, and maximum value can be specified. The user can choose which value to apply at simulation time. This provides the flexibility to experiment with three delay values without changing the Verilog code. + The effect of propagation delay on waveforms was explained by the simple, two-gate logic ex- ample. For each gate with a delay of ¢ the output changes ftime units after any of the inputs change. Exercises 1; Create your own 2-input Verilog gates called my-or, my-andand my-notfrom 2-input nand gates. Check the functionality of these gates with a stimulus module. 2: A2-inputxor gate can be built from my_and, my_orand my_notgates. Construct an xox module in Verilog that realizes the logic function, z = xy’ + xy. Inputs are x and y, and zis the output. Write a stimulus module that exercises all four combinations of xand y inputs. 38: The 41-bit full adder described in the chapter can be expressed in a sum of products form.Gate-Level Modeling 56 sum = a.b.c_in + a'b.cin'+ a cout=a.b+bc_intacin Assuming @, 6, c_inare the inputs and sum and c_outare the outputs, design a logic circuit to implement the 1-bit full adder, using only and, not, and or gates. Write the Verilog description for the circuit. You may use up to 4-input Verilog primitive and and or gates. Write the stimulus for the full adder and check the functionality for all input combinations 4: The logic diagram for an AS /aich with delay is shown below. reset bar set 2 (reset) Write the Verilog description for the RS latch. Include delays of 1 unit when instantiating the nor gates. Write the stimulus module for the RS latch, using the following table, and verify the outputs set reset | Gye) 5; Design a 2-to-1 multiplexer using bufif0 and bufifl gates as shown below.Gate-Level Modeling inl out Apply stimulus and test the output values 5758 Chapter 6. Dataflow Modeling For small circuits, the gate-level modeling approach works very well because the number of gates is limited and the designer can instantiate and connect every gate individually. Also, gate-level modeling is very intuitive to a designer with a basic knowledge of digital logic design. However, in complex designs the number of gates is very large. Thus, designers can design more effectively if they concentrate on implementing the function at a level of abstraction higher than gate level. Da- taflow modeling provides a powerful way to implement a design. Verilog allows a circuit to be de- signed in terms of the data flow between registers and how a design processes data rather than instantiation of individual gates. Later in this chapter, the benefits of dataflow modeling will become more apparent. With gate densities on chips increasing rapidly, dataflow modeling has assumed great importance. No longer can companies devote engineering resources to handcrafting entire designs with gates. Currently, automated tools are used to create a gate-level circuit from a dataflow design description. This process is called /ogic synthesis. Dataflow modeling has become a popular design approach as logic synthesis tools have become sophisticated. This approach allows the designer to concen- trate on optimizing the circuit in terms of data flow. For maximum flexibility in the design process, designers typically use a Verilog description style that combines the concepts of gate-level, data flow, and behavioral design. In the digital design community, the term RTL (Register Transfer Level) design is commonly used for a combination of dataflow modeling and behavioral modeling, Leaming Objectives: + Describe the continuous assignment (assign) statement, restrictions on the assign state- ment, and the implicit continuous assignment statement. + Explain assignment delay, implicit assignment delay, and net declaration delay for continuous assignment statements. + Define expressions, operators, and operands. + List operator types for all possible operations—arithmetic, lagical, relational, equali reduction, shift, concatenation, and conditional + Use dataflow constructs to model practical digital circuits in Verilog y, bitwise, Continuous Assignments A continuous assignment is the most basic statement in dataflow modeling, used to drive a value onto a net. This assignment replaces gates in the description of the circuit and describes the circuit at a higher level of abstraction. The assignment statement starts with the keyword assign. The syntax of an assign statement is as follows. cont mu iim assign [ de list of teength } [ detay3 | gn :Dataflow Modeling 59 Notice that drive strength is optional and can be specified in terms of strength levels discussed in Section 3.2.1, Value Set. We will not discuss drive strength specification in this chapter. The default value for drive strength is strongl and strong0. The delay value is also optional and can be used to specify delay on the assign statement. This is like specifying delays for gates. Delay specification is discussed in this chapter. Continuous assignments have the following characteris- ties: 41. The left hand side of an assignment must always be a scalar or vectar net or a concatenation of scalar and vector nets. It cannot be a scalar or vector register. Concatenations are discussed in Section 6.4.8, Concatenation Operator. 2. Continuous assignments are always active. The assignment expression is evaluated as soon as one of the right-hand-side operands changes and the value is assigned to the left-hand- side net. 3. The operands on the right-hand side can be registers or nets or function calls. Registers or nets can be scalars or vectors 4. Delay values can be specified for assignments in terms of time units. Delay values are used to control the time when a net is assigned the evaluated value. This feature is similar to spec- ifying delays for gates. It is very useful in modeling timing behavior in real circuits. Examples of continuous assignments are shown below. Operators such as & “, |, {,} and + used in the examples are explained in Section 6.4, Operator Types. At this point, concentrate on how the assign statements are specified Example 6-1. Examples of Continuous Assigament ie anet. £1 and iZ are nets inuous aseig assign out ~ il & i2r us ageign for vector nete. addr ie a Lé-bit vector net ° addr? _bite[1s:o); f 01 atenation of a scalar ign We now discuss a shorthand method of placing a continuous assignment on a net. Implicit Continuous Assignment Instead of declaring a net and then writing a continuous assignment on the net, Verilog provides a shortcut by which a continuous assignment can be placed on a net when it is declared. There can be only one implicit declaration assignment per net because a net is declared only once. In the example below, an impli assignment. continuous assignment is contrasted with a regular continuous ontinuous Assignment Regular ign out ~ Lal @ ind; sSame effect nieved by an t continuaue ageignmen Implicit Net Declaration Ifa signal name is used to the left of the continuous assignment, an implicit net declaration will be inferred far that signal name. If the net is connected to a module port, the width of the inferred net is equal to the width of the module port.Dataflow Modeling 60 42; /fmote that out ¥ ffout an implicit wire declaration far out 4a dene by th ator Delays Delay values control the time between the change in a right-hand-side operand and when the new value is assigned to the left-hand side. Three ways of specifying delays in continuous assignment statements are regular assignment delay, implicit continuous assignment delay, and net declaration delay. Regular Assignment Delay The first method is to assign a delay value in a continuous assignment statement. The delay value is specified after the keyword assign. Any change in values of infor in2will result in a delay of 10 time units before recomputation of the expression in7 & in2, and the result will be assigned to out If ind or in2 changes value again before 10 time units when the result propagates to out the values of in7 and inZat the time of recompultation are considered. This property is called /nertia/ delay. An input pulse that is shorter than the delay of the assignment statement does not propagate to the output. y dn a continuous assign The waveform in Figure 6-1 is generated by simulating the above assign statement. It shows the delay on signal out. Note the following change: When signals in/ and in2 go high at time 20, out goes to a high 10 time units later (time = 30). When jn? goes low at 60, ouf changes to low at 70. However, inf changes to high at 80, but it goes down to low before 10 time units have elapsed. Hence, at the time of recomputation, 10 units after time 80, Jn7 is 0. Thus, out gets the value 0. A pulse of width less than the specified assignment delay is not propagated to the output. Pensa | | I | it OUt Goocex | | | I D \ time 10 20 30 60 70 8085 Figure 8-1. Delays Inertial delays also apply to gate delays, discussed in Chapter 5, Gate-Level Modeling. Implicit Continuous Assignment Delay ‘An equivalent method is to use an implicit continuous assignment to specify both a delay and an assignment on the net.Dataflow Modeling 64 ageign #1 The declaration above has the same effect as defining a wire outand declaring a continuous as- signment on out. Net Declaration Delay A delay can be specified on a net when it is declared without putting a continuous assignment on the net. Ifa delay is specified on a net ous, then any value change applied to the net outis delayed accordingly. Net declaration delays can also be used in gate-level modeling Ant @ ind; /The above statement has the same effect as the following assign #10 out = inl 6 ind; Having discussed continuous assignments and delays, let us take a closer look at expressions, operators, and operands that are used inside continuous assignments. Expressions, Operators, and Operands Dataflow modeling describes the design in terms of expressions instead of primitive gates. Expres- sions, operators, and operands torm the basis of dataflow modeling, Expressions Expressions are constructs that combine operators and operands to produce a result. f Examples of expressions o2 aperande and operators arb add. 1 inl | adder (2 Operands Operands can be any one of the data types defined in Section 3.2, Data Types. Some constructs will take only certain types of operands. Operands can be constants, integers, real numbers, nets, registers, times, bit-sefect (one bit of vector net or a vector register), part-select (selected bits of the vector net or register vector), and memories or function calls (functions are discussed later) integer count, f1nal_count; final_count ~ count > count is an integer operand >a; //a and b are real operands reg [15:0] real, reg2: reg ) re reg out = res 0 reg2{3:0) are elect register operandsDataflow Modeling 62 zet_value - calculate parity (A, B);//ealeulal eanetion Operators Operators act on the operands to produce desired results. Verilog provides various types of oper- ators. Operator types are discussed in detail in Section 6.4, Operator Types. #1 us 42 // £4 i an eperator on operands 41 and 42 ta] // ! 4s an operator on operand a A Operator on operands B and 1 Operator Types Verilog provides many different operator types. Operators can be arithmetic, logical, relational, equality, bitwise, reduction, shift, concatenation, or conditional Some of these operators are similar to the operators used in the C programming language. Each operator type is denoted by a symbol. Table 6-1 shows the complete listing of operator symbols classified by category. Table 6-t. Operator Types and Symbols Operator Type Operator Symbol Operation Performed — Number of Oper Arithmetic * multiply two ys divide wo + add two S) subtract, two & modulus two ” power (exponent) bwo Logica ' logical negation one ae logical and two " logical or two Relational > greater than two < less than bwo >= greater than or equal wo <= less than er equal two Equality = equality two '= inequality two _ case equality two I= case incquality two Bitwise ~ bitwise negation one * bitwise and nwo ' bitwise or two io bitwise xor two Paor ~° bitwise xnor two Reduction 4 reduction and one ~& reduction nand one ' reduction oF one +l reduction nor oneDataflow Modeling 63 Operator Type Operator Symbol Operation Performed Number of Operands aeor reduction xor one reduction xnor one Shift >> Right shift Two << Left shift Two o> Arithmetic right shift Twa <6 Arithmetic left shift Two Concatenation {> Coneatenation Any number Replication coho Replication Any number Conditional 2 Conditional Three Let us now discuss each operator type in detail Arithmetic Operators There are two types of arithmetic operators: binary and unary. Binary operators Binary arithmetic operators are mutiply (* ), divide (/ ), add (+), subtract (-), power (**), and modulus (@). Binary operators take two operands. A= Q*RO011; BM - 4*H0100; // A and B are register vectors a; 2¢/ D and © are integers A* 8 // Multiply A and B. Evaluates be 4'b1100 D/& // Divide D by B. evalu tol ates any fractional part A+B // Add A and B. Evaluates to 4'bO B- A // Subtract A from B. Evaluates to ("bo PoE ** fF; //f to the power F, yields 16 If any operand bit has a value x, then the result of the entire expression is x. This seems intuitive because if an operand value is not known precisely, the result should be an unknown. inl = ¢tp1oay, a+ ind; ‘ will be evaluated to the value (thx Madulus operators produce the remainderfrom the division of two numbers. They operate similarly to the medulus operator in the C programming language. , takes eign of the £ takes sign of the first operand 00 zi operand Unary operators The operators + and - can also work as umary operators. They are used to specify the positive or negative sign of the operand. Unary + or ~ operators have higher precedence than the binary + or - operators. Negative 4Dataflow Modeling 64 Negative numbers are represented as 2's complement internally in Verilog. It is advisable to use negative numbers only of the type integer or real in expressions. Designers should avoid negative numbers of the type
‘
in expressions because they are converted to unsigned 2's complement numbers and hence yield unexpected results. fAdviseble te use integer or real numbers “1b / SAY Bw 0 -2 fDo not use numbers of type
‘cbase>
), less-than (<), greater-than-or-equal-to (>=), and less- than-or-equal-to (<=). If relational operators are used in an expression, the expression retums a logical value of 1 if the expression is true and 0 if the expression is false. If there are any unknown or z bits in the operands, the expression takes a value x. These operators function exactly as the corresponding operators in the G programming language 7X awiO1, Y= @b1EOL, 2 aria lates to @ logical 0 ical 1 legie <2 // Evaluates to an x Evaluates ¢ oe x Af EwDataflow Modeling 65 Equality Operators Equality operators are fogical equality (==), logical inequality case equality (===), and case inequatity (!==). When used in an expression, equality operators return logical value 1 if true, 0 if false. These operators compare the two operands bit by bit, with zero filling if the operands are of unequal length. Table 6-2 lists the operators. Table 6-2. Equality Operators Expression Description Possible Logical Value 2 equal to b, result unknown if or # ina orb oa a not equal to b, result unknown if or inaerb 0, 1,x a equal to b, including » and 2 a1 a not equal to b, including x and 2 a2 Itis important to note the difference between the logical equality operators (==, !=) and case equality operators (= ). The logical equality operators ( will yield an x if either operand has x or z in its bits. However, the case equality operators (===, !== ) compare both operands bit by bit and compare all bits, including x and z. The result is 1 if the operands match exactly, including x and z bits. The result is 0 if the operands do not match exactly. Case equality operators never result in an x. b1202 biswe, N~ a! bless (au Bitwise Operators Bitwise operators are negation (~), ana{&), ar(|),xor(*), xner(*~, ~*). Bitwise operators perform a bit-by-bit operation on two operands. They take each bit in one operand and perform the operation with the corresponding bit in the other operand. If one operand is shorter than the other, it will be bit-extended with zeros to match the length of the longer operand. Logic tables for the bit-by-bit computation are shown in Table 6-3. A z is treated as an x in a bitwise operation. The exception is the unary negation operator (~), which takes only one operand and operates on the bits of the single operandDataflow Modeling 66 bitwise and 1 x bitwise or 0 1 x bitwise negation Figure 6-3. Truth Tables for Bitwise Operators Examples of bitwise operators are shown below fJ X= atpno1o, ¥ = 4*b1101 / 2 = a'p1Ox2 ox / Negation. Result Le 4*po101 XY // Bitwee Ri is 4'b100 XY // Bltwise oe. Result 43 a'nai XY // Bitwise xor. Result ie 4’b0121 Kt Yd) Bitws rs Result te ("bLOde X&2 // Reaul &1b10%0 It is important to guish bitwise operators ~, &, and | from logical operators 1, &&, ||. Logical operators always yield a logical value 0, 1, x, whereas bitwise operators yield a bit-by-bit value. Logical operators perform a logical operation, not a bit-by-bit operation. {X= avpne1d, ¥ = «'p00d0 Reguit 42 ¢'bL010 » Equivalent to 1 || Reault ta 1. Reduction Operators Reduction operatars are and(&), mand (~&), or(1), aar(~|), xor(*), and xnar(~*, *~). Reduction operators take only one operand. Reduction operators perform a bitwise operation on a single vector operand and yield a 1-bit result. The logic tables for the operators are the same as shown in Section 6.4.5, Bitwise Operators. The difference is that bitwise operations are on bits from two different operands, whereas reduction operations are on the bits of the same operand. Reduction operators work bit by bit from right to left. Reduction nand, reduction nor, and reduction xnar are computed by inverting the result of the reduction and, reduction or, and reduction xor, respectively.Dataflow Modeling 67 m2010 4X //Bquivalent te 1 Ix/ equivalent to 1 *¥/ /Equ: yR raduets tor’ odd parity ffgeneration of The use of a similar set of symbols for logical (!, £6, | |), bitwise (~, &, |, *), and reduction operators (6, 1, 4) is somewhat confusing initially. The difference lies in the number of operands each operator takes and also the value of results computed. Shift Operators Shift operators are right shift ( >>), left shift (<<), arithmetic right shift (>>>), and arithmetic /eff shift(<<<). Regular shift operators shift a vector operand to the right or the left by a specified number of bits. The operands are the vector and the number of bits to shift. When the bits are shifted, the vacant bit positions are filled with zeros. Shift operations do not wrap around. Arithmetic shift op- erators use the context of the expression to determine the value with which to fill the vacated bits. 1 bit. 0 filled in 1 bit. © filed in xs ee left 2 pita. #/Signed date types 0 binar 3); //Results in -2 decimal, due te arit Shift operators are useful because they allow the designer to model shift operations, shift-and- add algorithms for multiplication, and other useful operations. Concatenation Operator The concatenation operator ( {, } ) provides a mechanism to append multiple operands. The ap- erands must be sized. Unsized operands are not allowed because the size of each operand must be known for computation of the size of the result. Concatenations are expressed as operands within braces, with commas separating the operands. Operands can be scalar nets or registers, vector nets or registers, bit-select, part-select, or sized constants. ty ds 1a*p1oonei10002 3"b10L Replication Operator Repetitive concatenation of the same number can be expressed by using a replication constant. A replication constant specifies how many times to replicate the number inside the brackets ( { } ). reg A: reg [1:0] By reg [2:0] Dy Aw itil; B= 2!nogy c= ate = a'priorDataflow Modeling 68 Conditional Operator The conditional operator(? :) takes three operands. Usage. condition_expr ? true_expr : false_expr; The condition expression (condition_expr is first evaluated. If the result is true (logical 1), then the true_expris evaluated. If the result is false (logical 0), then the fa/se_expris evaluated. If the result is x (ambiguous), then both érwe_exprand false_exprare evaluated and their results are compared, bit by bit, to return for each bit position an x if the bits are different and the value of the bits if they are the same The action of a conditional operator is similar to a multiplexer. Alternately, it can be compared to the if-else expression false_expr —a»| 0 2-to-1 multiplexer |e out true_expr ——te| | cond_expr Conditional operators are frequently used in dataflow modeling to model conditional assignments. The conditional expression acts as a switching control. unct y of a tristate burte: addr by be; functlonality of a 2 o-1 mux Conditional operations can be nested. Each frue_expr or false_exprcan itself be a conditional op- eration. In the example that follows, convince yourself that (A==3) and control are the two select signals of 4-to-1 multiplexer with 7, m, y, xas the inputs and oufas the output signal. t= (A 3) 7 ( eoneeel 2a: yd Ce Operator Precedence Having discussed the operators, it is now important to discuss operator precedence. If no paren- theses are used to separate parts of expressions, Verilog enforces the following precedence. Op- erators listed in Table 6-4 are in order from highest precedence to lowest precedence. It is recom- mended that parentheses be used to separate expressions except in case of unary operators or when there is no ambiguity.Dataflow Modeling 69 Table 6-4, Operator Precedence Operators Unary -1- Highest precedence Multiply, Divide, Modulus * / & Add, Subtract Shift pears ‘Operator Symbols Precedence Relational Equality Reduction Logical te Conditional ae Lowest precedence Examples A design can be represented in terms of gates, data flow, or a behavioral description. In this section, we consider the 4-to-1 multiplexer and 4-bit full adder described in Section 5.1.4, Examples. Pre- viously, these designs were directly translated from the logic diagram into a gate-level Verilog de- scription, Here, we describe the same designs in terms of data flow. We also discuss two additional examples: a 4-bit full adder using carry lookahead and a 4-bit counter using negative edge-triggered D-fiiprlops. 4-to-1 Multiplexer Gate-level modeling of a 4-to-1 multiplexer is discussed in Section 5.1.4, Examples. The logic diagram for the multiplexer is given in Figure 5-5 and the gate-level Verilog description is shown in Example 5-5. We describe the multiplexer, using dataflow statements. Compare it with the gate- level description. We show two methods to model the multiplexer by using dataflow statements. Method 1: logic equation We can use assignment statements instead of gates to model the logic equations of the multiplexer (see Example 6-2). Notice that everything is same as the gate-level Verilog description except that computation of outis done by specifying one logic equation by using operators instead of individual gate instantiations. /O ports remain the same. This is important so that the interface with the envi- ronment does not change. Only the intemals of the module change. Notice how concise the de- scription is compared to the gate-level description. Example 6-2. 4-to-1 Multiplexer, Using Logie Equations / Module -1 multiplexer using data flow. logic equation 7 Compare model & gate-L module (out, 40, 11, 62, 43, #1, 20) from the 1/0 diagram equationDataflow Modeling 70 (el £20 «12 | {sl & 30-4 13) 5 endmodule Method 2: conditional operator There is a mare concise way to specify the 4-to-1 multiplexers. In Section 6.4.10, Conditional operator, we described how a conditional statement corresponds to 2 multiplexer operation. We will use this operator to write a 4-to-1 multiplexer. Convince yourself that this description (Example 6-3) correctly models a multiplexer. Example 6-3. 4-lo-1 Multiplexer, Using Conditional Operators f Module @=te=1 / Compare to gat pdule wultplexerd eo 1 (out, 40, i1, 42, 43, a1, 201; uleiples level model weing data flew. Conditsenal operator. st declarations from the I/O dia endmedule In the simulation of the multiplexer, the gate-level module in Example 5-5 on page 72 can be sub- stituted with the dataflow multiplexer modules described above. The stimulus module will not change. The simulation results will be identical. By encapsulating functionality inside a module, we can replace the gate-level module with a dataflow module without affecting the other modules in the simulation, This is a very powerful feature of Verilog. 4-bit Full Adder The 4-bit full adder in Section §.1.4, Examples, was designed by using gates; the logic diagram is shown in Figure 5-7 and Figure 5-6. In this section, we write the dataflow description for the 4-bit adder. Compare it with the gate-level description in Figure 5-7. In gates, we had to first describe a 1-bit full adder. Then we built a 4-bit full ripple carry adder. We again illustrate two methods to describe a 4-bit full adder by means of dataflow statements. Method 1: dataflow operators A concise description of the adder (Example 6-4) is defined with the + and ¢ } operators Example 6-4. 4-bit Full Adder, Using Dataflow Operators f Define a a-bit furl a Jataflow statemente module fulladda(sum, cout, endmodule Ifwe substitute the gate-level 4-bit full adder with the dataflow 4-bit full adder, the restof the modules will not change. The simulation results will be identical,Dataflow Modeling 74 Method 2; jull adder with carry lookahead In ripple carry adders, the carry must propagate through the gate levels before the sum is available at the output terminals. An mbit ripple carry adder will have 2n gate levels. The propagation time can be a limiting factor on the speed of the circuit. One of the most popular methods to reduce delay is to use a carry lookahead mechanism. Logic equations for implementing the carry lookahead mechanism can be found in any logic design baok. The propagation delay is reduced to four gate /evels, irrespective of the number of bits in the adder. The Verilog description for a carry lookahead adder is shown in Example 6-5. This module can be substituted in place of the full adder madules described before without changing any other compa- nent of the simulation. The simulation results will be unchanged Example 6-5. 4-bit Full Adder with Cay Lookahead module fulladad(sum, cout, a by ¢_ // Inputs and outputs 15:0) sum; 350) a,b; / Internal wires wire p0/a0, plral, p2ra2, p3,93s Wize e4, €3, 62, 1; / compute the p for each stage agsign po = a(0] > BfO], plata) > bt), p2 ~ a[2] ° BI], p3 = (3) * BIayr onpute the q for each. stage assign gO = a(0] © btOl, gi - afi) é bt), @2 - a[2] # BIZ), g3 ~ (3) @ bEa}e f compute the for ea: f Mote th: equivalent cO in the arithmetic equation for Yearry 1 mputation ageign cl = ga | «cin 2 ~ 490) | tp & pO & cial, a tp? & gi) | (p2 6 pl 4g) | (2 e ple pos ein ca > tp3 6 a2) | (pd § pz @ al) | (p38 p2 & pl s Gb} (p3 & p2 & ple po ee inh; / Compute s ign a cin, 8 carry output = gu} ign ¢ aut imodule Ripple Counter We now discuss an additional example that was not discussed in the gate-level modeling chapter. We design a 4-bit ripple counter by using negative edge-triggered flipflops. This example was dis- cussed at a very abstract level in Chapter 2, Hierarchical Modeling Concepts. We design it using Verilog dataflow statements and test it with a stimulus module. The diagrams for the 4-bit ripple carry counter modules are shown below. Figure 6-2 shows the counter being built with four T-flipflops.Dataflow Modeling 72 0 ql q2 B Po pS ie => S44 I \ I qa q q q | clock —-O> T_FF| T_FF T_FF| TF | I ufo tffl tf tff3 I I | I | clear—t | Pee 4 Figure 6-2. 4-bit Ripple Carty Counter Figure 6-3 shows that the 7-fijprlap is built with one Q-flipflap and an inverter gate. TFF q rocco a | reset Figure 6-3. T-fiphop Finally, Figure 6-4 shows the D-flipflap constructed from basic logic gatesDataflow Modeling 73 clear q clk qbar d Figure 6-4. Negative Edge-Tniggered D-fipflop with Clear Given the above diagrams, we write the corresponding Verilog, using dataflow statements in a top- down fashion. First we design the module counter. The code is shown in Figure 6-6. The code contains instantiation of four 7 FF modules. Example 6-6. Verilog Code lor Ripple Counter module counter(Q , clock, cle: clock, tate the T elipfte ££0(Q(0), clock, endmodule clear clock count enable Figure 6-6. 4-bit Synchronous Counter with clear and count_enable Next, we write the Verilog description for 7_FF (Example 6-7). Notice that instead of the not gate, a dataflow operator ~ negates the signal g, which is fed backDataflow Modeling 74 Example 6-7. Verilog Code tor F-fipflop red T-flipfiop. Toggles every clock module TLFF(q, clk, clear); / 1/0 porte output a: ut elk, clear; }/ instantiate the edge-criag 7 Complement of output q Ls Tf Motice abar eded. Unconnected port edge_dff ff1qr ,-a) clk, clear); ed DEF back endmodule Finally, we define the lowest level module D_FF (edge_dff), using dataflow statements (Example 6-8). The dataflow statements correspond to the logic diagram shown in Figure 6-4. The nets in the logic diagram correspond exactly to the declared nets. Example 6-8. Verilog Code lor Edge-Triggered D-fliphop IY Bdge-triggered 0 flipfiop module edge d€6(q, bar, d, elk, cleaz); SURpUE geaber: input d, elk, clear; / Internal variables Ss) sbar, ry rbar, 77 datariow (Create 2 compler aggign char = selearr of signal clear ut latenes; & is implemented by using 3 5R latches. shar - ~{rbar & s}, 2 = «(bar & char & ~elR), r= s(cbar & selk & 2), kbar - ~(e & char & a); teh (e level sensitive. An edge-senaitive f/ Output latch assign q- ~(s & qbae), qbar = <(q & 5 @ char)? edule The design biock is now ready. Now we must instantiate the design block inside the stimulus block to test the design. The stimulus block is shown in Example 6-9. The clock has a time period of 20 with a 50% duty eycle. Example 6-9. Stimufus Module for Ripple Counter / Top level stimulus module module stimuius; / Declare variables for stim ating input tor(Stime, * coust a = Clears sen, 0 /é Tnatantiate the design Bleek counter counter c1(0, CLOCK, CLEAR): / Stimulate the Clear SignalDataflow Modeling 75 beain CLEAR - 1"b1; #36 CLEAR = 2 #200 CLEAR - 1! #50 CLEAR = 27h Set up the clack to toggle every Lo forever #10 CLOCK = =CE he simulation at time and #400 Sein oc0000e00 2006006000 Summary + Continuous assignmentis one of the main constructs used in dataflow modeling. A continuous assignment is always active and the assignment expression is evaluated as soon as one of the right-hand-side variables changes. The left-hand side of a continuous assignment must be a net. Any logic function can be realized with continuous assignments. + Delay values control the time between the change in a right-hand-side variable and when the new value is assigned to the left-hand side. Delays on a net can be defined in the assign. statement, implicit continuous assignment, or net declaration. + Assignment statements contain expressions, operators, and operands. + The operator types are arithmetic, logical, relational, equality, bitwise, reduction, shift, concat- enation, replication, and conditional. Unary operators require one operand, binary operators require two operands, and ternary require three operands, The concatenation operator can take any number of operands. + The conditional operatorbehaves like a multiplexer in hardware or like the if-then-else statement in programming languages.Dataflow Modeling 76 + Dataflow description of a circuit is more concise than a gate-level description. The 4-to-t multi- plexer and the 4-bit full adder discussed in the gate-level modeling chapter can also be designed by use of dataflow statements. Two dataflow implementations for both circuits were discussed. A 4-bit ripple counter using negative edge-triggered D-flipflops was designed Exercises 4; A full subtractor has three 41-bit inputs x, y, and z (previous borraw) and two 1-bit outputs D (difference) and 8 (borrow). The logic equations for D and B are as follows: Da xiy Zt xt yZ! # XYZ" + YZ Baxiytxiztyz Write the full Verilog description for the full subtractor module, including /O ports (Remember that + in logic equations corresponds to a logical or operator (| |) in dataflow). instantiate the subtractor inside a stimulus block and test all eight possible combinations of x, ¥, and zgiven in the following truth table x ye 2 D oo 00 o oor sd oro1d orto Loo tot 1100 6 2: A magnitude comparator checks if one number is greater than or equal to or less than another number. A 4-bit magnitude comparator takes two 4-bit numbers, A and 8, as input. We write the bits in A and Bas follows. The leftmost bit is the most significant bit. A = A(3) A(2) A(T) A(O) B = B(3) B(2) B(1) B(O) The magnitude can be compared by comparing the numbers bit by bit, starting with the most significant bit. if any bit mismatches, the number with bit 0 is the lower number. To realize this functionality in logic equations, let us define an intermediate variable. Notice that the function below is an xnor function ai) = AG).BO) + AG). BA! ‘The three outputs of the magnitude comparator are A_gt 8, A_it_B, A_eq_&. They are defined with the following logic equations: gt B = A(3).B(3)' + x(3).A(2).B(2)' + (3) x(2).A(1).B(1)' + x(3).x(2).x(1).A(0).B(O}" ALILB = A(3)'B(3) + x(3).A(2)B(2) + x(3).x(2).A(1) B¢1) + X(3).x(2)-X( 1). (0). B(0) A_eq_B = x(3).x(2).x(1).%(0) Write the Verilog description of the module magnitude_comparator. instantiate the magnitude comparator inside the stimulus module and try out a few combinations of A and &.Dataflow Modeling 77 3: A synchronous counter can be designed by using master-slave JK flipflops. Design a 4-bit syn- chronous counter. Circuit diagrams for the synchronous counter and the JK flipflop are given below. The cfear signal is active low. Data gets latched on the positive edge of clock, and the output of the flipflop appears on the negative edge of cfock. Counting is disabled when count_en- able signal is low. Write the dataflow description for the synchranaus counter. Write a stimulus file that exercises clearand count_enable. Display the output count Q/3.0} clear qbar ybar clock cbar Figure 6-5. Master-Slave JK-fipflop78 Chapter 7. Behavioral Modeling With the increasing complexity of digital design, ithas become vitally important to make wise design decisions early in a project. Designers need to be able to evaluate the trade-offs of various archi- tectures and algorithms before they decide on the optimum architecture and algorithm to implement in hardware. Thus, architectural evaluation takes place at an algorithmic level where the designers do not necessarily think in terms of logic gates or data flow but in terms of the algorithm they wish to implement in hardware. They are more concerned about the behavior of the algorithm and its performance. Only after the high-level architecture and algorithm are finalized, do designers start focusing on building the digital circuit to implement the algorithm Verilog provides designers the ability to describe design functionality in an algorithmic manner. In other words, the designer describes the behavior of the circuit, Thus, behavioral modeling repre- sents the circuit at a very high level of abstraction. Design at this level resembles C programming more than it resembles digital circuit design. Behavioral Verilog constructs are similar to C language constructs in many ways. Verilog is rich in behavioral constructs that provide the designer with a great amount of flexibility Learning Objectives + Explain the significance of structured procedures always and ini tial in behavioral modeling. + Define blocking and nonblocking procedural assignments. + Understand delay-based timing control mechanism in behavioral modeling. Use regular delays, intra-assignment delays, and zero delays. + Describe event-based timing control mechanism in behavioral modeling. Use regular event control, named event control, and event OR control. + Use level-sensitive timing control mechanism in behavioral modeling + Explain conditional statements using if and else + Describe multiway branching, using case, casex, and casez statements. + Understand looping statements such as while, for, repeat, and forever. + Define sequential and parallel blocks. + Understand naming of blocks and gisabting of named blocks. + Use behavioral modeling statements in practical examples Structured Procedures ‘There are two structured procedure statements in Verilog: always and ini tial. These statements are the two most basic statements in behavioral modeling. All other behavioral statements can appear only inside these structured procedure statements.Behavioral Modeling 73 Verilog is a concurrent programming language unlike the C programming language, which is se- quential in nature. Activity flows in Verilog run in parallel rather than in sequence. Each always and initial statement represents a separate activity flow in Verilog. Each activity flow starts at sim- ulation time 0. The statements always and initia cannotbe nested. The fundamental difference between the two statements is explained in the following sections initial Statement Allstatements inside an initial statementconstitute an initial block. An initial block starts at time 0, executes exactly once during a simulation, and then does nat execute again. If there are multiple initial blocks, each block starts to execute concurrently at time 0. Each block finishes execution independently of other blocks. Multiple behavioral statements must be grouped, typically using the keywords begin and end. If there is only one behavioral statement, grouping is not nec- essary. This is similar to the begin-end blocks in Pascal programming language or the {} grouping in the C programming language. Example 7-1 illustrates the use of the initial statement. Example 7-1. initial Statement module otimulua: Peg Key, Sy, oy /eingle statement; does not need to be groupe, i #/multiple imodule In the above example, the three initial statements start to execute in parallel at time 0. If a delay #
is seen before a statement, the statement is executed
time units after the current simulation time. Thus, the execution sequence of the statements inside the initial blocks will be as follows. time statement executed a The initia’ blocks are typically used for initialization, monitoring, waveforms and other processes that must be executed only once during the entire simulation run. The following subsections dis- cussion how to initialize values using alternate shorthand syntax. The use of such shorthand syntax has the same effect as an initial block combined with a variable declaration.Behavioral Modeling 80 Combined Variable Declaration and Initialization Va bles can be initialized when they are declared. Example 7-2 shows such a declar: Examplo 7-2. initiat Value Assignment }/The clock variable is deft zag clock; s/he value of clock is set to 0 initial clock - 07 (Instead of the above method, clock variable fean be initialized at the time of declavatian yh. allowed only for variables declared Ha req Combined Port/Data Declaration and Initialization The combined port/data declaration can also be combined with an initialization. Example 7-3 shows such a declaration Example 7-3. Combined PortData Declaration and Variable Initialization module adder (aum, eurpur veg [7:0] output req 0 = OF tialize 1b od alization Combined ANSI C Style Port Declaration and Ini ANSI C style port declaration can also be combined with an initialization. Example 7-4 shows such a declaration Example 7-4. Combined ANSI C Port Declaration and Variable fnitialization module adder (output rea { reg se > [720] a, By 0) sum ~ 0, #/znitieltze @ nit output #/Todedals: e 1 bit output endmedule always Statement All behavioral statements inside an always statement constitute an always block. The always statement starts at time 0 and executes the statements in the alway s block continuously ina looping fashion. This statement is used to model a block of activity that is repeated continuously in a digital circuit, An example is a clock generator module that toggles the clock signal every half cycle. In real circuits, the clock generator is active from time 0 to as long as the circuit is powered on. Example 7-4 illustrates one method to model a clock generator in Verilog. Example 7-5. always Statement module clock gen (output reg clock): /Tndtsalize clock at time sexe k= LorBehavioral Modeling 84 fTeggle very half-cyele (time peried = 20) always $10 eloek - ~eloek: In Example 7-5, the always statement starts at time 0 and executes the statement clock = ~clock every 10 time units, Notice that the initialization of clock has to be done inside a separate ini- tial statement. If we put the initialization of clock inside the always block, clock will be initialized every time the always is entered. Also, the simulation mustbe halted inside an initial statement. Ifthere is no $stop or $£inish statementto halt the simulation, the clock generator will run forever. C programmers might draw an analogy between the always block and an infinite loop. But hardware designers tend to view it as a continuously repeated activity in a digital circuit starting from pawer on. The activity is stopped only by power off (§£inish) or by an interrupt ($stop) Procedural Assignments Procedural assignments update values of reg, integer, real, or time variables. The value placed on a variable will remain unchanged until another procedural assignment updates the vari- able with a different value. These are unlike continuous assignments discussed in Chapter 6, Da- taflow Modeling, where one assignment statement can cause the value of the right-hand-side ex- pression to be continuously placed onto the left-hand-side net. The syntax for the simplest form of procedural assignment is shown below The left-hand side of a procedural assignment can be one of the following: + A reg, integer, real, or time register variable or a memory element + Abit select of these variables (e.g., ader/0) + Apart select of these variables (e.g., addr[31:16)) + A concatenation of any of the above The right-hand side can be any expression that evaluates to a value. In behavioral modeling, all operators listed in Table 6-1 on page 96 can be used in behavioral expressions. There are two types of procedural assignment statements: blacking and nonblocking. Blocking Assignments Blocking assignment statements are executed in the order they are specified in a sequential block. A blocking assignment will not block execution of statements that follow in a parallel block. Bo! parallel and sequential blocks are discussed in Section 7.7, Sequ Blocks. The = operator is used to specify blocking assignments. Example 7-6. Blocking Statements reg Hy Ye ae req [15:0] req a, reg_b //ALL behavioral statements mist be inside an 4 orBehavioral Modeling 82 begin f/Scalar assignments eat to integer varia = reg_a; //initiali #15 reg _a(2] = 1p #10 reg bt15:13) = pit sete 2) //as with delay di par end In Example 7-6, the statement y = 1 is executed only after x = 0 is executed. The behavior in a particular block is sequential in a begin-end block if blocking statements are used, because the statements can execute only in sequence. The statement count = count + 7 is executed last. The simulation times at which the statements are executed are as follows: + All statements x = @ through reg_b = reg_a are executed at time 0 + Statement reg_a/2/ = Oat time = 15 + Statement reg_b/15:13} = fx, y, zfat time = 25 + Statement count = count + 7 at time = 25 + Since there is a delay of 15 and 10 in the preceding statements, count = count + Twill be executed al time = 25 units Note that for procedural assignments to registers, if the right-hand side has more bits than the register variable, the right-hand side is truncated to match the width of the register variable. The least significant bits are selected and the most significant bits are discarded. If the right-hand side has fewer bits, zeros are filled in the most significant bits of the register variable Nonblocking Assignments Nonblocking assignments allow scheduling of assignments without blocking execution of the state- ments that follow in a sequential block. A <= operator is used to specify nonblocking assignments. Note that this operator has the same symbol as a relational operator, /ess_than_equal_to. The op- erator <= is interpreted as a relational operator in an expression and as an assignment operater in the context of a nenblocking assignment. To illustrate the behavior of nonblocking statements and its difference fram blocking statements, let us consider Example 7-7, where we convert some block- ing assignments to nonblocking assignments, and observe the behavior. Example 7-7. Nonblocking Assignments Beg My Ye BE reg [15:0] re eger count; /ALL behavioral statements must be inaide an initial er always block beain x0; yr 1; 27 1p f/Sealar a count = 0; //Aseiqnment to i rega ~ 16"bO; reg_b - req_ay //Taitdal ctors req_a(2] <> #15 ‘bl; //Bit select with reg_b[15:13] <- #20 Ix, y, 2] / § of cancatenation © of a vector count <- count + 1; //Assignment te an integer (increment) end In this example, the statements x = 0 through reg_b = reg_a are executed sequentially at time 0. Then the three nonblocking assignments are processed at the same simulation time. 4. reg_al2] = Ois scheduled to execute after 15 units (i.e., time = 15)Behavioral Modeling 83 2. reg_b[18:13] = fx, y, z}is scheduled to execute after 10 time units (i.e., time = 10) ) Thus, the simulator schedules a nonblocking assignment statement to execute and continues to the next statement in the block without waiting for the nonblocking statement to complete execution. Typically, nonblocking assignment statements are executed last in the time step in which they are scheduled, that is, after all the blocking assignments in that time step are executed 3. count = count + 1 is scheduled to be executed without any delay (i , time In the example above, we mixed blocking and nonblocking assignments to illustrate their behavior. However, it is recommended that blocking and nonblocking assignments not be mixed in the same always block. Application of nonblocking assignments Having described the behavior of nonblocking assignments, it is important to understand why they are used in digital design. They are used as a method to model several concurrent data transfers that take place after a common event. Consider the following example where three concurrent data transfers take place at the positive edge of clock. always @(pesedge clock) beain regl <= 4 reg2 <~ @(negedge clock) in2 > in3 vega <- 41 reg; //The end Id value of vegl Ateach positive edge of clock, the following sequence takes place for the nonblocking assignments. 1. A read operation is performed on each right-hand-side variable, /7/, in2, in3, and reg7, at the positive edge of clock. The right-hand-side expressions are evaluated, and the results are stored internally in the simulator. 2. The write operations to the left-hand-side variables are scheduled to be executed at the time specified by the intra-assignment delay in each assignment, that is, schedule “write” to reg? after 1 time unit, to reg2 at the next negative edge of clock, and to reg3 after 1 time unit 3. The write operations are executed at the scheduled time steps. The order in which the write operations are executed is not important because the internally stored right-hand-side ex- pression values are used to assign to the left-hand-side values. For example, note that reg is assigned the old value of reg? that was stored after the read operation, even if the write operation wrote a new value to reg? before the write operation to reg3 was executed Thus, the final values of reg7, reg2, and reg3 are not dependent on the order in which the assign- ments are processed. To understand the read and write operations further, consider Example 7-8, which is intended to swap the values of registers a and # al each positive edge of clock, using two concurrent always blocks. Example 7-8. Nonblocking Statements to Elininate Race Conditions fate I: Two concurrent always blocks with blocking always @(posedge clock) hon at //Iliustsatien 2; Two concurzent always blocks with nonbleckint always @(pBehavioral Modeling 84 always @(pesedge clock) bce ar In Example 7-8, in Illustration 1, there is a race condition when blocking statements are used. Either a = bwould be executed before b = a, or vice versa, depending on the simulator implementation. Thus, values of registers a and dwill not be swapped. Instead, both registers will get the same value (previous value of 2 or 6), based on the Verilog simulator implementation. However, nonblocking statements used in Illustration 2 eliminate the race condition. At the positive edge of clock, the values of all right-hand-side variables are “read,” and the right-hand-side expres- sions are evaluated and stored in temporary variables. During the write operation, the values stored in the temporary variables are assigned to the left-hand-side variables. Separating the read and write operations ensures that the values of registers a and b are swapped correctly, regardless of the order in which the write operations are performed. Example 7-9 shows how nonblacking as- signments shown in Illustration 2 could be emulated using blocking assignments. Example 7-9. implementing Nanbiocking Assignments using Blocking Assignments ve late the behavior of nonblocking aseignments ng te king assignments aye @ begin [PRead ® and porary vari, asedge clock) s/evore 2 of right-hand-eide expreseiene in temporary varlablee temp_a £ temporary variables to left-hand-side variables For digital design, use of nonblocking assignments in place of blocking assignments is highly rec- ommended in places where concurrent data transfers take place after a common event. In such cases, blocking assignments can potentially cause race conditions because the final result depends on the order in which the assignments are evaluated. Nonblocking assignments can be used ef- fectively to model concurrent data transfers because the final result is not dependent on the order in which the assignments are evaluated. Typical applications of nonblecking assignments include pipeline modeling and modeling of several mutually exclusive data transfers. On the downside, nonblocking assignments can potentially cause a degradation in the simulator performance and increase in memory usage. Timing Controls Various behavioral timing control constructs are available in Verilog. In Verilog, if there are no timing control statements, the simulation time does not advance. Timing controls provide a way to specify the simulation time at which procedural statements will execute. There are three methods of timing control: delay-based timing control, event-based timing control, and fevel-sensitive timing control Delay-Based Timing Control Delay-based timing control in an expression specifies the time duration between when the statement is encountered and when it is executed. We used delay-based timing control statements when writing few modules in the preceding chapters but did not explain them in detail. In this section, we will discuss delay-based timing control statements. Delays are specified by the symbol #. Syntax for the delay-based timing control statement is shown below
You might also like
Introduction To Formal Hardware Verification-Springer-Verlag Berlin Heidelberg (1999)
PDF
No ratings yet
Introduction To Formal Hardware Verification-Springer-Verlag Berlin Heidelberg (1999)
308 pages
Birkhauser Press - Finite Automata, Formal Logic, and Circuit Complexity, Straubing H., 237s - 19
PDF
0% (1)
Birkhauser Press - Finite Automata, Formal Logic, and Circuit Complexity, Straubing H., 237s - 19
237 pages
Current ASIC Design Flow
PDF
No ratings yet
Current ASIC Design Flow
7 pages
Module 1 Chapter 1
PDF
No ratings yet
Module 1 Chapter 1
14 pages
11 Chapter 06 Compression
PDF
No ratings yet
11 Chapter 06 Compression
70 pages
MCA603 Advanced Comp Architecture PDF
PDF
100% (1)
MCA603 Advanced Comp Architecture PDF
247 pages
Journal of Society 54 Soci Rich
PDF
No ratings yet
Journal of Society 54 Soci Rich
788 pages
Open File 2
PDF
No ratings yet
Open File 2
68 pages
Verification of Complex Analog ICs
PDF
No ratings yet
Verification of Complex Analog ICs
35 pages
Hardware Description Languages
PDF
No ratings yet
Hardware Description Languages
12 pages
Design Flow Vlsi
PDF
No ratings yet
Design Flow Vlsi
42 pages
Digital Design Through Verilog-18 PDF
PDF
No ratings yet
Digital Design Through Verilog-18 PDF
31 pages
Glenn Okamoto ASIC Engr Resume SJ
PDF
No ratings yet
Glenn Okamoto ASIC Engr Resume SJ
11 pages
The Missing Link: The Testbench To Dut Connection: David Rich - Mentor A Siemens Business
PDF
No ratings yet
The Missing Link: The Testbench To Dut Connection: David Rich - Mentor A Siemens Business
10 pages
SystemVerilog 20041201165354
PDF
No ratings yet
SystemVerilog 20041201165354
34 pages
Verilog Imp...
PDF
No ratings yet
Verilog Imp...
105 pages
Ankit Resume
PDF
No ratings yet
Ankit Resume
3 pages
17ec53 - Verilog HDL - Combined
PDF
No ratings yet
17ec53 - Verilog HDL - Combined
124 pages
Bias Circuits
PDF
0% (1)
Bias Circuits
5 pages
Verilog
PDF
No ratings yet
Verilog
338 pages
Designing of Alu Using Verilog HDL
PDF
No ratings yet
Designing of Alu Using Verilog HDL
2 pages
Design of DDR4 SDRAM Controller - Ashraful Et. Al.
PDF
No ratings yet
Design of DDR4 SDRAM Controller - Ashraful Et. Al.
5 pages
Shahid Qureshi MSEE
PDF
No ratings yet
Shahid Qureshi MSEE
1 page
Top 7 Analog Design Engineer Interview Questions - Maven Silicon
PDF
No ratings yet
Top 7 Analog Design Engineer Interview Questions - Maven Silicon
1 page
RTL Verification and FPGA Implementation of Vedic Multiplier.
PDF
No ratings yet
RTL Verification and FPGA Implementation of Vedic Multiplier.
7 pages
A Slave VIP For Verification of AMBA AXI-3 Master DUT in UVM
PDF
No ratings yet
A Slave VIP For Verification of AMBA AXI-3 Master DUT in UVM
8 pages
Shotgun Verification
PDF
No ratings yet
Shotgun Verification
19 pages
An Introduction To Functional Verification of I2C Protocol Using UVM
PDF
No ratings yet
An Introduction To Functional Verification of I2C Protocol Using UVM
5 pages
UVM Usage For Dynamic Reconfiguration of Complex Designs DVCon India 2014 Paper
PDF
No ratings yet
UVM Usage For Dynamic Reconfiguration of Complex Designs DVCon India 2014 Paper
12 pages
Dijsktra Thesis
PDF
No ratings yet
Dijsktra Thesis
65 pages
Verilog SAP
PDF
No ratings yet
Verilog SAP
69 pages
Cmos
PDF
100% (1)
Cmos
20 pages
Lecture 17: Designing A Central Processor Unit 1: The Architecture
PDF
100% (1)
Lecture 17: Designing A Central Processor Unit 1: The Architecture
6 pages
Sva in A Uvm Class Based Environment VH v9 I3
PDF
No ratings yet
Sva in A Uvm Class Based Environment VH v9 I3
6 pages
Uvm: The Next Generation in Verification Methodology: Mark Glasser, Methodology Architect February 4, 2011
PDF
No ratings yet
Uvm: The Next Generation in Verification Methodology: Mark Glasser, Methodology Architect February 4, 2011
6 pages
High Speed Uvm B Ased Verification Ip For Gigabit Ethernet Protocol IJERTV2IS120883
PDF
No ratings yet
High Speed Uvm B Ased Verification Ip For Gigabit Ethernet Protocol IJERTV2IS120883
7 pages
Can Protocol Uvm PDF
PDF
No ratings yet
Can Protocol Uvm PDF
5 pages
doku.pub_uvm-ramakrishna
PDF
No ratings yet
doku.pub_uvm-ramakrishna
54 pages
Astro 2004 7
PDF
No ratings yet
Astro 2004 7
322 pages
Design & Verification of AMBA APB Protocol
PDF
No ratings yet
Design & Verification of AMBA APB Protocol
4 pages
Laboratory Experiment For Digital Electronics
PDF
No ratings yet
Laboratory Experiment For Digital Electronics
1 page
UVM RAL Model: Usage and Application
PDF
No ratings yet
UVM RAL Model: Usage and Application
12 pages
Dvcon2017 Uvm Debug Lib Final
PDF
No ratings yet
Dvcon2017 Uvm Debug Lib Final
9 pages
Verdi: Automated Debug System
PDF
No ratings yet
Verdi: Automated Debug System
8 pages
ModelSim ME v10.5c User PDF
PDF
No ratings yet
ModelSim ME v10.5c User PDF
808 pages
Ashutosh Jaiswal Resume (NEW)
PDF
No ratings yet
Ashutosh Jaiswal Resume (NEW)
2 pages
Why Active Low Reset
PDF
No ratings yet
Why Active Low Reset
1 page
PISO Verilog PDF
PDF
No ratings yet
PISO Verilog PDF
5 pages
Verilog
PDF
No ratings yet
Verilog
42 pages
VERILOG
PDF
100% (1)
VERILOG
111 pages
HDL Designer Series TCL Reference Manual: Release v2019.4
PDF
No ratings yet
HDL Designer Series TCL Reference Manual: Release v2019.4
170 pages
Introduction To Computer System
PDF
No ratings yet
Introduction To Computer System
4 pages
VHDL ppt1
PDF
No ratings yet
VHDL ppt1
37 pages
Finite State Machine (FSM) : Example
PDF
No ratings yet
Finite State Machine (FSM) : Example
22 pages
Verilog Basics
PDF
100% (7)
Verilog Basics
50 pages
Manasa Hanakere Krishnappa - Resume
PDF
No ratings yet
Manasa Hanakere Krishnappa - Resume
3 pages
SystemC UVM Library
PDF
No ratings yet
SystemC UVM Library
90 pages
Vlsi Design
PDF
100% (9)
Vlsi Design
215 pages
Full Download Quick Start Guide to VHDL 2nd Edition Brock J. Lameres PDF DOCX
PDF
100% (3)
Full Download Quick Start Guide to VHDL 2nd Edition Brock J. Lameres PDF DOCX
40 pages
Xilinx XC 3000
PDF
100% (1)
Xilinx XC 3000
21 pages
B Tech ECE JNTUA
PDF
No ratings yet
B Tech ECE JNTUA
134 pages
Physical Design - Overall Flow
PDF
No ratings yet
Physical Design - Overall Flow
40 pages
Ece IV Fundamentalsofhdl10ec45 Notes 150103114952 Conversion Gate02
PDF
No ratings yet
Ece IV Fundamentalsofhdl10ec45 Notes 150103114952 Conversion Gate02
288 pages
SISO - Verilog
PDF
No ratings yet
SISO - Verilog
5 pages
DDVHDL - Planning
PDF
No ratings yet
DDVHDL - Planning
1 page
PISO - Verilog
PDF
No ratings yet
PISO - Verilog
5 pages
Section - I Note: This Section Consists of Two Essay Type Questions of Twenty (20) Marks Each, To Be (2 × 20 40 Marks)
PDF
No ratings yet
Section - I Note: This Section Consists of Two Essay Type Questions of Twenty (20) Marks Each, To Be (2 × 20 40 Marks)
14 pages
W.A.T.T.: World Association of Technology Teachers
PDF
No ratings yet
W.A.T.T.: World Association of Technology Teachers
0 pages
MC10E156, MC100E156 5VECL 3-Bit 4:1 Mux-Latch: Description
PDF
No ratings yet
MC10E156, MC100E156 5VECL 3-Bit 4:1 Mux-Latch: Description
8 pages
FIR Filter Design by Windowing
PDF
No ratings yet
FIR Filter Design by Windowing
6 pages