212
Transaction-Based Verification: TestBuilder Reference Manual Product Version 1.10 June 2000 1999-2000 Cadence Design Systems, Inc. All rights reserved. Printed in the United States of America. Cadence Design Systems, Inc., 555 River Oaks Parkway, San Jose, CA 95134, USA Trademarks: Trademarks and service marks of Cadence Design Systems, Inc. (Cadence) contained in this document are attributed to Cadence with the appropriate symbol. For queries regarding Cadence’s trademarks, contact the corporate legal department at the address shown above or call 1-800-862-4522. All other trademarks are the property of their respective holders. Restricted Print Permission: This publication is protected by copyright and any unauthorized use of this publication may violate copyright, trademark, and other laws. Except as specified in this permission statement, this publication may not be copied, reproduced, modified, published, uploaded, posted, transmitted, or distributed in any way, without prior written permission from Cadence. This statement grants you permission to print one (1) hard copy of this publication subject to the following conditions: 1. The publication may be used solely for personal, informational, and noncommercial purposes; 2. The publication may not be modified in any way; 3. Any copy of the publication or portion thereof must include all original copyright, trademark, and other proprietary notices and this permission statement; and 4. Cadence reserves the right to revoke this authorization at any time, and any such use shall be discontinued immediately upon written notice from Cadence. Disclaimer: Information in this publication is subject to change without notice and does not represent a commitment on the part of Cadence. The information contained herein is the proprietary and confidential information of Cadence or its licensors, and is supplied subject to, and may be used only by Cadence’s customer in accordance with, a written agreement between Cadence and its customer. Except as may be explicitly set forth in such agreement, Cadence does not make, and expressly disclaims, any representations or warranties as to the completeness, accuracy or usefulness of the information contained in this document. Cadence does not warrant that use of such information will not infringe any third party rights, nor does Cadence assume any liability for damages or costs of any kind that may result from use of such information. Restricted Rights: Use, duplication, or disclosure by the Government is subject to restrictions as set forth in FAR52.227-14 and DFAR252.227-7013 et seq. or its successor.

Transaction-Based Verification: TestBuilder …mrs8n/soc/SynthesisTutorials/testbuilderref.pdfTransaction-Based Verification: TestBuilder Reference Manual June 2000 2 Product Version

Embed Size (px)

Citation preview

Transaction-Based Verification:TestBuilder Reference Manual

Product Version 1.10June 2000

1999-2000 Cadence Design Systems, Inc. All rights reserved.Printed in the United States of America.

Cadence Design Systems, Inc., 555 River Oaks Parkway, San Jose, CA 95134, USA

Trademarks: Trademarks and service marks of Cadence Design Systems, Inc. (Cadence) contained in thisdocument are attributed to Cadence with the appropriate symbol. For queries regarding Cadence’s trademarks,contact the corporate legal department at the address shown above or call 1-800-862-4522.

All other trademarks are the property of their respective holders.

Restricted Print Permission: This publication is protected by copyright and any unauthorized use of thispublication may violate copyright, trademark, and other laws. Except as specified in this permission statement,this publication may not be copied, reproduced, modified, published, uploaded, posted, transmitted, ordistributed in any way, without prior written permission from Cadence. This statement grants you permission toprint one (1) hard copy of this publication subject to the following conditions:

1. The publication may be used solely for personal, informational, and noncommercial purposes;2. The publication may not be modified in any way;3. Any copy of the publication or portion thereof must include all original copyright, trademark, and other

proprietary notices and this permission statement; and4. Cadence reserves the right to revoke this authorization at any time, and any such use shall be

discontinued immediately upon written notice from Cadence.

Disclaimer: Information in this publication is subject to change without notice and does not represent acommitment on the part of Cadence. The information contained herein is the proprietary and confidentialinformation of Cadence or its licensors, and is supplied subject to, and may be used only by Cadence’s customerin accordance with, a written agreement between Cadence and its customer. Except as may be explicitly setforth in such agreement, Cadence does not make, and expressly disclaims, any representations or warrantiesas to the completeness, accuracy or usefulness of the information contained in this document. Cadence doesnot warrant that use of such information will not infringe any third party rights, nor does Cadence assume anyliability for damages or costs of any kind that may result from use of such information.

Restricted Rights: Use, duplication, or disclosure by the Government is subject to restrictions as set forth inFAR52.227-14 and DFAR252.227-7013 et seq. or its successor.

Transaction-Based Verification: TestBuilder Reference Manual

Contents

Preface ............................................................................................................................ 7

1HDL Tasks API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

$tbv_tvm_connect() PLI Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9$tbv_main() PLI Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10$tbv_task_set_arg_format() PLI Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Calling HDL Tasks from TestBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Creating an HDL TVM Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Calling an HDL TVM Task from a Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11$tbv_task_decl() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12$tbv_task_trigger() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12$tbv_task_add_arg() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12$tbv_task_set_arg_format() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13$tbv_task_decl_done() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13$tbv_task_done() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Example: Defining a TVM Task in Verilog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2Signal Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Signal Class Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Signal Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Signal Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Specifying a Range of Indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Naming a Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Specifying an Initial Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Specifying a Name and an Initial Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Connecting to the HDL Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Defining Read-Only and Write-Only TBV Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

June 2000 2 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

Signal Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Signal Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Size of Operands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Bit and Part Selects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Little Endian and Big Endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Four-State Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Additional Signal Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24tbvSignalT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24tbvSignal4StateT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30tbvSignalHdlT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Arrays of Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32tbvSignalArrayT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32tbvSignalArray4StateT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33tbvSignalArrayHdlT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Arrays of Signals: Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Thread Class Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Thread Control: tbvThreadT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38tbvThreadT::arbModeT Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38tbvThreadT::arbFuncT Function Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38tbvThreadT::statusT Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39tbvThreadT::edgeT Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39tbvThreadT Public Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40tbvThreadT Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42singleArgT and doubleArgT Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Spawning C Functions and C++ Methods as Threads . . . . . . . . . . . . . . . . . . . . . . . . 42Spawning TVM Tasks as Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Controlling the Threading Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44Controlling Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

Synchronizing Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Barriers: tbvBarrierT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

June 2000 3 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

Semaphores: tbvSemT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Mutexes: tbvMutexT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Synchronizing with the Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Wait on Signal Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Wait on Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Wait on Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

Waiting on Multiple Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Types of Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Resource Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59waitCycle() and waitEvent() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60tbvWaitAllSharedT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62tbvWaitAllUnsharedT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63tbvWaitAnyHybridT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63tbvWaitAnySharedT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65tbvWaitAnyUnsharedT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Minimizing the Number of Active Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Suspending on Thread Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Delayed Spawning of Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Suspending Threads and Allocating CPU Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Type-Safe Spawning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

4TVMs, Tasks, and Fibers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Class Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80tbvTvmT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81tbvTaskT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83tbvTaskTypeSafeT Class: Type-Safe Task Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . 85tbvProfileT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87tbvTaskGroupT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91tbvTaskContextT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Automatic Copy and Delete of Task Context Objects . . . . . . . . . . . . . . . . . . . . . . . . . 95

June 2000 4 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

tbvFiberT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96TVMs, Tasks, and Fibers Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

5Randomization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Randomization Class Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Overview of the Randomization Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Type and Range of Generated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Internal Random int Stream for Initial Seeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Seed Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Matching Seeds to Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Example: Unconstrained Random Integer Generation . . . . . . . . . . . . . . . . . . . . . . . 104Specifying Generation Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Specifying Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

tbvRandomT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Value Generators with Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

tbvValueGeneratorT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114tbvValueGeneratorT::generatorModeT Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116tbvIntGeneratorT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120tbvRealGeneratorT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124tbvSignalGeneratorT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127tbvComplexGeneratorT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

Randomization Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

6Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

Data Structures Class Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Overview of the Data Structure Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Requirements for Template Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Enhanced Queues and Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Data Structures Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Public Common Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148tbvDataStructureT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149tbvDataStructureT::priorityMode Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

June 2000 5 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

Iterator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Data Structure Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

tbvStringT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157tbvSparseArrayT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158tbvAssociativeArrayT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161tbvListT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165tbvPriorityListT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168tbvStackT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173tbvQueueT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176tbvPriorityQueueT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179tbvSmartQueueT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184tbvBagT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190tbvSafeHandleT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

7TestBuilder Miscellaneous Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

TestBuilder Stream Class: tbvOut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200Exiting TestBuilder: tbvExit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200TestBuilder Exceptional Condition Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

tbvExceptionT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201tbvExceptionEnvironmentT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Index.............................................................................................................................. 207

June 2000 6 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

June 2000 7 Product Version 1.10

Preface

The Transaction-Based Verification (TBV) system is for logic designers and testbenchdesigners who want to analyze and verify circuit designs at the transaction level. The TBVsystem improves the productivity of engineers working on various aspects of designverification and improves overall confidence of first pass success among both the engineeringand management teams.

The TBV system is integrated with Signalscan TX and NC-Verilog and works with otherVerilog simulators. With the TBV system you can:

■ Record transactions into your simulation database.

❑ See the DTAPI User Guide and the DTAPI Reference Manual for descriptionsof C functions you can use to record transactions into your simulation database.

❑ TestBuilder (see references below) automatically records transactions.

■ View transactions and their properties and relationships in Signalscan TX. See “ViewingTransactions” in the Signalscan Waves User Guide.

■ Automatically generate test stimulus and check expected results with TestBuilder. Seethis book (the TestBuilder Reference Manual) and the TestBuilder User Guide.

■ Interactively discover information stored in one or more SST2 databases withTransactionExplorer. See the TransactionExplorer User Guide.

For notes on this release of TestBuilder, see the TestBuilder Product Notes andTestBuilder Known Problems and Solutions.

Transaction-Based Verification: TestBuilder Reference Manual

1HDL Tasks API

This chapter describes the TestBuilder API that can be called from your HDL code. Currently,this includes only Verilog tasks.

■ $tbv_tvm_connect() PLI Call

■ $tbv_main() PLI Call

■ $tbv_task_set_arg_format() PLI Call

■ Calling HDL Tasks from TestBuilder

❑ $tbv_task_decl()

❑ $tbv_task_trigger()

❑ $tbv_task_add_arg()

❑ $tbv_task_decl_done()

❑ $tbv_task_done()

■ Example: Defining a TVM Task in Verilog

June 2000 8 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

$tbv_tvm_connect() PLI Call

Make this task call in your HDL code to have TestBuilder create an instance of one of yourTestBuilder TVMs (Transaction Verification Models — see “TVMs” in the TestBuilder UserGuide and “TVMs, Tasks, and Fibers” in this manual). The place in your HDL where you makeeach $tbv_tvm_connect() call becomes the hierarchical anchor point for the specifiedTestBuilder TVM instance.

The remainder of this section describes the arguments to $tbv_tvm_connect() . (See also“The $tbv_tvm_connect() PLI Call” in the TestBuilder User Guide.)

The first argument to $tbv_tvm_connect() is a string that is the definition name of yourTVM. This name must appear in the tbvTvmTypes table in your TestBuilder C++ code. (See“Registering a TVM” for information on the tbvTvmTypes table.)

When $tbv_tvm_connect() is called:

1. TestBuilder finds the definition name in the tbvTvmTypes table.

2. TestBuilder calls the user-written create function that is associated with this TVM entryin the tbvTvmTypes table. This function should create an instance of your TVM, usingthe C++ new operator.

3. The constructor of the tbvTvmT base class is called first, which registers this TVMinstance with TestBuilder so that this TVM can be later identified by TestBuilder tests.Your constructor for your derived TVM class is then called.

The second argument to $tbv_tvm_connect() is a string that is the instance name for thisTVM. This name is appended to the full HDL hierarchical path name of where the$tbv_tvm_connect() call is made. The instance name must be unique for your complete,elaborated design. If the instance name is not unique, then TestBuilder gives a warningmessage and subsequent TVMs with the same instance name are not returned by thetbvTvmT::getTvmByInstanceNameP() method. However, your TVM creation willcontinue.

The remaining arguments specify the HDL signals that are associated with TVM formal signalnames. In your TVM, you can use the formal name in thetbvTvmT::getFullInterfaceHdlNameP() method so that you can identify the actualHDL signal in the $tbv_tvm_connect() call. This allows you to refer to just formal namesin your TVM, without needing to know the actual HDL signals that a TVM is referencing.These arguments must appear in pairs, and you can have zero or more pairs.

■ The first argument in the pair is a string name. This will be the formal name of theassociated HDL signal.

June 2000 9 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

■ The second argument in the pair is the HDL signal that will be associated with the formalname. This argument must be a reference to an HDL signal; it must not be a string.

The $tbv_tvm_connect() PLI call can also be made without specifying all the argumentsthat were described above.

If the first argument is missing, then the definition name that TestBuilder uses is the definitionname of the HDL module in which the $tbv_tvm_connect() call is made. For example:

$tbv_tvm_connect( , "my_instance_name", ...);

If the second argument is missing, then the instance name is the instance name of the HDLmodule in which the $tbv_tvm_connect() call is made (the Verilog instance name, withno hierarchy).

You can also leave out any or all of the formal/actual argument pairs in a$tbv_tvm_connect() call. When you make a call totbvTvmT::getFullInterfaceHdlNameP() in your TestBuilder code, the method firstsearches the list of formal names that were given in the $tbv_tvm_connect() call. If thename is not found, then TestBuilder searches the names of ports and regs that are locallydeclared in the HDL module where the $tbv_tvm_connect() call was made.

It is possible to call $tbv_tvm_connect() with no arguments. In this case, the definitionname that TestBuilder uses is the HDL module’s definition name, and the instance name thatTestBuilder uses is the Verilog instance name of the module, without the hierarchy. When youmake calls to tbvTvmT::getFullInterfaceHdlNameP() in your TestBuilder code, thename space in the HDL module where the $tbv_tvm_connect() call is made is used.

$tbv_main() PLI Call

Make this task call in your HDL code after all your $tbv_tvm_connect() calls have beenmade. When $tbv_main() is called, TestBuilder spawns a new process thread and callsyour tbvMain() function. Any tests that you have are expected to be started in yourtbvMain() function.

The $tbv_main() task has no arguments.

$tbv_task_set_arg_format() PLI Call

This task call is similar in function to the tbvProfileT:: setArgFormat() method. Ittakes the name of a profile argument field and a format string to specify the format for thenamed argument when it is displayed as a property value in a transaction in Signalscan.

June 2000 10 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

Calling HDL Tasks from TestBuilder

This section describes the TestBuilder HDL tasks to use when you have a TVM Task writtenin HDL code, and you want to be able to call that HDL TVM Task from your TestBuilder C++code.

The HDL tasks described here enable TestBuilder to make your HDL TVM Task appear toyour tests as if it were a TestBuilder C++ Task. Then if you later migrate your HDL TVM Taskto TestBuilder C++, you do not need to change the interface to the Task.

Creating an HDL TVM Task

Create your HDL TVM Task as described in the following steps:

1. In your HDL code, declare your HDL task to TestBuilder. See “$tbv_task_decl()” onpage 12.

2. In your HDL code, declare your task’s argument types to TestBuilder. See“$tbv_task_add_arg()” on page 12 and “$tbv_task_decl_done()” on page 13.

3. Make a wrapper around a call to your HDL task. The wrapper consists of an alwaysblock that waits on an HDL signal.

4. In the body of the always block wrapper, put a call to the HDL task, followed by a TestTask call that indicates that the HDL task has returned. See “$tbv_task_done()” onpage 13.

5. Declare this HDL trigger signal to TestBuilder. See “$tbv_task_trigger()” on page 12.

Your HDL task can now be invoked from TestBuilder as if it were a C++ task object.

Calling an HDL TVM Task from a Test

In your test, identify and invoke HDL tasks the same way you identify and invoke TestBuildertasks that are written in C++.

TestBuilder performs the following steps when you invoke an HDL task in your test:

1. When TestBuilder is ready to call an HDL task, it first waits on a semaphore that controlsall access to the HDL task. The semaphore around an HDL task call prevents the HDLtask from being called concurrently multiple times. This semaphore is automaticallycreated by TestBuilder, and should not be confused with the Fibers that control taskinvocations. See Chapter 4, “TVMs, Tasks, and Fibers,” for more information on Fibers.

June 2000 11 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

2. When your task invocation acquires the semaphore, the WRITE_ONLYand READ_WRITEarguments that you passed in the task’s task context object are copied to the argumentsof the HDL task call.

3. The HDL trigger signal, which controls entry into the body of your wrapper, istransitioned, and your HDL task is called. Your task can block, if necessary, and you donot need to worry about another task invocation entering the HDL task since entry iscontrolled by the semaphore.

4. When your task returns, your READ_ONLYand READ_WRITEarguments are copied intoyour task context object.

5. The semaphore for this call of the HDL task is released.

$tbv_task_decl()

Use this task at the beginning of a declaration of a new HDL task. The only argument is astring that is the name of the task.

TestBuilder creates a tbvTvmT object that is instantiated in the hierarchy at the point wherethe $tbv_task_decl() call is made. Any additional $tbv_task_decl() calls for otherHDL tasks at this point in the hierarchy also appear in the same TestBuilder TVM.

$tbv_task_trigger()

The argument to this TestBuilder PLI call is an HDL signal that is the trigger for the HDLalways block wrapper that contains the call to your HDL task. When you invoke an HDL taskfrom your TestBuilder code, your arguments are first copied to the HDL signal arguments inyour wrapper, and then TestBuilder causes a transition on this trigger signal. The HDL task isthen called.

$tbv_task_add_arg()

Use this PLI call to describe to TestBuilder the arguments of your HDL task. This is similar tothe way you construct a TestBuilder Profile. See Chapter 4, “TVMs, Tasks, and Fibers,” formore information on Profiles.

The first argument is a string that is the name of the argument, as it will be seen byTestBuilder.

The second argument is an HDL signal that is an actual argument to the HDL task call insideyour HDL task wrapper. When you invoke this task from your TestBuilder C++ code,

June 2000 12 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

TestBuilder copies the value from TestBuilder to this HDL signal, before the HDL task iscalled.

The third argument is optional; it is a string that specifies the direction of this argument. Thedefault is WRITE_ONLY. Other options are READ_ONLY and READ_WRITE. Arguments thatare WRITE_ONLYor READ_WRITEare copied to the HDL task’s argument list before the HDLtask call is made. READ_ONLY and READ_WRITE arguments are copied back to theTestBuilder task context object when the HDL task returns.

You must have the same number of $tbv_task_add_arg() calls as the number ofarguments in your HDL task. The order of your calls to $tbv_task_add_arg() must alsomatch the HDL task argument declaration order.

$tbv_task_set_arg_format()

Use this PLI call to describe to TestBuilder the format of arguments of your HDL task. Thedefault format is hexadecimal. This task works just like thetbvProfileT:: setArgFormat() method.

$tbv_task_decl_done()

You must make this call when you have finished all your calls to $tbv_task_add_arg() ,for a particular HDL task.

$tbv_task_done()

You must make this call immediately after the call to your HDL task, inside your HDL taskwrapper. Typically, you will have an HDL end after the $tbv_task_done() , to close thewrapper block.

Example: Defining a TVM Task in Verilog

This section shows an example of a Verilog task and the TestBuilder C++ code to access thetask.

Following is the Verilog code that defines the task:

//Verilog HDL TVM with task

module vlogTvm (clk, din, dout);

input clk;

input [7:0] din;

June 2000 13 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

output [7:0] dout;

reg doIncr;

reg [7:0] inc_val;

initial begin

$tbv_task_decl("incr_data");

$tbv_task_trigger(doIncr);

$tbv_task_add_arg("inc_val", inc_val);

$tbv_task_decl_done();

end

always @(doIncr) begin

incr_data(inc_val);

$tbv_task_done(doIncr); // Tell TestBuilder the task is done.

end

task incr_data;

input [7:0] inc;

reg [7:0] tmp;

begin

@(posedge clk) tmp = d_in;

@(posedge clk) dout = din + inc;

end

endtask

endmodule

Following is the TestBuilder code that accesses the Verilog task:

// C++ to link to the TVM and run the task

void tbvMain() {

// Setup arguments and connect to Verilog TVM, task, and signals.

tbvTvmT & vlogTvm = *(tbvTvmT::getTvmByFullNameP("top.vlogTvm0");

tbvSignal4StateT incrData(7,0), *incrDataP = &incrData;

tbvTaskT & incrTask = *(vlogTvm.getTaskByNameP("incr_data");

// Setup the context for a run or spawn.

tbvTaskContextT *incrContextP;

int contextSize = incrTask.getProfileP()->getTbvContextSize();

incrContextP = (tbvTaskContextT *)calloc (contextSize, 1);

incrTask.getProfileP()->setValue("inc_val", incrContextP, incrDataP);

incrData = 0x0a;

// Turn on transaction recording.

June 2000 14 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualHDL Tasks API

incrContextP->setInitialFiber(incrTask.getFiberP());

// Run the task.

incrTask.run(incrContextP);

}

June 2000 15 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

2Signal Class

This chapter discusses the signal class (tbvSignalT ), including:

■ Signal Data Types

■ Signal Declarations

■ Signal Assignments

■ Signal Operations

■ Additional Signal Class Methods

❑ tbvSignalT Public Methods

❑ tbvSignal4StateT Public Methods

❑ tbvSignalHdlT Public Methods

■ Arrays of Signals

❑ tbvSignalArrayT Public Methods

❑ tbvSignalArray4StateT Public Methods

❑ tbvSignalArrayHdlT Public Methods

❑ Arrays of Signals: Examples

June 2000 16 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Signal Class Diagram

Signal Data Types

Signal objects embody all the functionality of a variable width bit vector, including arithmetic,logical, and relational operations. Signals may be 2-state (0,1), like integers, or they may be4-state (0,1,X,Z), like Verilog nets or registers.

A Signal object may be (but need not be) mapped to a signal in the HDL. If it is, then writeaccesses to it update the value in the HDL, and read accesses retrieve the current value inthe HDL.

Table 2-1 shows different signal types, which vary according to the values they can store:

Table 2-1 Signal Types Hierarchy

Signal Class Derivation DescriptiontbvSignalT unsigned 2-statetbvSignal4StateT unsigned 4-state

1tbvSignalT tbvSignal4StateT tbvSignalArray4StateT

Implemented as _tbvSignal<T>:

- tbvSignal == _tbvSignal<Uint64>

- tbvSignal4State == _tbvSignal<_tbvSigValue4s>

n

tbvSignalHdlT tbvSignalArrayHdlT

Implemented as _tbvSignalHdlT<_tbvSigValue4s>

June 2000 17 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Signal Declarations

The default constructor creates a single-bit signal, indexed 0..0.

tbvSignalT a;

Specifying a Range of Indices

You can specify a range of indices as follows (msb first):

tbvSignalT a(0,0); // 2-state, unsigned, indexed 0..0

tbvSignalT b(4,0); // 2-state, unsigned, indexed 4..0

tbvSignalT c(3,8); // 2-state, unsigned, indexed 3..8

A signal can be any width:

tbvSignalT c(63,0);

tbvSignalT d(95,0);

tbvSignalT e(127,0);

Naming a Signal

The following example shows how to name a tbvSignalT :

tbvSignalT cedar(63,0,"cedar");

Specifying an Initial Value

If the third argument in the constructor is a numeric value, then that is the initial value of thesignal:

tbvSignalT fir(63,0,"0x0123456789abcdef")

tbvSignalHdlT derived class for mapping to a 4-state signal in the HDLtbvSignalArrayT arrays of unsigned 2-state SignalstbvSignalArray4StateT arrays of unsigned 4-state SignalstbvSignalArrayHdlT arrays of HDL mapped, 4-state Signals

Table 2-1 Signal Types Hierarchy, continued

Signal Class Derivation Description

June 2000 18 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Specifying a Name and an Initial Value

To name a signal with an initial value, use the four-argument constructor:

tbvSignalT balsam(63,0,"0x0123456789abcdef", "balsam")

Connecting to the HDL Model

To map a TBV signal to a signal in the HDL model:

■ Use the tbvSignalHdlT form of the constructor.

■ Specify the signal’s full HDL name.

The constructor infers the signal’s size and type from its declaration in the HDL. For example:

tbvSignalHdlT adder_out("top.cpu.alu.adder.out");

Assigning to adder_out writes into top.cpu.adder.out in the simulator.

Reading adder_out reads the value of top.cpu.adder.out in the simulator.

You can name these signals. This is useful for concatenating Verilog signals. For example:

tbvSignalHdlT instr_word ("{cpu.ibox.opcode,cpu.ibox.op_a,cpu.ibox.op_b}",

"instruction_word");

Defining Read-Only and Write-Only TBV Signals

The READ_ONLY and WRITE_ONLY variants of TBV signal types define a read-only or write-only relationship to the simulator. By default, signals are created READ_WRITE. A write-onlyrelationship increases efficiency, since you do not need to listen for changes from thesimulator. See also the tbvEnumsT::sigDirT enumeration and direction parameter in“tbvSignalHdlT Public Methods” on page 30.

tbvSignalHdlT sequoia("top.cypress.sequoia",tbvEnumsT::READ_WRITE);

Reading sequoia reads the value of top.cypress.sequoia in the simulator.

tbvSignalHdlT sequoia("top.cypress.sequoia",tbvEnumsT::WRITE_ONLY);

Assigning to sequoia writes into top.cypress.sequoia in the simulator.

Signal Operations

Most of the usual arithmetic and logical operators are overloaded to handle signal objects.

June 2000 19 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Table 2-2 below shows operators that are defined in Verilog and C, along with theirequivalents in the signal class.

Following the table, see:

■ Signal Assignments

■ Size of Operands

■ Bit and Part Selects

■ Little Endian and Big Endian

■ Four-State Relational Operators

Operators

Table 2-2 Operators: Verilog, C, and Signal Class Equivalents

Verilog C Description Signal Class (tbvSignalT){} not present concatenation tbvConcatenate(Signal, Signal, ...)

= = assignment =

+ - same unary arithmetic + -

+ - * / same arithmetic + - * /

^ same modulus ^

< <= > >= same relational < <= > >=

! same logical negation !

&& same logical and not overloaded; tbvLogicalAnd(a,b)

|| same logical or not overloaded; tbvLogicalOr(a,b)

== != same logical equality == !=

=== !== not present case equality tbv4StateEqual(),tbv4StateNotEqual()

~ same bitwise negation ~

& same bitwise and &

| same bitwise or |

^ same bitwise xor ^

June 2000 20 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

The operators &&and || are not overloaded. Overloading them would result in function callsemantics where both operands are evaluated with an undefined order of evaluation (insteadof left-to-right).

The comma operator is not overloaded for reasons similar to the issue with &&and || . Withfunction semantics, the overloaded comma operator would not be able to guarantee left-to-

~^ ^~ not present bitwise equivalence tbvBitEquiv()

& not present reduction and reductionAnd()

~& not present reduction nand reductionNand()

| not present reduction or reductionOr()

~| not present reduction nor reductionNor()

^ not present reduction xor reductionXor()

~^ ^~ not present reduction xnor reductionXnor()

<< >> same logical shifts << >>

<<< >>> not present arithmetic shifts tbvArithShiftL()

tbvArithShiftR()?: same conditional not overloadable

not present += add assignment +=

not present -= subtract assignment -=

not present *= multiply assignment *=

not present /= divide assignment /=

not present %= modulo assignment %=

not present ^= xor assignment ^=

not present &= and assignment &=

not present |= or assignment |=

not present >>= <<= shift assignment >>= <<=

not present ++ increment ++

not present -- decrement --

Table 2-2 Operators: Verilog, C, and Signal Class Equivalents, continued

Verilog C Description Signal Class (tbvSignalT)

June 2000 21 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

right evaluation of the operands of comma. In addition, the comma operator is too useful inits ordinary function to be overloaded. For example:

tbvSignalT a(3,0), b(3,0);

for (a=0, b=9; a < 10; a++, b--) {...}

Signal Assignments

If the source and destination widths are the same, all bits are copied from the source to thedestination. If the source and destination widths are not the same, a runtime error messageis issued. This is a form of strong typing, a technique that allows the compiler to statically finderrors in the HDL source code.

In the following example, the value of b is copied to a. The sizes of a and b do not change asthe result of the assignment.

tbvSignalT a;

tbvSignalT b;

a = b;

In the following example, the value of top.redwood.a is retrieved from the simulator at thecurrent time and assigned to b with width checking. It is an error if the widths do not match.

tbvSignalHdlT a("top.redwood.a");

tbvSignal4StateT b;

b = a;

In the following example, the value of the local variable a is changed and the value isscheduled for top.redwood.a in the simulator at the current time step. It is an error if thewidths do not match.

tbvSignalHdlT a("top.redwood.a");

tbvSignal4StateT b;

a = b;

Size of OperandstbvSignal4StateT a(10,0);

tbvSignal4StateT b(10,0);

tbvSignal4StateT c(10,0);

tbvSignal4StateT d(21,0);

tbvSignal4StateT f(4,0);

c = a + b; // all signals are 11 bits wide

d = a * b; // 22 bit result

c = a + f.msbExtend(11); // msb extend f to 11 bits

June 2000 22 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

c = a + f.zeroExtend(11); // zero extend f to 11 bits

The size of the operands of binary operators must be equal. Use the msbExtend() andzeroExtend() member functions to increase the size of rhs signals as needed. The size ofthe receiver of the result must also be the same width as the operands on the rhs. Theexception is the receiver of a multiply, which must be twice the width of the multiplicand andthe multiplier.

Bit and Part Selects

The function call operator, () , is overloaded to select a single bit or a range of bits from amulti-bit signal. The index argument must be in the range as defined by the object constructor.For example:

tbvSignalT s(8,15);

tbvSignalT t;

tbvSignalT u(1,0);

t = s(9); // legal

t = s(3); // error since 3 is out of range for object s;

u = s(8,9);

Bit ranges are supported on the left hand side of an assignment, as shown below:

tbvSignalT a(63,0), b(63,0), c(7,0);

a(63,60) = 0xF;

a(59,56) = b(63,60);

a(55,52) = c(7,0);

a(51,0) = 0x01234567890ABCULL;

b(63) = 1;

Little Endian and Big Endian

It is an error if a signal is declared little endian but is referenced big endian. It is an error if asignal is declared big endian but is referenced little endian. Little endian defined signals mustuse little endian references. Big-endian definitions require big endian references. Forexample:

tbvSignalT bigend(2,10), littlend(10,2);

bigend(4,6) = 7; // ok: big-endian reference and definition

bigend(6,4) = 7; // error: little-endian reference

littlend(4,6) = 7; // error: big-endian reference

littlend(6,4) = 7; // ok: little-endian reference and definition

June 2000 23 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Four-State Relational Operators

If either operand in a 4-state relational expression contains an X bit or a Z bit, then theexpression evaluates to false in an if statement. In the following example, if either opA oropB has any bit that is either X or Z, then the else block of the if statement is executed.

tbvSignal4StateT opA(63,0), opB(63,0);

if (opA == opB)

{ Code that executes if the equality expression is true. }

else

{ Code that executes if the equality expression is false. }

Relational expressions have a 4-state value when they are used as an r-value. That is, on theright hand side of an assignment, relational expressions produce a 4-state bit value. In thefollowing example, if either opA or opB contains an X bit or a Z bit, thenconditionCodeEqual is X. If opA has the same defined (unambiguous) numeric value asopB, then conditionCodeEqual is a 1. If opA and opB are not ambiguous but also are notequal, conditionCodeEqual is a 0.

tbvSignal4StateT opA(63,0), opB(63,0), conditionCodeEqual(0,0);

conditionCodeEqual = (opA == opB);

For more information and examples, see “Relational Operations on Four-State Signals” in theTestBuilder User Guide. See also tbv4StateEqual() and tbv4StateNotEqual() .

Additional Signal Class Methods

tbvSignalT Public Methods

Table 2-3 lists the tbvSignalT public methods. Following the table, see:

■ Assigning Hex and Binary Constants

■ Converting 2-State to 4-State and 4-State to 2-State Signals

■ Reduction Functions

Table 2-3 tbvSignalT Public Methods

Public Method DescriptiontbvSignalT(); Create a single bit signal with range 0..0.

June 2000 24 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

tbvSignalT(const char *initialValue);

Create a signal with value initialValue . Usethis form to create constants in your model.

tbvSignalT( int msb, int lsb ); Create a multibit signal with range msb..lsb .tbvSignalT( int msb, int lsb ,const char * initialValueOrName );

Create a multibit signal with range msb..lsb andeither an initial value or a name.

tbvSignalT( int msb, int lsb ,const char * initialValueOrName ,const char * initialValueOrName );

Create a multibit signal with range msb..lsb andboth an initial value and a name.

tbvSignalT(tbvSignalT&); Create a signal that is a copy of another signal.tbvSignalT& operator=(const tbvSignalT&);

Assign a signal. Make sure operands are the sametype. Use convertXZ() to assign a 4-state to a 2-state.

tbvSignalT& operator=(const char * value );

Assign a constant hex or binary value to a signal.See “Assigning Hex and Binary Constants” onpage 28.

tbvSignalT convertXZ(int XBecomes, int ZBecomes);

Convert a tbvSignal4StateT ortbvSignalHdlT from 4-state to 2-state. Thearguments XBecomes and ZBecomes map X andZ to 1 or 0. See also “Converting 2-State to 4-Stateand 4-State to 2-State Signals” on page 28.

int lsb() const; Return the LSB of the signal.int msb() const; Return the MSB of the signal.int size() const; Return the number of bits in the signal, which is

equal to: |msb-lsb|+1const tbvSignalT operator()(const int index ) const;

Return index ..index as a signal of size 1.

const tbvSignalT operator()(const int msb, const int lsb )const;

Return msb..lsb as a signal of size |lsb -msb|+1.

tbvSignalT operator()(const int msb, const int lsb );

Return msb..lsb as a signal of size |lsb -msb|+1.Used for signals that are not const .

tbvSignalT operator()(const int subscript );

Return the signal at subscript . Used for signalsthat are not const .

tbvSignalT zeroExtend(const int width );

Zero-extend. It is an error if the new width isshorter than the original width.

Table 2-3 tbvSignalT Public Methods, continued

Public Method Description

June 2000 25 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

tbvSignalT msbExtend(const int width );

Sign-extend. It is an error if the new width isshorter than the original width.

friend tbvSignalT tbvConcatenate(const tbvSignalT&,const tbvSignalT&);

Concatenate two signals. For example:

a = tbvConcatenate(b, c);

friend tbvSignalT operator+(consttbvSignalT&, const tbvSignalT&);

Add two signals.

friend tbvSignalT operator-(consttbvSignalT&, const tbvSignalT&);

Subtract two signals.

friend tbvSignalT operator*(consttbvSignalT&, const tbvSignalT&);

Multiply two signals.

friend tbvSignalT operator/(consttbvSignalT&, const tbvSignalT&);

Divide two signals.

friend tbvSignalT operator%(consttbvSignalT&, const tbvSignalT&);

Modulo two signals.

friend bool operator>(consttbvSignalT&, const tbvSignalT&);

Compare two signals.

friend bool operator>=(consttbvSignalT&, const tbvSignalT&);

Compare two signals.

friend bool operator<(consttbvSignalT&, const tbvSignalT&);

Compare two signals.

friend bool operator<=(consttbvSignalT&, const tbvSignalT&);

Compare two signals.

const bool operator!() const; Logical negation.const bool tbvLogicalAnd(consttbvSignalT&, const tbvSignalT&);

Logical AND.

const bool tbvLogicalOr(consttbvSignalT&, const tbvSignalT&);

Logical OR.

const bool operator==(consttbvSignalT&, const tbvSignalT&);

Logical equality.

const bool operator!=(consttbvSignalT&, const tbvSignalT&);

Logical inequality.

const bool tbv4StateEqual(consttbvSignalT&, const tbvSignalT&);

Case equality. See examples in “tbv4StateEqual()and tbv4StateNotEqual()” in the TestBuilder UserGuide.

const bool tbv4StateNotEqual(consttbvSignalT&, const tbvSignalT&);

Case inequality.

tbvSignalT operator~(const tbvSignalT&) const;

Bitwise negation. Return a signal of the same sizeas the argument.

const tbvSignalT operator&(consttbvSignalT&, const tbvSignalT&);

Bitwise AND.

const tbvSignalT operator|(consttbvSignalT&, const tbvSignalT&);

Bitwise OR.

Table 2-3 tbvSignalT Public Methods, continued

Public Method Description

June 2000 26 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

const tbvSignalT operator^(consttbvSignalT&, const tbvSignalT&);

Bitwise XOR.

const tbvSignalT tbvBitEquiv(const tbvSignalT&,const tbvSignalT&);

Bitwise equivalence.

const bool reductionAnd() const; Reduction AND. Usage:

a = b.reductionAnd();

const bool reductionNand() const; Reduction NAND.const bool reductionOr() const; Reduction OR.const bool reductionNor() const; Reduction NOR.const bool reductionXor() const; Reduction XOR.const bool reductionXnor() const; Reduction XNOR.const tbvSignalT operator>> (const tbvSignalT&, int);

Logical shift right. The returned signal is the samesize as the shifted signal.

const tbvSignalT operator<< (const tbvSignalT&, int);

Logical shift left. The returned signal is the samesize as the shifted signal.

const tbvSignalT arithShiftL (const tbvSignalT&, int);

Arithmetic shift left. The returned signal is the samesize as the shifted signal.

const tbvSignalT arithShiftR (const tbvSignalT&, int);

Arithmetic shift right. The returned signal is thesame size as the shifted signal.

ostream& operator<< (ostream&,const tbvSignalT&);

Output a signal.

istream& operator>> (istream&,const tbvSignalT&);

Input a signal.

void setRecording(tbvTvmT * tvmP ,const char * signalName =CHAR_P_NULL) const

Turns on recording of value transitions on signalsignalName into the SST2 database. The tvmPargument is the TestBuilder TVM in which thissignal is declared, and signalName is the nameof the signal that will appear in the database. IfsignalName is NULL, then the signal name isobtained from the declaration of the tbvSignalT .If there is no signal signalName , then TestBuildercreates a signal name.

Table 2-3 tbvSignalT Public Methods, continued

Public Method Description

June 2000 27 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Assigning Hex and Binary Constants

A hex constant may include 0-9 and A-F. A binary constant may include X and Z. AssigningX or Z to a 2-state causes an error.

tbvSignalT ash(95,0);

tbvSignalT balsam(31,0);

ash = "0xEDACADEDACADEDACADEDACAD";

balsam = "0b11011110101011011011111011101111";

You can use either 0x /0X or 0h /0H to specify a hex constant. You may want to use 0h /0H tomake your code more readable when you are assigning Xs.

tbvSignal4StateT cedar(63,0);

cedar = "0xZZZZZZZZZZZZZZZZ"; // 64 bits of Zs

cedar = "0hXXXXXXXXXXXXXXXX"; // 64 bits of Xs

Converting 2-State to 4-State and 4-State to 2-State Signals

See the from2To4State() and convertXZ() methods.

An example 2-state to 4-state conversion is shown below:

tbvSignalT sig2State(63,0);

tbvSignalHdlT sig4State("top.alu.out");

sig4State = sig2State; // ERROR: produces compile-time error message

sig4State = sig2State.from2To4State(); // okay: explicit type conversion

tbvUInt64T*tbvSignalT::getValueP()

Return a pointer to a tbvUInt64T (a typedef forunsigned long long , a 64-bit integer). Can beused for type conversion from Signals to integers:

tbvSignalT sig2State("top.alu.out");

tbvUInt64T *sigP;

sigP = sig2State.getValueP();

tbvSignal4StateTtbvSignalT::from2To4State()

Return a 4-state value based on the value of a2-state signal. The returned 4-state value has no Xor Z bits. This is an explicit type conversion. Seealso “Converting 2-State to 4-State and 4-State to2-State Signals” on page 28.

Table 2-3 tbvSignalT Public Methods, continued

Public Method Description

June 2000 28 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Example 4-state to 2-state conversions are shown below:

sig2State = sig4State; // ERROR: produces compile-time error message

sig2State = sig4State.convertXZ(); // okay: X->1, Z->0 by default

sig2State = sig4State.convertXZ(0,1); // okay: X->0, Z->1

Reduction Functions

These member functions produce a result similar to the Verilog in-fix operators.

If you call one of these operators on a 4-state signal, it returns FALSE if any bit is X or Z. Ifyou assign the result of any of these operators on a 4-state signal that contains an X or a Z,the assigned value is an X.

These operators return one bit on the right hand side of an assignment. They evaluate toTRUE or FALSE in if expressions.

The following example shows the use of the Signal reduction functions:

tbvSignal4StateT s4_8(7,0);

s4_8 = 0xE;

if (!s4_8.reductionOr())

{

tbvOut << "*** reductionOr() failure: " << s4_8.reductionOr() << " s4_8: "

<< s4_8 << endl;

}

if (s4_8.reductionAnd())

{

tbvOut << "*** reductionAnd() failure: " << s4_8.reductionAnd() << " s4_8: "

<< s4_8 << endl;

}

if (s4_8.reductionNor())

{

tbvOut << "*** reductionNor() failure: " << s4_8.reductionNor() << " s4_8: "

<< s4_8 << endl;

}

if (!s4_8.reductionNand())

{

tbvOut << "*** reductionNand() failure: " << s4_8.reductionNand()

<< " s4_8: " << s4_8 <<

endl;

}

if (!s4_8.reductionXor())

June 2000 29 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

{

tbvOut << "*** reductionXor() failure: " << s4_8.reductionXor() << " s4_8: "

<< s4_8 << endl;

}

if (s4_8.reductionXnor())

{

tbvOut << "*** reductionXnor() failure: " << s4_8.reductionXnor()

<< " s4_8: " << s4_8 <<

endl;

}

s4_8 = "0bx1111111";

if (tbv4StateNotEqual(s4_1 = s4_8.reductionOr(), "0bx"))

{

tbvOut << "*** reductionOr() failure: " << s4_8.reductionOr() << " s4_8: "

<< s4_8 << endl;

}

tbvSignal4StateT Public Methods

tbvSignalHdlT Public Methods

The tbvSignalHdlT class is derived from tbvSignalT .

Table 2-4 tbvSignal4StateT Public Methods

Public Method DescriptiontbvSignal4StateT(); Create a single bit signal with range 0..0.tbvSignal4StateT(const char *initialValue);

Create a signal with value initialValue . Usethis form to create constants in your model.

tbvSignal4StateT(int msb, int lsb );

Create a multibit signal with range msb..lsb .

tbvSignal4StateT(int msb, int lsb ,const char * initialValueOrName );

Create a multibit signal with range msb..lsb andeither an initial value or a name.

tbvSignal4StateT(int msb, int lsb ,const char * initialValueOrName ,const char * initialValueOrName );

Create a multibit signal with range msb..lsb andboth an initial value and a name.

June 2000 30 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

The tbvEnumsT::sigDirT enumeration specifies the direction of the link with the HDL.

Table 2-5 tbvEnumsT::sigDirT Enum Members

Member Description

READ_ONLY Fetches a value from the HDL.

WRITE_ONLY Updates the HDL value.

READ_WRITE Both fetches and updates HDL values.

Table 2-6 tbvSignalHdlT Public Methods

Public Method DescriptiontbvSignalHdlT(const char* HdlName,const sigDirTdirection =READ_WRITE);

Map a signal without a user name.

tbvSignalHdlT(const char* HdlName,const char* UserName,const sigDirTdirection =READ_WRITE);

Map a signal with a user name.

tbvSignalHdlT(const tbvSignalHdl&);

copy constructor

char *tbvSignalHdlT::getHdlNameP()

Return the name of the HDL signal that was passedinto the constructor for an HDL mapped Signal. Forexample:

tbvSignalHdlT alu("top.alu.out");

char * name = alu.getHdlNameP();

// name points to the string "top.alu.out"

tbvUInt64T*tbvSignalHdlT::getValueP()

Return a pointer to a tbvUInt64T (a typedef forunsigned long long , a 64-bit integer). Can beused for type conversion from Signals to integers:

tbvSignalHdlT sig4State("top.alu.out");

tbvUInt64T *sigP;

sigP = sig4State.getValueP();

June 2000 31 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

Arrays of Signals

TestBuilder provides three types of arrays of Signals, which correspond to the three types ofSignals discussed above: tbvSignalArrayT , tbvSignalArray4StateT , andtbvSignalArrayHdlT .

Most Signal operations do not apply to arrays of Signals. The only operations supported forarrays of Signals are subscripting and assignment.

Subscripting is supported for all three types of arrays of Signals. Assignment is supported fortbvSignalArrayT and tbvSignalArray4StateT , but not for tbvSignalArrayHdlT .There is no copy operation defined for tbvSignalArrayHdlT arrays; you must copy thesearrays one element at a time.

tbvSignalArrayT Public Methods

Table 2-7 tbvSignalArrayT Public Methods

Public Method DescriptiontbvSignalArrayT(const int size ,const int msb, const int lsb );

Create an array of tbvSignalT[size:0] with thespecified msb and lsb . For example:

tbvSignalArrayT sigArray(128,63,0);

tbvSignalArrayT(const int size ,const int msb, const int lsb ,const char* NameOrValue );

Create an array of tbvSignalT[size:0] with thespecified msb and lsb . Initialize all array elementsto NameOrValue if that string is numeric, or namethe array if NameOrValue is not numeric.

tbvSignalArrayT(const int size ,const int msb, const int lsb ,const char* Value ,const char* Name);

Create an array of tbvSignalT[size:0] with thespecified msb and lsb . Initialize all array elementsto Value if that string is numeric, and name thearray with the string Name.

tbvSignalArrayT& operator=(const tbvSignalArrayT&);

Copy one array to another.

tbvSignalT& operator[](const int index ) const;

Select a word from the array.

June 2000 32 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

tbvSignalArray4StateT Public Methods

tbvSignalArrayHdlT Public Methods

Arrays of Signals: Examples

The following is TestBuilder code that shows arrays of Signals:

void tbvMain()

{

tbvSignalArrayT sigArray1(128, 31,0);

tbvSignalArrayT sigArray2(128, 31,0);

Table 2-8 tbvSignalArray4StateT Public Methods

Public Method DescriptiontbvSignalArray4StateT(const int size , const int msb,const int lsb );

Create an array of tbvSignal4StateT[size:0]with the specified msb and lsb . For example:

tbvSignalArray4StateT sigArray(128,63,0);

tbvSignalArray4StateT(const int size , const int msb,const int lsb ,const char* NameOrValue );

Create an array of tbvSignal4StateT[size:0]with the specified msb and lsb . Initialize all arrayelements to NameOrValue if that string isnumeric, or name the array if NameOrValue is notnumeric.

tbvSignalArray4StateT& operator=(const tbvSignalArray4StateT&);

Copy one array to another.

tbvSignal4StateT& operator[](const int index ) const;

Select a word from the array.

Table 2-9 tbvSignalArrayHdlT Public Methods

Public Method DescriptiontbvSignalArrayHdlT(const _tbvHdlNameProxyT HdlName,const char* UserName,const tbvEnumsT::sigDirTdirection =tbvEnumsT::READ_WRITE);

Create an array of tbvSignalHdlT that is thesize of the HDL array (and has the same msb andlsb of the HDL array.) UserName anddirection are optional, as withtbvSignalHdlT constructors.

tbvSignalHdlT& operator[](const int index );

Select a word from the array.

June 2000 33 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

sigArray2[100] = 0xffff0000;

sigArray1 = sigArray2; // copy all words of sigArray2

// to all words of sigArray1

tbvSignalHdlT hdl64("my_top.hdl63");

tbvSignalArrayHdlT hdlArray("my_top.hdlArray");

for (int i = 0; i < 20; i++)

{

tbvOut << hdlArray[0] << " " << hdlArray[1] << " "

<< hdlArray[2] << " " << hdlArray[2](7,4) << endl;

tbvWait(2);

}

hdlArray[2](7,4) = 0xd;

tbvOut << hdlArray[0] << " " << hdlArray[1] << " "

<< hdlArray[2] << " " << hdlArray[2](7,4) << endl;

tbvWait(20);

hdlArray[127] = hdlArray[0] + hdlArray[1] + hdlArray[2];

tbvOut << "127: = " << hdlArray[127] << endl;

}

The following is Verilog code that shows arrays of Signals:

module my_top;

reg[63:0] hdl63;

reg[10:0] hdlArray[127:0];

initial begin

#10

$display("Now calling $tbv_main() to start the TestBuilder tests");

$tbv_main();

hdlArray[1] = 64’b1111;

#10

hdlArray[2] = 64’b000100100011;

#10

hdlArray[0] = 64’b010001000100;

$display("Verilog: %x", hdlArray[127]);

$display("Verilog, sum: %x", hdlArray[0] + hdlArray[1] + hdlArray[2]);

#50

$display("Verilog: %x", hdlArray[127]);

$display("Verilog, sum: %x", hdlArray[0] + hdlArray[1] + hdlArray[2]);

June 2000 34 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualSignal Class

#1000

$finish;

end

endmodule

June 2000 35 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

3Concurrency

This section describes the multithreading facility in TestBuilder. The ability to express a testas multiple interacting threads facilitates localization of test intent, since a single thread caninitiate a transaction and check its results, even as other activity occurs in the testbench. Anexample of this is testing multiple interacting state machines.

This chapter discusses the following topics:

■ Thread Control: tbvThreadT Class

❑ Spawning C Functions and C++ Methods as Threads

❑ Spawning TVM Tasks as Threads

❑ Controlling the Threading Package

❑ Controlling Threads

■ Synchronizing Threads

■ Synchronizing with the Simulator

❑ Wait on Signal Change

❑ Wait on Time

❑ Wait on Event

■ Waiting on Multiple Items

❑ Resource Sets

■ Minimizing the Number of Active Threads

❑ Suspending on Thread Count

❑ Delayed Spawning of Threads

■ Suspending Threads and Allocating CPU Time

■ Type-Safe Spawning

June 2000 36 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Thread Class Diagram

Names

Most objects described here can be given string names. Unnamed objects cannot beaccessed via Signalscan or the command line. You can determine the name of an object viaits getNameP() method.

tbvTaskT tbvThreadT tbvThreadT

tbvThreadT

parent

children1 n

tbvSignalT tbvSemTtbvMutexT tbvEventTtbvBarrierT

n n n n n

1 1 1 1 1

June 2000 37 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Thread Control: tbvThreadT Class

tbvThreadT::arbModeT Enum

The tbvThreadT::arbModeT enumeration specifies the ordering of the list of threads thatare ready to run. See getArbitration() and setArbitration() in “tbvThreadT PublicMethods” on page 40. See also “Controlling the Threading Package” on page 44.

tbvThreadT::arbFuncT Function Type

A function of type tbvThreadT::arbFuncT specifies how threads are sorted for a customsort. (See the CUSTOM member of “tbvThreadT::arbModeT Enum” above.) ThetbvThreadT::arbFuncT type is defined as:

typedef int (*arbFuncT)(const tbvThreadT&, const tbvThreadT&);

Table 3-1 tbvThreadT::arbModeT Enum Members

Member Description

FIFO Ignores priority.

FIFO_PRIORITY FIFO within highest-priority READY threads. (See“tbvThreadT::statusT Enum” on page 39.)

LIFO Ignores priority.

LIFO_PRIORITY LIFO within highest-priority READY threads.

RANDOM Randomly select some READY thread.

RANDOM_PRIORITY Randomly select among highest-priority READY threads.

CUSTOM Selects the first thread from the list of READY threads,which is sorted according to a user-specifiedtbvThreadT::arbFuncT function. See“tbvThreadT::arbFuncT Function Type” below.

June 2000 38 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvThreadT::statusT Enum

The tbvThreadT::statusT enumeration specifies the status of a thread. See thegetStatus() method in Table 3-4 on page 40.

tbvThreadT::edgeT Enum

The tbvThreadT::edgeT enumeration specifies the edge of a signal to wait on. See “Waiton Signal Change” on page 55.

Table 3-2 tbvThreadT::statusT Enum Members

Member Description

DONE Completed or killed.

READY Eligible to run.

RUNNING Executing on the CPU.

WAITING Waiting for some resource or simulator event.

Table 3-3 tbvThreadT::edgeT Enum Members

Member Description

ANYEDGE Wait on any change in a signal’s value.

NEGEDGE Wait on a negative edge on the signal. That is, wait untilone of the following transitions occurs on the LSB of thesignal:

X --> 0, Z --> 01 --> 0, 1 --> X, 1 --> Z

POSEDGE Wait on a positive edge on the signal. That is, wait untilone of the following transitions occurs on the LSB of thesignal:

X --> 1, Z --> 10 --> 1, 0 --> X, 0 --> Z

June 2000 39 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvThreadT Public Methods

Table 3-4 shows the public methods of the tbvThreadT class.

Table 3-4 tbvThreadT Public Methods

Public Method Descriptionconst tbvListT<tbvThreadT>getChildren() const;

Return a list of the direct descendants of the currentthread in a tbvListT structure.

const char *getNameP(); Return the name of this thread.int getNumDescendants(); Return a count of the direct and indirect

descendants of the current thread.tbvThreadT getParent(); Return the ancestor of the current thread.int getPriority(); Return the priority of this thread. See

“tbvThreadT::arbModeT Enum” on page 38.statusT getStatus(); Return the status of this thread. See

“tbvThreadT::statusT Enum” on page 39.tbvTaskT *getTaskP() const; For threads spawned by tbvTaskT::spawn() ,

return a pointer to the spawning task. For otherthreads, return 0.

unsigned long long getUniqueId(); Return the id of this thread. Every spawned threadhas a unique id that is a 64-bit unsigned integer.

void kill(); Kill this thread. See “Controlling Threads” onpage 45.

static void getArbitration(tbvThreadT::arbModeT& mode,tbvThreadT::arbFuncT& func );

Determine the current arbitration criteria for the listof threads that are ready to run. See“tbvThreadT::arbModeT Enum” on page 38.

static int getNumThreads(); Return the total number of threads, not countingthose with status DONE.

static unsigned getStackSize(); Determine the stack size currently in use for newthreads.

static tbvThreadT self(); Return a reference to the currently-executingthread.

static void setArbitration(tbvThreadT::arbModeT mode,tbvThreadT::arbFuncT func );

Set the ordering for the list of threads that are readyto run. The default is FIFO. See“tbvThreadT::arbModeT Enum” on page 38.

June 2000 40 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

void setPriority(int priority ); Set the priority of this thread to priority . See“tbvThreadT::arbModeT Enum” on page 38.

static void setStackSize(unsigned size );

Set the stack size to be used for new threads tosize .

static tbvThreadT spawn(const char * threadname ,tbvThreadT::singleArgT func ,void * args );

Create a named thread to run a function with asingle void* argument.

static tbvThreadT spawn(tbvThreadT::singleArgT func ,void * args );

Create an unnamed thread to run a function with asingle void* argument.

static tbvThreadT spawn(const char * threadname ,tbvThreadT::doubleArgT func ,void * data , void * args );

Create a named thread to run a function with twovoid* arguments.

static tbvThreadT spawn(tbvThreadT::doubleArgT func ,void * data , void * args );

Create an unnamed thread to run a function withtwo void* arguments.

static void waitAllThreads(int threshold );

Suspend the current thread until the total number ofnot-yet-terminated threads drops below thespecified threshold .

static void waitChildren(int threshold );

Suspend the current thread until the count of itsnot-yet-terminated children drops below thespecified threshold .

static void waitDescendants(int threshold );

Suspend the current thread until the count of itsnot-yet-terminated descendants drops below thespecified threshold .

static void yield(); Yield control back to the thread scheduler. See“Controlling Threads” on page 45.

Table 3-4 tbvThreadT Public Methods, continued

Public Method Description

June 2000 41 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvThreadT Functions

Table 3-5 shows functions that take a tbvThreadT argument:

singleArgT and doubleArgT Types

The tbvThreadT::singleArgT and tbvThreadT::doubleArgT types are used in thetbvThreadT::spawn() methods shown above. These types are defined as follows:

typedef void (*singleArgT)(void *args);

typedef void (*doubleArgT)(void *data, void *args);

Spawning C Functions and C++ Methods as Threads

You can use tbvThreadT::spawn() to create a new thread to execute the specified Cfunction. You can specify either a function that takes a single void* argument, or one thattakes two void* arguments. It may be more convenient to spawn threads to execute tasksin C TVMs using two arguments: one that points to the TVM’s persistent state, and one thatpoints to data specific to this task call.

You can discard the tbvThreadT returned by tbvThreadT::spawn() when you arefinished interacting with the thread. You do not need to check whether the thread hasterminated.

TestBuilder includes a set of templates for spawning of both C functions and C++ methods,with compile-time type checking. For information on these templates, see “Type-SafeSpawning” on page 72 and “tbvTaskTypeSafeT Class: Type-Safe Task Invocation” onpage 85.

Spawning TVM Tasks as Threads

This discussion applies to new TVMs, written in C++. For TVMs written in C, see “SpawningC Functions and C++ Methods as Threads” above.

Table 3-5 tbvThreadT Functions

Function Descriptionvoid tbvWait(tbvThreadT) Suspend the calling thread until the specified thread is

complete.

June 2000 42 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

It seems natural to define a TVM as a class and TVM tasks as member functions of the TVMclass. Unfortunately, that approach causes problems when you try to spawn TVM tasks. Toavoid these problems, wrap an object around each TVM task as described below.

First, define a TVM as a class derived from tbvTvmT , and declare its tasks as instancevariables of types derived from tbvTaskT . The tbvTaskT base class facilitates registrationof TVMs, and it also makes it possible to spawn TVM tasks.

The following example illustrates how these classes work. Suppose you want to create a TVMtype my_tvm_t , which includes two tasks, do_task1 and do_task2 , and which referencessignals CLK and DATA from the $tbv_tvm_connect() in the Verilog. Following is adefinition for my_tvm_t :

class my_tvm_t : public tbvTvmT {

my_tvm_t()

// get CLK

: clk( *( new tbvSignalHdlT(getFullInterfaceHdlNameP("CLK" )) ) ),

// get DATA

data( *( new tbvSignalHdlT(getFullInterfaceHdlNameP("DATA")) ) ),

do_task1(this), // constructor for task1 wrapper

do_task2(this) // constructor for task2 wrapper

{} // no code in constructor

// wrapper class for task1

class do_task1 : public tbvTaskT {

private:

my_tvm_t& parent;

public:

do_task1(my_tvm_t *parent_tvm)

: tbvTaskT(parent_tvm,"do_task1"),

parent(*parent_tvm)

{}

virtual void body(tbvTaskContextT *args) {

/* CODE FOR TASK1 */

}

};

// wrapper class for task2

class do_task2 : public tbvTaskT {

private:

my_tvm_t& parent;

public:

do_task2(my_tvm_t *parent_tvm)

: tbvTaskT(parent_tvm,"do_task2"),

June 2000 43 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

parent(*parent_tvm)

{}

virtual void body(tbvTaskContextT *args) {

/* CODE FOR TASK2 */

}

};

// function that the registry calls to create a TVM instance

static void create() { new my_tvm_t(); }

// declare handles for CLK and DATA

tbvSignalT &clk, &data;

// declare instance variables for task1 and task2

class do_task1 do_task1;

class do_task2 do_task2;

};

Since clk and data are declared ahead of do_task1 and do_task2 , the values of clkand data are available inside the constructors for do_task1 and do_task2 .

The do_task1.body() and do_task2.body() task bodies can use the parent pointer toreference instance variables in my_tvm .

Calling Tasks

Use tvm.task1.run( arg ) to call the task blocking. Use tvm.task1.spawn( arg ) tocall the task non-blocking (that is, to execute it in a new thread). See “tbvTaskT Class” onpage 83 for more information on run() and spawn() .

Controlling the Threading Package

The tbvThreadT class has several static member functions that interact with the threadingfacility rather than with a single thread:

The self() function returns a reference to the currently-executing thread.

The threading facility maintains a list of threads that are ready to run. ThesetArbitration() function controls how this list is ordered. The default is FIFO. Todirectly control the order, select CUSTOMand provide your own arbitration function. The threadlist is maintained in increasing order according to this function. Use getArbitration() todetermine the current arbitration criteria.

To access the stack size used for new threads, use getStackSize() andsetStackSize() . Changing stack size does not affect threads that already exist.

June 2000 44 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

The waitChildren() and waitDescendants() methods allow a test to suspend until itscount of not-yet-terminated children (directly spawned) or descendants (spawned by somechild or descendant) drops below the specified threshold.

Controlling Threads

To create a thread, use tbvThreadT::spawn() or tbvTaskT::spawn() .

Important

Do not store pointers or references to tbvThreadT : Always pass the tbvThreadTdirectly.

So that the threading package knows when it can recover resources associated with athread, a tbvThreadT is actually a reference-counted pointer. Pointers and referencesto tbvThreadT are accesses that the threading package cannot track, and as a resultthe threading package may recycle the resources associated with a thread before youare actually finished with the thread. Of course, the threading package will never recyclethe resources associated with a thread as long as the thread itself is still executing.

To suspend thread A until thread B is complete, call tbvWait(B) from thread A.

To kill thread B, call B.kill() . If a thread is killed while awaiting some event, it is removedfrom the queue. If a thread is killed while it possesses some mutex, that resource becomesavailable to another thread. The kill() call is used primarily by one thread to terminateanother. A thread can kill itself with tbvThreadT::self().kill() , but the usual way fora thread to end its own execution is to return from body() .

A thread can yield the CPU back to the scheduler by calling tbvThreadT::yield() . Whenyou call tbvThreadT::yield() , the current thread yields control back to the threadscheduler, and the scheduler activates another thread in the testbench. The current thread isplaced into the list of ready threads. This may, depending on thread priority and the arbitrationscheme in effect, lead to the immediate reactivation of the current thread.

The scheduler will not reactivate the simulator as long as there are threads in the readyqueue. Thus, a construct like this:

do tbvThreadT::yield() while ( signal != 1u );

is just a fancy infinite loop (unless another thread in the testbench controls signal ). It ismuch better to use something like this:

do tbvWaitCycle(signal) while ( signal != 1u );

To access the priority of a thread, use getPriority() and setPriority() . To accessthe status of a thread, use getStatus() .

June 2000 45 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

The following example shows how a thread can boost its own priority:

tbvThreadT me = tbvThreadT::self();

me.setPriority( me.getPriority() + 1 );

Before calling tbvWait(B) , a thread A that needs to wait on a thread B can test whetherthread B is already done by calling getStatus() as follows:

B.getStatus() == tbvThreadT::DONE.

To navigate a thread’s tree of spawned threads, use getChildren() ,getNumDescendants() , and getParent() . The getChildren() function returns a listof the direct descendants of the current thread. It is a copy of the actual list, and does notchange as threads are created and destroyed. Delete the list when you are finished with it.The getNumDescendants() function returns a count of direct and indirect descendants ofthe current thread. The getParent() function returns the direct ancestor of the currentthread (the thread that spawned the current thread).

June 2000 46 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Synchronizing Threads

The synchronization facilities allow threads to coordinate their activities.

Multiple threads can suspend on any of these facilities. Each of them allows you to control theorder in which these suspended threads are reactivated. There are several predefinedorderings, listed as tbvThreadT::arbModeT in Table 3-1 on page 38. To specify a customordering, specify a comparison function. Use the getArbitration() andsetArbitration() functions to control this order.

To access a list of all threads waiting on a TestBuilder facility, use the getWaiters() methodfor that facility (tbvBarrierT , tbvMutexT , or tbvSemT ), or use the tbvGetWaiters()function for a list of threads waiting on a simulator resource (a signal, event, or specified time).This returns a list of threads, in the order in which they would be reactivated. This is a copyof the actual list. Free the list when you are finished using it.

The default order for all thread lists associated with semaphores and mutexes, is FIFO.Thread lists for barriers are ordered LIFO by default.

This section discusses several simple synchronization classes and functions:

■ tbvBarrierT

■ tbvSemT

■ tbvMutexT

■ tbvWaitCycle()

■ tbvWaitEvent()

■ tbvWait()

■ tbvTimeT

■ tbvEventT

and classes and functions used for more complex control:

■ tbvWaitAllSharedT

■ tbvWaitAllUnsharedT

■ tbvWaitAnyHybridT

■ tbvWaitAnySharedT

■ tbvWaitAnyUnsharedT

June 2000 47 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

■ tbvWatcherT

June 2000 48 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Barriers: tbvBarrierT Class

Barriers are used to synchronize execution between threads.

tbvBarrierT Public Methods

tbvBarrierT Example

Suppose you have five threads, and you do not want any of them to progress beyond a certainpoint until all of them have reached that point.

1. Define a barrier for five threads:

tbvBarrierT b("WAIT",5);

2. Insert a b.wait() call at the appropriate spot in each thread.

The first four threads to reach the b.wait() suspend until the fifth one reaches itsb.wait() . At that point, all threads continue.

Table 3-6 tbvBarrierT Public Methods

Public Method DescriptiontbvBarrierT(const char * name,int threads );

Create a barrier with name name.

tbvBarrierT(int threads ); Create a barrier.const char *getNameP(); Return the name of this barrier.reset(); Set the barrier to its original state so that it can be

used again.void getArbitration(tbvThreadT::arbModeT& mode,tbvThreadT::arbFuncT& func );

Determine the current arbitration criteria for the listof threads that are ready to run. See“tbvThreadT::arbModeT Enum” on page 38.

void setArbitration(tbvThreadT::arbModeT mode,tbvThreadT::arbFuncT func );

Set the ordering for the list of threads that are readyto run. The default is LIFO . See“tbvThreadT::arbModeT Enum” on page 38.

wait() Suspend the calling thread.getWaiters() Return a list of the threads waiting at this barrier in

a tbvListT structure.

June 2000 49 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

If another thread calls b.wait() at this point, it is an error, unless b.reset() has beencalled. It is also an error to call b.reset() before five b.wait() calls have occurred.

By default, the threads are reactivated in LIFO order so the last thread can continue withoutinterruption.

June 2000 50 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Semaphores: tbvSemT Class

Semaphores are often used to control access to a limited shared resource, or to coordinateexecution between threads.

tbvSemT Public Methods

Table 3-7 tbvSemT Public Methods

Public Method DescriptiontbvSemT(const char * name,int value = 0);

Create a semaphore with name name and initialcounter value value .

tbvSemT(); Create a semaphore with the default counter value0.

const char *getNameP(); Return the name of the semaphore.const int getValue(); Return the value of the semaphore’s counter.void post(); Activate one of the threads suspended on this

semaphore. If no threads are suspended on thissemaphore, increment the semaphore’s counter.

void postAll(); Activate all of the threads suspended on thissemaphore.

bool tryWait(); Test whether the semaphore’s counter is positive.void getArbitration(tbvThreadT::arbModeT& mode,tbvThreadT::arbFuncT& func );

Determine the current arbitration criteria for the listof threads that are ready to run. See“tbvThreadT::arbModeT Enum” on page 38.

void setArbitration(tbvThreadT::arbModeT mode,tbvThreadT::arbFuncT func );

Set the ordering for the list of threads that are readyto run. The default is FIFO. See“tbvThreadT::arbModeT Enum” on page 38.

wait() Decrement the semaphore’s counter if the counteris positive. Otherwise, suspend the current thread.

getWaiters() Return a list of the threads suspended on thissemaphore in a tbvListT structure.

June 2000 51 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvSemT Description

The semaphore contains a counter. You can specify an initial value on the constructor. Thedefault initial value of the counter is 0.

Use tbvSemT::wait() to obtain the semaphore. If the semaphore’s internal counter ispositive, tbvSemT::wait() decrements it. Otherwise, tbvSemT::wait() suspends thecurrent thread.

Use tbvSemT::post() to relinquish the semaphore. If there are threads suspended on thissemaphore, use post() to activate one of them. Otherwise, post() increments thesemaphore’s internal counter.

Use postAll() to activate all waiting threads.

The tryWait() method works as if it were coded as follows (except that it is atomic):

if ( semaphore.wait() would suspend thread ) return FALSE;

else { semaphore.wait(); return TRUE; }

To retrieve the value of the semaphore’s internal counter, use getValue() .

June 2000 52 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Mutexes: tbvMutexT Class

Mutexes are usually used to protect the consistency of shared resources. They do this byserializing access to the regions of code that manipulate the shared resources.

tbvMutexT Public Methods

tbvMutexT Description

A mutex starts out unlocked. Call tbvMutexT::lock() at the beginning of a critical regionof code, and call tbvMutexT::unlock() at the end of the critical region.

The tryLock() function works for mutexes the way tryWait() works for semaphores.

Table 3-8 tbvMutexT Public Methods

Public Method DescriptiontbvMutexT(const char * name); Create a mutex with name name.tbvMutexT(); Create a mutex.const char *getNameP(); Return the name of the mutex.bool tryLock(); Test whether the mutex is locked.void unlock(); Unlock the mutex and activate a waiting thread if

one exists. Only the thread that locked the mutex(by calling tbvWait(tbvMutexT&) ) is allowed tounlock it.

void getArbitration(tbvThreadT::arbModeT& mode,tbvThreadT::arbFuncT& func );

Determine the current arbitration criteria for the listof threads that are ready to run. See“tbvThreadT::arbModeT Enum” on page 38.

void setArbitration(tbvThreadT::arbModeT mode,tbvThreadT::arbFuncT func );

Set the ordering for the list of threads that are readyto run. The default is FIFO. See“tbvThreadT::arbModeT Enum” on page 38.

lock() Lock the mutex if it is not already locked. Suspendthe calling thread if the mutex is already locked.

getWaiters() Return a list of the threads locked by this mutex in atbvListT structure.

June 2000 53 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

A thread that calls tbvMutexT::lock() on an unlocked mutex locks the mutex andcontinues executing. A thread that calls tbvMutexT::lock() on a locked mutex suspends.

When the thread that locked the mutex (by calling tbvMutexT::lock() ) unlocks it (viatbvMutexT::unlock() ), a waiting thread is activated and is allowed to lock the mutex. Ifthere are no waiting threads, the mutex is left unlocked. Only the thread that locked a mutexis allowed to unlock it.

It is an error for a thread to call lock() on a mutex twice without unlocking it in between, orcall unlock() on a mutex twice without locking it in between, or call unlock() on a mutexthat it has not locked.

June 2000 54 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Synchronizing with the Simulator

The TestBuilder threading package allows threads to wait on several types of simulatorevents. Unlike mutexes and semaphores, which activate threads one at a time, the facilitiesthat synchronize with the simulator activate all the threads suspended pending an event,when that event occurs.

Wait on Signal Change

Use the tbvWaitCycle() and tbvWaitEvent() functions to suspend until a signalchanges. The signal must be associated with an HDL signal.

The primary difference between the two functions is in exactly when the thread is executed.Also, there can be a difference in the order in which threads are executed if multiple threadsare activated in the same time step.

The tbvWaitCycle() function supports a cycle-based model of design and simulation. ThetbvWaitEvent() function supports event-based simulation better.

Reactivate After Cycle: tbvWaitCycle()

The tbvWaitCycle() function reactivates threads when the simulator issues value-changecallbacks, but it does not execute the activated thread until after changes to the specifiedsignal have propagated through the circuit: after the simulator exhausts its event queue,completes NBAs (non-blocking assignments), and issues a RWSync callback.

Table 3-9 tbvWaitCycle() and tbvWaitEvent() Functions

Function Descriptionvoid tbvWaitCycle(const tbvSignalHdlT& signal ,tbvThreadT::edgeTedge =tbvThreadT::ANYEDGE);

Suspend the current thread until a signal changes.Reactivate thread after value-change callback.Execute activated thread after changes propagate.Specify edge to wait on a specific edge.

void tbvWaitEvent(const tbvSignalHdlT& signal,tbvThreadT::edgeTedge =tbvThreadT::ANYEDGE);

Suspend the current thread until a signal changes.Reactivate and execute thread after value-changecallback. Specify edge to wait on a specific edge.

tbvListT<tbvThreadT>tbvGetWaiters(const tbvSignalHdlT& signal )const;

Return a list of the threads waiting on a particularsignal in a tbvListT structure.

June 2000 55 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

If different events in the same time step activate multiple threads waiting on the same signal,tbvWaitCycle() executes the threads according to the global thread arbitration methodcurrently in effect under tbvThreadT::setArbitration() .

Use tbvWaitCycle() along with tbvThreadT::edgeT to wait on a specific edge.

Use the tbvGetWaiters(tbvSignalHdlT) function to determine which threads arecurrently waiting on a particular signal. This list includes threads that are waiting for particularedges, as well as those that are waiting for any change.

Reactivate Immediately on Value Change: tbvWaitEvent()

The tbvWaitEvent() function executes an activated thread as soon as the simulatorissues the value-change callback. The circuit may be in an inconsistent state, and NBAs (non-blocking assignments) may not have been performed (unless the value change is the resultof an NBA).The thread then runs until it does something to cause the threading package tosuspend it, as described in “Suspending Threads and Allocating CPU Time” on page 71.

If different events in the same time step activate multiple threads waiting on the same signal,tbvWaitEvent() executes the threads in the order in which the simulator issues thecallbacks.

Use tbvWaitEvent() along with tbvThreadT::edgeT to wait on a specific edge.

Use the tbvGetWaiters(tbvSignalHdlT) function to determine which threads arecurrently waiting on a particular signal. This list includes threads that are waiting for particularedges, as well as those that are waiting for any change.

June 2000 56 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Wait on Time

Use the tbvWait( time ) function to suspend for a specified amount of DUV time. In bothtbvWait( time ) and tbvGetWaiters( time ) , time is relative to the current DUV time,not relative to the start of simulation.

Wait on Event

Use the tbvWait( event ) function to suspend until a particular Verilog named event(tbvEventT ) occurs.

Table 3-10 tbvWait(time) Functions

Function Descriptionvoid tbvWait(const tbvTimeT& time );

Suspend the current thread for the specifiedamount of time.

The tbvTimeT type is unsigned long long , sotbvTimeT& time is equivalent toconst unsigned long long& time .

tbvListT<tbvThreadT>tbvGetWaiters(const tbvTimeT& time ) const;

Return a list of the threads waiting until thespecified time in a tbvListT structure.

void tbvWait(int time ); Suspend the current thread for the specifiedamount of time.

inline tbvListT<tbvThreadT>tbvGetWaiters(const int time )const;

Return a list of the threads waiting until thespecified time in a tbvListT structure.

void tbvWait(unsigned time ); Suspend the current thread for the specifiedamount of time.

inline tbvListT<tbvThreadT>tbvGetWaiters(const unsigned time ) const;

Return a list of the threads waiting until thespecified time in a tbvListT structure.

June 2000 57 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvEventT Class

The tbvEventT class gives you access to a Verilog named event. These events are definedin the HDL. Include the event name on the constructor as shown in Table 3-11:

tbvWait(event) Functions

Waiting on Multiple Items

This facility provides a way to create collections of resources (such as semaphores, mutexes,or signals), and a way to wait until all resources in the collection become available, or untilany single resource in the collection becomes available. These collections of resources canbe nested.

Types of Resources

Resources are shared or unshared. When a shared resource triggers, all threads waiting onit are activated. When an unshared resource triggers, a single thread is activated.

Table 3-11 tbvEventT Public Methods

Public Method DescriptiontbvEventT(const char * name); Create a tbvEventT with name name, which is

the name of the Verilog event.const char *getNameP(); Return the name of the event.

Table 3-12 tbvWait(event) Functions

Function Descriptionvoid tbvWait(tbvEventT& event ); Suspend the current thread until the specified event

occurs.

The tbvEventT type is described below.tbvListT<tbvThreadT>tbvGetWaiters(const tbvEventT& event ) const;

Return a list of the threads waiting until thespecified Verilog event in a tbvListT structure.

June 2000 58 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Table 3-13 lists all resources that a thread can wait on and shows whether each resource isshared (all waiting threads are activated) or unshared (a single waiting thread is activated):

Unshared resources must be released before another waiting thread can be activated.Table 3-14 lists the operations that release the various unshared resource types:

Resource Sets

Resources are aggregated into sets that support different wait functionality:

■ tbvWaitAllSharedT

■ tbvWaitAnySharedT

■ tbvWaitAllUnsharedT

■ tbvWaitAnyUnsharedT

■ tbvWaitAnyHybridT

A tbvWaitAllSharedT or a tbvWaitAnySharedT instance can include:

Table 3-13 Resource Types to Wait On

Resource Type

event shared

signal (any/neg/posedge) shared

Verilog named event shared

simulation time shared

semaphore unshared

mutex unshared

thread termination shared

Table 3-14 Operations to Release Unshared Resources

Unshared Resource Release Operations

semaphore post() or postAll()

mutex unlock()

June 2000 59 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

■ shared resources

■ tbvWaitAllSharedT instances

■ tbvWaitAnySharedT instances

A tbvWaitAllUnsharedT or a tbvWaitAnyUnsharedT instance can include:

■ unshared resources

■ tbvWaitAllUnsharedT instances

■ tbvWaitAnyUnsharedT instances

A tbvWaitAnyHybridT instance can include:

■ unshared resources

■ tbvWaitAllUnsharedT instances

■ tbvWaitAnyUnsharedT instances

■ one shared resource

A thread that waits on a tbvWaitAllSharedT or tbvWaitAllUnsharedT does not regaincontrol until it has possession of every resource, and has satisfied every resource set, in theset.

A thread that waits on a tbvWaitAnySharedT , tbvWaitAnyUnsharedT , ortbvWaitAnyHybridT regains control when it has possession of some resource, or hassatisfied some resource set, in the set.

waitCycle() and waitEvent()

Each of the resource sets described above supports two wait operations: waitCycle() andwaitEvent() .

■ If a value change on a signal is the final resource required to satisfy a waitCycle() ,the thread is reactivated in the same manner as a thread that has just done awaitCycle() on the signal.

■ If a value change on a signal is the final resource required to satisfy a waitEvent() ,the thread is reactivated in the same manner as a thread that has just done awaitEvent() on the signal.

■ If the final resource was anything other than a signal, then waitCycle() andwaitEvent() behave identically.

June 2000 60 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

A thread that performs one of these wait operations on a tbvWaitAllUnsharedT ,tbvWaitAnyUnsharedT , or tbvWaitAnyHybridT must eventually perform a release()on the same set. This operation releases any unshared resources the thread may haveacquired as a result of the wait operation.

See “Wait on Signal Change” on page 55 for information about tbvWaitCycle() andtbvWaitEvent() .

June 2000 61 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvWaitAllSharedT Class

tbvWaitAllSharedT Methods

Table 3-15 tbvWaitAllSharedT Methods

Public Method DescriptiontbvWaitAllSharedT(); Create an unnamed tbvWaitAllSharedT

resource set.tbvWaitAllSharedT(const char * nameP);

Create a tbvWaitAllSharedT resource setwith name nameP.

void add(tbvEventT& event ); Add a Verilog named event to this resource set.void add(const tbvSignalT& signal ,tbvThreadT:: edge =tbvThreadT::ANYEDGE);

Add a signal change to this resource set.

void add(tbvThreadT& thread ); Add a thread termination to this resource set.void add(tbvTimeT time ); Add an elapsed time entry to this resource set.void add(tbvWaitAllSharedT& wait ); Add a tbvWaitAllSharedT resource set to the

current resource set.void add(tbvWaitAnySharedT& wait ); Add a tbvWaitAnySharedT resource set to the

current resource set.const char *getNameP() const; Get the name of the current resource set.void waitCycle() Suspend until all resources in this set have

triggered. Any signals in the set are awaited usingwaitCycle() .

void waitEvent() Suspend until all resources in this set havetriggered. Any signals in the set are awaited usingwaitEvent() .

June 2000 62 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvWaitAllUnsharedT Class

tbvWaitAllUnsharedT Methods

tbvWaitAnyHybridT Class

tbvWaitAnyHybridT Methods

Table 3-16 tbvWaitAllUnsharedT Methods

Public Method DescriptiontbvWaitAllUnsharedT(); Create an unnamed tbvWaitAllUnsharedT

resource set.tbvWaitAllUnsharedT(const char * nameP);

Create a tbvWaitAllUnsharedT resource setwith name nameP.

void add(tbvMutexT& mutex ); Add a mutex to this resource set.void add(tbvSemT& sem); Add a semaphore to this resource set.void add(tbvWaitAllUnsharedT& wait );

Add a tbvWaitAllUnsharedT resource set tothe current resource set.

void add(tbvWaitAnyUnsharedT& wait );

Add a tbvWaitAnyUnsharedT resource set tothe current resource set.

const char *getNameP() const; Get the name of the current resource set.void release(); Release acquired resources in this resource set.void waitCycle() Suspend until all resources in this set are

available.void waitEvent() Same effect as:

tbvWaitAllUnsharedT::waitCycle()

Table 3-17 tbvWaitAnyHybridT Methods

Public Method DescriptiontbvWaitAnyHybridT(); Create an unnamed tbvWaitAnyHybridT

resource set.

June 2000 63 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvWaitAnyHybridT(const char * nameP);

Create a tbvWaitAnyHybridT resource setwith name nameP.

void add(tbvEventT& event ); Add a Verilog named event to this resource set.void add(tbvMutexT& mutex ); Add a mutex to this resource set.void add(tbvSemT& sem); Add a semaphore to this resource set.void add(const tbvSignalT& signal ,tbvThreadT:: edge =tbvThreadT::ANYEDGE);

Add a signal change to this resource set.

void add(tbvThreadT& thread ); Add a thread termination to this resource set.void add(tbvTimeT time ); Add an elapsed time entry to this resource set.void add(tbvWaitAllUnsharedT& wait );

Add a tbvWaitAllUnsharedT resource set tothe current resource set.

void add(tbvWaitAnyUnsharedT& wait );

Add a tbvWaitAnyUnsharedT resource set tothe current resource set.

const char *getNameP() const; Get the name of the current resource set.void release(); Release acquired resources in this resource set.void waitCycle() Suspend until all resources in this set have

triggered. Any signals in the set are awaited usingwaitCycle() .

void waitEvent() Suspend until all resources in this set havetriggered. Any signals in the set are awaited usingwaitEvent() .

int which() const; Indicate which of the resources in the set actuallysatisfied the most-recent wait.

Table 3-17 tbvWaitAnyHybridT Methods, continued

Public Method Description

June 2000 64 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvWaitAnySharedT Class

tbvWaitAnySharedT Methods

Table 3-18 tbvWaitAnySharedT Methods

Public Method DescriptiontbvWaitAnySharedT(); Create an unnamed tbvWaitAnySharedT

resource set.tbvWaitAnySharedT(const char * nameP);

Create a tbvWaitAnySharedT resource setwith name nameP.

void add(tbvEventT& event ); Add a Verilog named event to this resource set.void add(const tbvSignalT& signal ,tbvThreadT:: edge =tbvThreadT::ANYEDGE);

Add a signal change to this resource set.

void add(tbvThreadT& thread); Add a thread termination to this resource set.void add(tbvTimeT time ); Add an elapsed time entry to this resource set.void add(tbvWaitAllSharedT& wait ); Add a tbvWaitAllSharedT resource set to the

current resource set.void add(tbvWaitAnySharedT& wait ); Add a tbvWaitAnySharedT resource set to the

current resource set.const char *getNameP() const; Get the name of the current resource set.void waitCycle() Suspend until all resources in this set have

triggered. Any signals in the set are awaited usingwaitCycle() .

void waitEvent() Suspend until all resources in this set havetriggered. Any signals in the set are awaited usingwaitEvent() .

int which() const; Indicate which of the resources in the set actuallysatisfied the most-recent wait.

June 2000 65 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvWaitAnyUnsharedT Class

tbvWaitAnyUnsharedT Methods

The which() method returns the number corresponding to the resource that the most recentwait operation (on this resource set) actually acquired, counting from 0 according to the orderin which they were added to the set with the add() method. It is an error to call which()prior to the first wait.

You can use this API to build complex nested resource sets.

A wait on a resource set results in waits on any resource sets it contains.

Table 3-19 tbvWaitAnyUnsharedT Methods

Public Method DescriptiontbvWaitAnyUnsharedT(); Create an unnamed tbvWaitAnyUnsharedT

resource set.tbvWaitAnyUnsharedT(const char * nameP);

Create a tbvWaitAnyUnsharedT resource setwith name nameP.

void add(tbvMutexT& mutex ); Add a mutex to this resource set.void add(tbvSemT& sem); Add a semaphore to this resource set.void add(tbvWaitAllUnsharedT& wait );

Add a tbvWaitAllUnsharedT resource set tothe current resource set.

void add(tbvWaitAnyUnsharedT& wait );

Add a tbvWaitAnyUnsharedT resource set tothe current resource set.

const char *getNameP() const; Get the name of the current resource set.void release(); Release acquired resources in this resource set.void waitCycle() Suspend until all resources in this set have

triggered. Any signals in the set are awaited usingwaitCycle() .

void waitEvent() Suspend until all resources in this set havetriggered. Any signals in the set are awaited usingwaitEvent() .

int which() const; Indicate which of the resources in the set actuallysatisfied the most-recent wait.

June 2000 66 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

How It Works

A simple wait occurs when a thread executes a wait operation (such as sem.wait() ,mutex.lock() , or tbvWaitEvent(signal) ) on some resource (not on a resource set).

A complex wait occurs when a thread executes a wait operation (such astbvWaitCycle() or tbvWaitEvent() , or tbvWaitAllShartedT::waitCycle() ) ona resource set.

Complex waits return as quickly as possible, having as little impact as possible on simplewaits on the same resources.

Complex waits use the queues for the underlying resources, and compete with other waits foreach resource according to the resource’s current arbitration mode.

The relative order of simple waits on a resource is not affected by complex waits involving thatresource. A simple wait on a resource may be satisfied ahead of a complex wait on the sameresource, event when the current arbitration scheme for that resource may dictate theopposite.

Examples

Wait for Signal with TimeouttbvWaitAnySharedT W;

W.add(enable,tbvThreadT::POSEDGE);

W.add(1000);

W.waitCycle();

if ( W.which() == 0 ) { edge occurred }

else { specified time elapsed }

Wait for one of three semaphorestbvWaitAnyUnsharedT W;

W.add(sem1);

W.add(sem2);

W.add(sem3);

W.waitCycle();

int result = W.which();

if ( result == 0 ) { use sem1 }

else if ( result == 1 ) { use sem2 }

else { use sem3 }

June 2000 67 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

W.release(); // does a post() on acquired semaphore

Wait for two semaphores with timeouttbvWaitAllUnsharedT W1;

W1.add(sem1);

W1.add(sem2);

tbvWaitAnyHybridT W2;

W2.add(W1);

W2.add(1000);

W2.waitCycle();

if ( W2.which() == 0 ) { use sem1 and sem2 }

else { timeout occurred }

W2.release(); // does sem1.post() sem2.post() if needed

Even if this W2.waitCycle() is at the head of the waiting list for sem1, other threads mayget possession of sem1 until the waitCycle() is also at the head of the list for sem2.

Wait for sem1 && ( sem2 || sem3 )tbvWaitAnyUnsharedT W1;

W1.add(sem2);

W1.add(sem3);

tbvWaitAllUnsharedT W2;

W2.add(sem1);

W2.add(W1);

W2.waitCycle();

if ( W1.which() == 0 ) { use sem1 and sem2 }

else { use sem1 and sem3 }

W2.release();

Even if this W2.waitCycle() is at the head of the waiting list for sem2 or sem3, otherthreads may get possession of it until the waitCycle() is also at the head of the list forsem1.

Wait for a complex condition involving an edge

The following example shows how to wait for posedge(clk) && sig1 == 5 :

do tbvWaitCycle(clk,tbvThreadT::POSEDGE)

while ( tbv4StateNotEqual(sig1,5) );

June 2000 68 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Wait for a complex condition involving levels only

The following example shows how to wait for ( sig1 = = 5 ) && ( sig2 == 7 ) :

tbvWaitAnySharedT W1;

W1.add(sig1);

W1.add(sig2);

while (

tbv4StateNotEqual(sig1,5) || tbv4StateNotEqual(sig2,7)

)

{ W1.waitCycle(); }

Minimizing the Number of Active Threads

The threading facility is most efficient if the total number of active threads is minimized (tensrather than thousands). Since it reuses threads, the total number of spawned threads is muchless important than the number active at any single time.

This section discusses a couple of facilities that make it easier to keep the number of activethreads low.

Suspending on Thread Count

Often a test writer knows that all but a small number of spawned threads will be suspended,and the test writer can estimate an upper bound on the number of active threads needed tosaturate the device. In these cases, the test writer can use the following functions (staticmember functions in the tbvThreadT class) to suspend the current thread until some countof not-yet-terminated threads drops to or below a threshold:

static void tbvThreadT:: waitAllThreads (int threshold );

static void tbvThreadT:: waitChildren (int threshold );

static void tbvThreadT:: waitDescendants (int threshold );

Delayed Spawning of Threads

In one typical model, you spawn many pairs of threads. In each pair, one thread initiates atransaction on the DUV and the other waits for some expected result. In most cases, the firstthing a thread does is to suspend pending some event. Often, when the thread awakens itloops on the wait() until some additional conditions are met. It is much more efficient todelay spawning each thread until the conditions it needs to wait for are satisfied. The facilitiesdescribed in this section make it easier to delay spawning a thread until conditions are met.

June 2000 69 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

This efficiency comes at a cost: Tests that use these facilities exhibit somewhat less localityof test intent.

tbvWatcherT Class

tbvWatcherT::Type Enum

The tbvWatcherT::Type enumeration controls the execution of the list of handler functionsfor a watched value.

The constructor identifies the signal that the watcher looks at. Whenever the signal valuechanges, the watcher looks for a function to handle the new value. To register a function tohandle a particular value, use the register() member function.

You can register multiple handlers for a value. The watcher calls the functions registered forthe value, in the order they were registered, and examines the status (return value). If(tbvWatcherT::MATCH & status) is nonzero, the watcher stops traversing the list. If(tbvWatcherT::REMOVE & status) is nonzero, the watcher deregisters the function. Ifno functions were registered for the new value, or if none of them reportstbvWatcherT::MATCH , the watcher reports an error.

This setup allows you to check additional conditions within the registered handler and decidewhether to accept the current wakeup or wait for another one. The watcher does not spawn

Table 3-20 tbvWatcherT Public Methods

Public Method DescriptiontbvWatcherT(const char * name,tbvSignalT& signal , void * data ,void * args );const char *getNameP();

void register(void * value ,tbvHandler handler , void * data ,void * args );

Table 3-21 tbvWatcherT::Type Enum Members

Member Description

MATCH If this bit is set, stop traversing the list of registered handlerfunctions.

REMOVE If this bit is set, deregister the handler function.

June 2000 70 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

a new thread for the handler, but the handler can spawn a thread itself. The handler must notwait, directly or indirectly, on any simulator event.

The signal must be attached to an HDL signal.

You can determine which values have functions registered, and you can traverse the list ofregistered functions. This helps you determine, at the end of simulation, whether or not allexpected events occurred.

Suspending Threads and Allocating CPU Time

The currently-executing thread retains the CPU for as long as possible. The following actions(and no others) cause the current thread to lose the CPU:

■ Calling tbvThreadT::kill() on the current thread.

■ Calling tbvWait() on a thread that has not yet terminated.

■ Calling tbvThreadT::yield() . However, the current thread goes into the ready listbefore arbitration, so the scheduling algorithm may choose to reactivate it immediately.

■ Calling wait() on a semaphore or mutex that is not currently available.

■ Calling wait() on a barrier, unless this is the last thread in the synching group.

■ Calling tbvWait() on events or time, or calling tbvWaitCycle() ortbvWaitEvent() on signals. None of these can occur until the simulator regainscontrol.

■ Calling waitCycle() or waitEvent() on a tbvWaitAllSharedT ,tbvWaitAllUnsharedT , tbvWaitAnyHybridT , tbvWaitAnySharedT , ortbvWaitAnyUnsharedT , unless the complex wait can be satisfied immediately.

■ Calling tbvThreadT::waitAllThreads() , unless the number of non-terminatedthreads is already at or below the threshold.

■ Calling tbvThreadT::waitChildren() , unless the number of non-terminatedchildren is already at or below the threshold.

The simulator gains control when there are no threads ready to run. When a simulator event(except for a callback resulting from a tbvWaitEvent() ) activates a thread, the simulatorloses the CPU as soon as it is finished processing events for the current time slice. When acallback for a tbvWaitEvent() activates one or more threads, the simulator loses the CPUimmediately, and each activated thread executes until it loses the CPU (for one of the reasonslisted above).

June 2000 71 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

Even on a multi-CPU machine, the threading package ensures that only one thread is activeat a time.

Type-Safe Spawning

TestBuilder includes a set of templates for spawning with compile-time type checking, asshown in Table 3-22 below.

Without these templates, traditional C threading packages allow you to spawn functions of thetype:

void (*function)(void *);

into a separate thread of execution. TestBuilder provides the same capability as:

tbvThreadT::spawn(void (*function)(void *), void *)

However, the use of void* requires casting in the function and can lead to subtle errors ifyou inadvertently use arguments of inappropriate type.

For example, in order to spawn the following function:

void delayedHelloWorld(int wait) {

tbvWait(wait);

tbvOut << "hello world !" << endl;

}

you must create a wrapper to use a traditional C threading package:

void wrapper1(void * a) {

int * i = (int *) a;

delayedHelloWorld(*i);

}

and you spawn this wrapper function instead of the actual function:

int i = 3;

tbvThreadT::spawn(wrapper1,&i);

This arrangement can cause subtle problems if you are not careful. For example:

double i = 3;

tbvThreadT::spawn(wrapper1,&i);

Although an inappropriate argument is provided, the compiler will not detect any error in theabove code.

June 2000 72 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

The set of templates in listed in Table 3-22 is designed to simplify the spawning process, andto avoid casting. For example, using this library, you can spawn the functiondelayedHelloWorld() as:

tbvSpawnOneArgFunctionT<int>::spawn(delayedHelloWorld,3);

You do not need to write a wrapper; and you do not need to put the argument in the variable i .

In a similar way, you can easily spawn a method of a C++ object, whereas it would be verytedious to do so without these templates.

Templates for Spawning with Compile-time Type Checking

Table 3-22 lists the TestBuilder set of templates for spawning with compile-time typechecking:

Examples of Spawning with Compile-Time Type Checking

The following example shows the three kinds of C functions and three kinds of C++ methodslisted in Table 3-22 above, and then shows how to spawn each of these functions andmethods using the TestBuilder templates listed in that table.

// three kinds of functions

void helloWorld1() { ... }

void helloWorld2(int i) { ... }

void helloWorld3(int i, int j) { ... }

Table 3-22 tbvSpawn*T Templates

Library Element Descriptionclass tbvSpawnNoArgFunctionT Spawn a function or a static method with no

arguments.template tbvSpawnOneArgFunctionT Spawn a function or a static method with one

argument.template tbvSpawnTwoArgFunctionT Spawn a function or a static method with two

arguments.template tbvSpawnNoArgMethodT Spawn a non-static method with no arguments.template tbvSpawnOneArgMethodT Spawn a non-static method with one argument.template tbvSpawnTwoArgMethodT Spawn a non-static method with two arguments.

June 2000 73 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

// three kinds of methods

class myClassT {

public:

...

void method1() { ... }

void method2(int i) { ... }

void method3(int i, int j) { ... }

};

// Examples of spawning different kinds of functions and methods:

void test() {

// Spawn a function with no arguments.

tbvSpawnNoArgFunctionT::spawn(helloWorld1);

// Spawn a function with one argument.

tbvSpawnOneArgFunctionT<int>::spawn(helloWorld2,1);

// Spawn a function with two arguments.

tbvSpawnTwoArgFunctionT<int,int>::spawn(helloWorld3,1,2);

// a C++ object

myClassT c(...);

// Spawn a method of "c" with no arguments.

tbvSpawnNoArgMethodT<myClassT>::spawn(&c,&myClassT::method1);

// Spawn a method of "c" with one argument.

tbvSpawnOneArgMethodT<myClassT,int>::spawn(&c,&myClassT::method2,5);

// Spawn a method of "c" with two arguments.

tbvSpawnTwoArgMethodT<myClassT,int,int>::spawn(&c,&myClassT::method3,5,2);

}

June 2000 74 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvSpawnNoArgFunctionT Member Types and Public Methods

tbvSpawnOneArgFunctionT Parameters, Member Types, and Public Methods

Table 3-23 tbvSpawnNoArgFunctionT Member Types

Member Type Descriptionvoid (*functionT)(); Type of the function to be spawned.

Table 3-24 tbvSpawnNoArgFunctionT Public Methods

Public Method Descriptionstatic void spawn(functionT funcP )

Spawn the function funcP in a separate thread ofexecution.

Table 3-25 tbvSpawnOneArgFunctionT Template Parameters

Template Parameter Descriptionclass argumentT Type of the argument of the function to be spawned.

Table 3-26 tbvSpawnOneArgFunctionT Member Types

Member Type Descriptionvoid (*functionT)(argumentT arg );

Type of the function to be spawned.

Table 3-27 tbvSpawnOneArgFunctionT Public Methods

Static Method Descriptionstatic void spawn(functionT funcP , argumentT arg )

Spawn the function funcP with argument arg in aseparate thread of execution.

June 2000 75 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvSpawnTwoArgFunctionT Parameters, Member Types, and Public Methods

tbvSpawnNoArgMethodT Parameters, Member Types, and Public Methods

Table 3-28 tbvSpawnTwoArgFunctionT Template Parameters

Template Parameter Descriptionclass argument1T Type of the first argument of the function to be

spawned.class argument2T Type of the second argument of the function to be

spawned.

Table 3-29 tbvSpawnTwoArgFunctionT Member Types

Member Type Descriptionvoid (*functionT)(argument1T arg1 ,argument2T arg2 );

Type of the function to be spawned.

Table 3-30 tbvSpawnTwoArgFunctionT Public Methods

Static Method Descriptionstatic void spawn(functionT funcP ,argument1T arg1 ,argument2T arg2 )

Spawn the function funcP with arguments arg1and arg2 in a separate thread of execution.

Table 3-31 tbvSpawnNoArgMethodT Template Parameters

Template Parameter Descriptionclass objectT Type of the object from which a method is to be

spawned.

June 2000 76 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvSpawnOneArgMethodT Parameters, Member Types, and Public Methods

Table 3-32 tbvSpawnNoArgMethodT Member Types

Member Type Descriptionvoid (*objectT::methodT)(); Type of the method to be spawned.

Table 3-33 tbvSpawnNoArgMethodT Public Methods

Static Method Descriptionstatic void spawn(objectT * obj ,methodT methodP )

Spawn the method methodP for object obj in aseparate thread of execution.

Table 3-34 tbvSpawnOneArgMethodT Template Parameters

Template Parameter Descriptionclass objectT Type of the object from which a method is to be

spawned.class argumentT Type of the argument of the method to be spawned.

Table 3-35 tbvSpawnOneArgMethodT Member Types

Member Type Descriptionvoid (*objectT::methodT)(argumentT arg );

Type of the method to be spawned.

Table 3-36 tbvSpawnOneArgMethodT Public Methods

Static Method Descriptionstatic void spawn(objectT * obj ,methodT methodP , argumentT arg )

Spawn the method methodP with argument arg forobject obj in a separate thread of execution.

June 2000 77 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualConcurrency

tbvSpawnTwoArgMethodT Parameters, Member Types, and Public Methods

Table 3-37 tbvSpawnTwoArgMethodT Template Parameters

Template Parameter Descriptionclass objectT Type of the object from which a method is to be

spawned.class argument1T Type of the first argument of the method to be

spawned.class argument2T Type of the second argument of the method to be

spawned.

Table 3-38 tbvSpawnTwoArgMethodT Member Types

Member Type Descriptionvoid (*objectT::methodT)(argument1T arg1 ,argument2T arg2 );

Type of the method to be spawned.

Table 3-39 tbvSpawnTwoArgMethodT Public Methods

Static Method Descriptionstatic void spawn(objectT * obj ,methodT methodP ,argument1T arg1 ,argument2T arg2 )

Spawn the method methodP with arguments ar1gand arg2 for object obj in a separate thread ofexecution.

June 2000 78 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

4TVMs, Tasks, and Fibers

This chapter describes the TestBuilder TVM, Task, and Fiber base classes and other relatedclasses:

■ tbvTvmT

■ tbvTaskT

■ tbvTaskTypeSafeT

■ tbvProfileT

■ tbvTaskGroupT

■ tbvTaskContextT

■ tbvFiberT

“Spawning TVM Tasks as Threads” on page 42 contains an example that shows how youshould write your derived TVM and Task classes.

June 2000 79 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

Class Diagram

tbvFiberTtbvTvmT tbvTaskT

UserTvmT UserTaskT

11 n

tbvSignalHdlT

tbvProfileT

tbvProfileArgT

n

1

tbvTaskContextT

1

June 2000 80 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTvmT Class

This is the TVM base class from which you derive your TVM classes.

Table 4-1 tbvTvmT Public Methods

Public Method DescriptiontbvTvmT() Create a TestBuilder TVM.tbvTvmT(char * tvmDefName = NULL,

char * tvmFullName = NULL,

char * tvmInstanceName = NULL,

tbvTvmDestroyFPT

usersDestroyFunctionP = NULL,

tbvTvmFullInterfaceHdlNameAssocArrayT

* tvmFullInterfaceHdlNameAssocArrayP

= NULL)

Create a TestBuilder TVM.

Use this form only to declare a TVM directly inyour TestBuilder C++ code. If you declare theTVM in $tbv_tvm_connect() in yourVerilog code, you do not need to supply thesearguments in the constructor.

The tvmDefName argument (defined name)corresponds to the first argument in a$tbv_tvm_connect() call,tvmInstanceName corresponds to thesecond argument in a$tbv_tvm_connect() call, tvmFullNameis the instance name concatenated with thehierarchical path in Verilog where the$tbv_tvm_connect() call would be made.

For example:

tbvTvmT mytvm ("tvmType1","Top.hier_1.hier_2.tvmInstance1","tvmInstance1");

virtual ~tbvTvmT() The destructor for a TVM. You should delete aTVM object only in the destroy function foryour TVM. See “Register a TVM” in theTestBuilder User Guide.

static void registerTvm

(const char * tvmName,

tbvTvmCreateFPT createFunction ,

tbvTvmDestroyFPT

destroyFunction =NULL

Dynamically register a TVM. Compare this tousing the tbvTvmTypes table to staticallyregister a TVM.

The tvmName is the name of this TVM,createFunction is a pointer to the createfunction for this TVM, anddestroyFunction is a pointer to thedestroy function for this TVM.

June 2000 81 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTvmDestroyFPTgetUsersDestroyFunctionP() const

Return the Destroy function for this TVM. Thisfunction was registered in the tbvTvmTypestable for this TVM.

const char *getFullNameP() const The full hierarchical name of a TVM.const char *getDefNameP() const The definition name of a TVM.const char *getInstanceNameP() const The instance name of a TVM.const char *getFullInterfaceHdlNameP(const char * formalName ) const

The full hierarchical path name of the HDLsignal or event that the specifiedformalName is mapped to in your$tbv_tvm_connect() call. Return NULL ifTestBuilder cannot find the signal.

void addTask(tbvTaskT * taskP ) Add a task to a TVM. This is normally done inthe tbvTaskT base constructor.

void removeTask(tbvTaskT * taskP ) Remove a task from a TVM. This is called inthe destructor of the tbvTaskT .

const tbvTaskListT &getTaskList()const

List of all Tasks in this TVM.

tbvTaskT *getTaskByNameP(const char * taskNameP ,bool giveWarning = TRUE)

Return a Task given its name, in the list oftasks in this TVM. If giveWarning is TRUE,then give a message if the task cannot befound, and return NULL.

static const tbvTvmListT&getTvmListByDefName(const char * defNameP)

Return a list of TVMs given a definition name.

static tbvTvmT &getTvmByInstanceName(const char * instanceNameP )

Return a TVM given its instance name. If notfound, then give a warning and return NULL.

static tbvTvmT *getTvmByFullNameP(const char * fullNameP )

Return a TVM given its full name. If not found,then give a warning and return NULL.

tbvFiberT *newFiberP() Return a Fiber that is created for this TVM.The Fiber object semaphore and threadDtHmembers are created by this method. ThisFiber object can also later be obtained by thegetFiberP() method.

Table 4-1 tbvTvmT Public Methods, continued

Public Method Description

June 2000 82 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTaskT Class

This is the Task base class from which you derive your Task classes.

void setFiber(tbvFiberT * fiberP ) Set a Fiber for this TVM. This Fiber object canalso later be obtained by the getFiberP()method.

tbvFiberT *getFiberP() Return a Fiber that was previously created orset.

static tbvUInt64T getSimTime() The current HDL simulation time.static dtObjectHandle getInstanceDtH() Return the DTAPI instance handle that is

currently in use. You can then use this handlein your DTAPI calls. See the DTAPIReference Manual for more information onDTAPI (Database Transaction API).

static bool transRecording() Return TRUE if DTAPI transaction recording iscurrently enabled, FALSE otherwise.

dtObjectHandle getModuleDtH() const Return the DTAPI module instance handle forthis TVM.

void setModuleDtH(dtObjectHandle _moduleDtH)

This is included for documentationcompleteness. You should not need to use thismethod.

Table 4-2 tbvTaskT Public and Protected Methods

Public Method DescriptiontbvTaskT() The constructor for the Task base class, with no

argument. You must call setName() and, ifnecessary, also setParentTask() to fullydescribe this Task.

tbvTaskT(tbvTvmT * parentTvmP ,const char * taskNameP )

Constructor where you give the parent TVM andthe task name.

Table 4-1 tbvTvmT Public Methods, continued

Public Method Description

June 2000 83 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTaskT(tbvTaskT * parentTaskP ,const char * taskNameP )

Constructor where you give the parent Task andthe task name.

~tbvTaskT() It is not a good idea to delete a task.void run(tbvTaskContextT * ContextP ) Do a blocking invocation of the task. See

Chapter 3, “Concurrency,” for more informationabout blocking and non-blocking tasks. Whenthe ContextP has a tbvFiberT , thenTestBuilder first waits on the fiber’s semaphore,and then begins a new DTAPI transaction beforecalling the task’s body method. After the bodyreturns, TestBuilder ends the transaction andposts the semaphore.

tbvThreadT spawn(tbvTaskContextT * ContextP )

Do a non-blocking invocation of the task, similarto run above. See Chapter 3, “Concurrency.”Return the tbvThreadT that was spawned.

tbvThreadT spawn(const char * nameP,tbvTaskContextT * ContextP );

Similar to above but allows you to name threads.

void setName(const char * taskNameP ) Set the name of the task. A copy of the name ismade.

const char *getNameP() const The name of this task.void setParentTvm(tbvTvmT * tvmP ) Set the parent TVM of this task.tbvTvmT *getParentTvmP() const The parent TVM of this task.void setParentTask(tbvTaskT * taskP ) Set the parent Task of this task, for nested

tasks.tbvTaskT *getParentTaskP() const The parent task, if nested.void setProfile(tbvProfileT * _profileP )

Set the profile for this task. If this is not explicitlyset, then TestBuilder uses the profile in the task.

tbvProfileT *getProfileP() const The profile for this task.

Table 4-2 tbvTaskT Public and Protected Methods, continued

Public Method Description

June 2000 84 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTaskTypeSafeT Class: Type-Safe Task Invocation

To avoid subtle errors due to explicit type casting, you may want to use tbvTaskTypeSafeTin place of tbvTaskT . In the tbvTaskTypeSafeT template, use the actual type for the taskcontext as the template. For example, a task that uses myTaskContextT as the argumentto the body() , run() , and spawn() can be specified as follows:

class myTaskContextT : public tbvTaskContextT {

public:

void setInitialFiber(tbvFiberT * fiberP )

Set the fiber that a tbvTaskContextT objectwill run on for this task.

The fiberP argument will always be the initialfiber that a tbvTaskContextT object will runon for this task. The initial fiber in thetbvTaskContextT object will be ignored. CallsetInitialFiber(NULL) so that the initialfiber in a tbvTaskContextT object will beused.

tbvFiberT *getInitialFiberP() const Return the initial fiber for thistbvTaskContextT object.

const tbvTaskListT &getTaskList()const

Return the list of all child tasks in this task.

tbvTaskT *getTaskByNameP(const char * taskNameP )

Return a specific child task, by name.

dtObjectHandlegetDtTransTypeHandleByFiberP(tbvFiberT * fiberP ,tbvTaskContextT * ContextP )

The DTAPI transaction type handle for this taskrunning on the Fiber.

tbvDtObjectHandleByNameAssocArrayT*getTransTypeArrayByFiberP(const tbvFiberT * fiberP ) const

Return an associative array of DTAPItransaction type handles.

void setIsHdlTask(bool _isHdlTask );bool getIsHdlTask() const;

True if the task is an HDL task.

void setAlwaysCheckConstraints(bool checkConstraints = TRUE);bool getAlwaysCheckConstraints();

If TRUE, then check all arguments againstconstraints in the profile.

Protected Method Descriptionvirtual void body(void * ContextP = 0)

The user-written body that gets called when thistask is invoked.

Table 4-2 tbvTaskT Public and Protected Methods, continued

Public Method Description

June 2000 85 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

int a;

};

class myTaskTypeSafeT : public tbvTaskTypeSafeT<myTaskContextT> {

public:

virtual void body(myTaskContextT * arg) {

tbvOut << "field 'a' of the context: " << arg->a << endl;

}

};

tbvTaskTypeSafeT Template Parameters

tbvTaskTypeSafeT Public Methods

The tbvTaskTypeSafeT methods are the same as the tbvTaskT methods, except thatbody() , run() , and spawn() are hidden by the new type-safe methods shown in table 2.

Table 4-3 tbvTaskTypeSafeT Template Parameters

Template Parameter DescriptioncontextTypeT The type of the argument to body() , run() , and spawn() .

This type must be a derived class of tbvTaskContextT ;otherwise, a compile-time error results.

Table 4-4 tbvTaskTypeSafeT Public Methods

Public Method Descriptionvoid body(contextTypeT * contextP = NULL)=0;

A pure virtual method to be implemented by thederived class. Use this method in place of:

tbvTaskT::body(tbvTaskContextT*)

There is no need to use explicit casting in thebody of this method.

void run(contextTypeT * contextP = NULL);

Hides and replaces:

tbvTaskT::run(tbvTaskContextT *)

Adds compile-time type checking to the interface.tbvThreadT spawn(contextTypeT * contextP = NULL);

Hides and replaces:

tbvTaskT::spawnn(tbvTaskContextT *)

Adds compile-time type checking to the interface.

June 2000 86 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvProfileT Class

The tbvTaskT base class contains a tbvProfileT member. This is the TVM Task Profileclass, which describes the task context object of a Task.

The tbvProfileT::argTypeT enumeration specifies the various argument types in aprofile:

tbvThreadT spawn(const char * nameP,contextTypeT * contextP );

Hides and replaces:

tbvTaskT::spawn(const char *,tbvTaskContextT *)

Adds compile-time type checking to the interface.

Table 4-5 tbvProfileT::argTypeT Members

Member Description

TBV_SIGNAL The argument is a tbvSignalT object.

TBV_SIGNAL_P The argument is a pointer to a tbvSignalT .

TBV_SIGNAL_HDL The argument is a tbvSignalHdlT object.

TBV_SIGNAL_HDL_P The argument is a pointer to a tbvSignalHdlT .

TBV_SIGNAL_HDL_2_STATE The argument is a tbvSignalHdl2StateT .

TBV_SIGNAL_HDL_2_STATE_P The argument is a pointer to atbvSignalHdl2StateT .

TBV_SIGNAL_4_STATE The argument is a tbvSignal4StateT .

TBV_SIGNAL_4_STATE_P The argument is a pointer to a tbvSignal4StateT .

INTEGER_32 The argument is a 32-bit integer.

STRING_P The argument is a pointer to a string.

REAL_64 The argument is a 64-bit real.

USER_DEFINED The argument is a placeholder for members thatshould be ignored by the profile.

Table 4-4 tbvTaskTypeSafeT Public Methods, continued

Public Method Description

June 2000 87 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

Table 4-6 tbvProfileT Public Methods

Public Method DescriptiontbvProfileT(const char * profileNameP ,tbvTaskT * parentTaskP ,const tbvProfileT * parentProfileP= NULL)

Create a Profile. If a parentProfileP issupplied, then this new profile is “derived” fromthe parentProfileP .

tbvProfileArgT *addArgP(const char * argNameP,tbvProfileT::argTypeT argType ,tbvEnumsT::sigDirT direction =tbvEnumsT::WRITE_ONLY)

Add a new argument field of the given type to aprofile, where argNameP is the name of the newfield. You can also specify the direction of eachargument. New fields must be added in the orderthat they appear in the task context object class(tbvTaskContextT ). VOID_32 fields areplaceholders that are ignored by TestBuilder.

void setArgIntGen(const char * argName ,tbvIntGeneratorT * intGenP )

Associate an integer generator with a profileargument.

void setAutoValueGeneration(const bool=TRUE,const char * argName=NULL)

Enable (TRUE) or disable (FALSE) automaticgeneration of argument values when a task is runor spawned.

void setValue(const char * argName ,tbvTaskContextT * ContextP ,void * valueP )

Set task context object values directly. TheargName is the name of the field, ContextP isthe task context object that will be set, andvalueP is a pointer to the value to set.

const void *getValueP(const char * argName,tbvTaskContextT * ContextP ) const

Get the value of an argument.

June 2000 88 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,tbvUInt64T)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,int)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,char *)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,double)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,tbvSignal2StateT&)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,tbvSignalHdl2StateT&)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,tbvSignal4StateT&)

void setValue(const char * argName ,tbvTaskContextT * tbvTaskContextP ,tbvSignalHdl4StateT&)

Set the value of an argument with the given objecttype.

Table 4-6 tbvProfileT Public Methods, continued

Public Method Description

June 2000 89 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

const tbvUInt64T getUInt64Value(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const int getIntValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const char *getCharPValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const double getDoubleValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const tbvSignal2StateT&getSignal2StateValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const tbvSignalHdl2StateT&getSignalHdl2StateValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const tbvSignal4StateT&getSignal4StateValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

const tbvSignalHdl4StateT&getSignalHdl4StateValue(const char * argName ,tbvTaskContextT *tbvTaskContextP)const

Get the value of an argument with the given objecttype.

void setArgFormat(const char * argName , const char* formatSpecifierStringP )

Set the DTAPI format specification for anargument. This describes how to display anargument’s value as a property value in atransaction in Signalscan. The default format ishexadecimal.

int getTbvContextSize() const The size, in bytes, of a task context object.tbvProfileT* copy(tbvProfileT* = NULL)

Copy a profile, so that you can set newconstraints. The default profile to copy is thetask’s base profile.

Table 4-6 tbvProfileT Public Methods, continued

Public Method Description

June 2000 90 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTaskGroupT Class

The Task Groups class allows you to collect into groups tasks and other task groups. A groupcan then be executed from a Test. Use the tbvTaskGroupT and TestBuilder randomizationAPIs to specify which tasks are executed and the order in which these tasks are executed.

tbvProfileArgAssocArrayTgetArgAssocArray() consttbvTaskContextT*newTbvTaskContextP()

Table 4-7 tbvTaskGroupT Public Methods

Public Method DescriptiontbvTaskGroupT(const char * nameP = NULL)

Name of this group.

static tbvTaskGroupT*getTaskGroupByName(const char * name)

Return a task group pointer, given its name. Ifnot found, give a warning and return NULL.

void setIntGenerator(tbvIntGeneratorT*)

Set the generator for this task group, which isused to randomly select tasks to run or spawn. Ifyou do not set this, a default generator is used.

tbvIntGeneratorT *getIntGenerator() Return the generator for this task.void setUseMarking(const bool _useMarking = TRUE)

Set the useMarking flag for the generator forthis task group. See “tbvIntGeneratorT Class”on page 120.

void addTask(tbvTaskT * theTaskP ,const int weight = 1)

Add a Task to this task group, with the specifiedweighting.

void removeTask(tbvTaskT * theTaskP ) Remove a task from this group.const tbvTaskListT &getTaskList()const

Return the list of Tasks in this group.

tbvTaskT *nextTask() Return the randomly selected next task to run.Note that this call does not run the task.

Table 4-6 tbvProfileT Public Methods, continued

Public Method Description

June 2000 91 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

tbvTaskContextT Class

This is the base class from which you derive your task context object classes, which arepassed to the tbvTaskT::run and tbvTaskT::spawn methods.

void run(tbvFiberT * callerFiberP = NULL)

Do a blocking invocation of the randomlyselected next task to run. A task context objectis allocated, filled in with values, and the task isrun. When the task returns, the task contextobject is freed.

void spawn(tbvFiberT * callerFiberP = NULL)

Do a non-blocking invocation of the nextrandomly selected task. A task context object isallocated, filled in with values, and the task isrun. The task context object is not freed.

tbvTaskT *getLastTask() Return the last task that was run or spawned.

Table 4-8 tbvTaskContextT Public Methods

Public Method DescriptiontbvTaskContextT() The constructor for this class.virtual ~tbvTaskContextT() The destructor.tbvTaskContextT(const tbvTaskContextT&)

The copy constructor.

void generateValues(const bool setAllArguments = FALSE)

Generate values for arguments in this taskcontext object, using tbvValueGeneratorTobjects that have been set to various argumentsin the profile.

If setAllArguments is TRUE, set all valuesand ignore all thesetAutoValueGeneration() settings foreach argument.

Table 4-7 tbvTaskGroupT Public Methods, continued

Public Method Description

June 2000 92 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

bool checkAllConstraints(const bool giveWarning = TRUE)

Check values of all arguments with theirconstraints. Return TRUE if OK.

If giveWarning is TRUE, give a warningmessage if any constraints are violated.

bool checkConstraints(const char * argName)

Check value constraints for a particularargument.

void setAlwaysCheckConstraints(const bool = TRUE)

If TRUE, then always check argument valueconstraints when the task is run or spawned.This overrides individual settings on arguments.

bool getAlwaysCheckConstraints() Return the setting.void setParentTask(tbvTaskT * taskP ) Set the parent task.tbvTaskT *getParentTaskP() const Return the parent task.void setProfile(tbvProfileT * profileP )

Set the profile for this task. If this is not explicitlyset, then TestBuilder uses the profile in the task.

tbvProfileT *getProfileP() const The profile for this task.void setInitialFiber(tbvFiberT * fiberP )

Set the fiber that a task will initially run on whenit is called with this task context object.

tbvFiberT *getInitialFiberP() const Return the initial fiber for this task contextobject.

void setCurrentFiber(tbvFiberT * fiberP )

Set the fiber that this task context object isrunning on. Use this when you need to makeexplicit transBegin() and transEnd() calls.

tbvFiberT *getCurrentFiberP() const Get the fiber that this task is currently runningon. Note that this is not always the same as theinitial fiber, since it is possible for a task tomigrate from one fiber to another during itsexecution.

void setCallerFiber(tbvFiberT * fiberP )

Call this method before you run or spawn a task.This method sets the calling fiber in the taskcontext object, so that transactions in the taskbody will be linked (as predecessors andsuccessors).

tbvFiberT *getCallerFiberP() const Return the caller fiber.

Table 4-8 tbvTaskContextT Public Methods, continued

Public Method Description

June 2000 93 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

void setIgnoreFiberAtInvocation(const bool)

Set this to TRUE if you do not want TestBuilderto automatically do a wait on a fiber and atransBegin() at the time a task run or spawnis done. You must do explicit semaphore waitsand transBegin() and transEnd() callsinside your task body for interface control andtransaction recording. The default setting for thismethod is FALSE.

bool getIgnoreFiberAtInvocation()const

This is included for documentationcompleteness. You should not need to use thismethod.

void transBegin()

void transEnd()Use these methods to explicitly begin and endDTAPI transactions. Normally, transactionsbegin and end using thetbvTaskContextT::changeFiber()method or the tbvTaskT::run() ortbvTaskT::spawn() methods.

void changeFiber(tbvFiberT * fiberP) Use this method when a task body requiresmultiple transactions during execution, as in thecase of pipelined TVMs. This method first endsa transaction (if open), posts on the currenttask’s semaphore, waits on the fiberP ->semaphore , and then does a transBegin()on the fiberP .

bool getWasSpawned()const void setWasSpawned(bool _wasSpawned )

Return the setting if the task was run orspawned.

void setTraceTagDtH(dtObjectHandle _traceTagDtH );

dtObjectHandle getTraceTagDtH()const;

The current DTAPI trace tag object for the taskcontext object.

Table 4-8 tbvTaskContextT Public Methods, continued

Public Method Description

June 2000 94 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

Automatic Copy and Delete of Task Context Objects

Often a testbench contains a loop that spawns several tasks, and each task requires its owntask context object. In such a case, you must create a new task context object each timethrough the loop, and then you must delete it at the end. An example of this is shown below:

for ( int i = 0; i < COUNT; i++ ) {

myArgs *args = new myArgs;

// CODE TO SET ARGS

myTask->spawn(args);

// You must delete args, in myTask or elsewhere.

}

void setAutoCopy(bool copy = TRUE);

bool getAutoCopy() constEnable (TRUE) or disable (FALSE) automaticcopy and delete for this task context object. Ifyou do not call setAutoCopy() , automaticcopy and delete is disabled by default.

If copy is TRUE, then the task context object iscopied when a task is spawned, and the taskcontext object is deleted automatically when thetask is finished.

The getAutoCopy() call returns TRUE ifautomatic copy and delete is enabled for thistask context object.

See also “Automatic Copy and Delete of TaskContext Objects” below.

virtual tbvTaskContextT *duplicate()const;

To use automatic copy and delete for a taskcontext object type (see setAutoCopy above),you must override this function in your derivedclass. Your duplicate() function must createand return a new task context object that is acopy of the current one. Remember to makeyour function virtual. See also “Automatic Copyand Delete of Task Context Objects” below.

int getIntValue(char * argName);

char *getCharPValue(char * argName);

double getRealValue(char * argName);

Return values for arguments, given theargument’s name.

Table 4-8 tbvTaskContextT Public Methods, continued

Public Method Description

June 2000 95 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

If the testbench does not need to access the task context object after the thread has finished,you can use the TestBuilder facility that copies and deletes task context objects automatically:

myArgs args;

// CODE TO SET ARGS

args. setAutoCopy(TRUE);

for ( int i = 0; i < COUNT; i++ ) {

// CODE TO ADJUST ARGS

myTask->spawn(&args);

// spawn() will make a copy of args, and delete the

// copy when the thread has finished executing

}

To use this facility, you need to define a duplicate() method in your task context objectderived class. This method must call the copy constructor for tbvTaskContextT . Followingis a skeletal example of how that works:

class myArgs : public tbvTaskContextT {

// ...

// copy constructor

myArgs(const myArgs& original) : tbvTaskContextT(original) {

// code to copy data added for derived class

}

// ...

virtual myArgs * duplicate() { return new myArgs(*this); }

// ...

};

This facility is available only for tbvTaskT::spawn() . It is not available fortbvTaskT::run() or tbvThreadT::spawn() .

tbvFiberT Class

The tbvFiberT class encapsulates a tbvSemT semaphore object and a DTAPI threadobject. A fiber controls activity on a TVM interface by using the semaphore. See the DTAPIReference Manual for more information on DTAPI (Database Transaction API).

A fiber object can be associated with a TVM, where it will be used as the default fiber whenno other fiber is specified.

A fiber object can also be associated with a tbvTaskContextT , where you can specify theinitial fiber that a task invocation will run on (this is usually, but not necessarily, the TVM’sfiber).

June 2000 96 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

In the tbvTaskContextT::changeFiber() method, an executing task will end thecurrent transaction, post the current semaphore, and then begin running on the new fiber.This entails first waiting on the new fiber’s semaphore and then beginning a new transactionon the fiber. A predecessor/successor transaction linkage relationship is also set when thishappens.

For most TestBuilder usage you do not need to explicitly create fibers; you can use thenewTbvMainFiberP() method to create a top level Test fiber, and also use thetbvTvmT::newFiberP() method for TVMs.

Table 4-9 tbvFiberT Public Methods

Public Method DescriptiontbvFiberT(const char * fiberName = NULL)

Create a fiber. You must set the thread andsemaphore explicitly later.

tbvFiberT(const char * _threadNameP ,tbvTvmT * tvmP )

Create a fiber. Also create a DTAPI TVM threadobject with a name constructed from_threadNameP and the name of the specifiedTVM, in the same DTAPI module where thetvmP exists. Also create a tbvSemT in the fiber.

tbvFiberT(const char * fiberNameP ,dtObjectHandle myThreadDtH ,const char * _threadNameP ,tbvSemT * mySemP)

Create a fiber, where you supply your own fibername, DTAPI thread, thread name, andsemaphore.

static tbvFiberT *newTbvMainFiberP(const char * _threadNameP )

Create a fiber for the top level test. A DTAPI testthread is created.

static tbvFiberT *getTbvMainFiberP() Get the top level test fiber. If the fiber does notexist, this method first callstbvFiberT::newTbvMainFiberP() .

const char *getNameP() const The name of the fiber.const dtObjectHandle getThreadDtH()const

The DTAPI thread in this fiber.

const char *getThreadNameP() const The name of the DTAPI thread.void setThreadDt(dtObjectHandle DtapiThread )

Set the DTAPI thread for this fiber object.

tbvSemT *getSemP() const The TestBuilder semaphore in this thread.

June 2000 97 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTVMs, Tasks, and Fibers

TVMs, Tasks, and Fibers Exceptions

The following table describes the exception messages you may see regarding TVMs. All ofthese exception messages are members of the enumtbvExceptionT:: exceptionTypeT .

Table 4-10 TVM Exceptions

Message and Description

TVM_UNKNOWN_INSTANCE_NAME_WARNING

TVM_MISSING_CTOR_ARGS_WARNING

TVM_DESTRUCTOR_ILLEGALLY_CALLED_WARNING

TASK_STILL_ACTIVE

June 2000 98 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

5Randomization

This chapter describes the facilities for random value generation. These facilities can be usedindependently or in conjunction with task profiles (see “tbvProfileT Class” on page 87) togenerate directed random tests. In future releases, they will be expanded to include testsynthesis.

This chapter discusses:

■ Overview of the Randomization Facilities

■ tbvRandomT

■ Value Generators with Constraints

❑ tbvValueGeneratorT

❑ tbvIntGeneratorT

❑ tbvRealGeneratorT

❑ tbvSignalGeneratorT

❑ tbvComplexGeneratorT

June 2000 99 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Randomization Class Diagram

tbvDataStructureT

tbvValueGeneratorTtbvRandomT

tbvListT<T>

tbvBagT<T>

tbvProfileT

tbvIntGeneratorT

tbvRealGeneratorT

tbvSignalGeneratorT

tbvComplexGeneratorT

tbvSignalT

June 2000 100 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Overview of the Randomization Facilities

In the standard C library, rand() generates a random integer, and srand() sets the seed.In Verilog, $random generates a random integer. Both of these suffer from the fact thatadding calls to rand() or $random affects the results of other calls to them.

In TestBuilder, the tbvRandomT class provides better control of a random simulation:

■ The operations of two instances of tbvRandomT are independent: Adding a new randomtest to run concurrently with an existing random test does not change the behavior of theexisting test.

■ The tbvRandomT class provides a registry to record the seeds used for the randomgenerators. Using the APIs to this registry, you can save and restore the seeds of thegenerators to reproduce the same behavior in different simulation runs.

■ The tbvRandomT class provides the APIs for you to specify a custom algorithm.

Another set of classes gives you the ability to handle constraints in directed random tests, andto use advanced techniques to increase simulation coverage. These classes are all derivedfrom the same base class, tbvValueGeneratorT , which summarizes the commoninterfaces to these generators. These generators are also a derived class of classtbvDataStructureT , inheriting the interface to turn on database recording.

There are many techniques to generate directed random tests that have good designcoverage. The different modes of generating values are captured in thetbvValueGeneratorT::generatorModeT enum.

There are four kinds of random value generators derived from tbvValueGeneratorT .

The use model is very simple for simple generators. For example:

tbvIntGeneratorT random;

int i = random.next();

Table 5-1 Random Value Generators

Random Value Generator Descriptionclass tbvIntGeneratorT A generator for random integer values.class tbvRealGeneratorT A generator for random floating point values.class tbvSignalGeneratorT A generator for random signal values.template tbvComplexGeneratorT A generator for user-defined data types.

June 2000 101 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

To specify simple constraints about the values to be generated, use the interface defined inthis chapter. To specify complex constraints, use the task profile facilities (see “tbvProfileTClass” on page 87).

To share a random value generator among multiple tests, tasks, or TVMs, use thetbvSafeHandleT as part of a task argument, or put the shared generators in a TVM or atask.

Type and Range of Generated Values

The rand() function generates an integer of type int from 0 to RAND_MAX, whereRAND_MAXis a constant from stdlib.h whose value is typically 0xFFFF. The tbvRandomTfacilities generate an integer of type unsigned int with a range from 0x0 to 0xFFFFFFFF.

This type of generated value supports two use models:

■ Generate an integer from 0 to MAX using the modulo operator, %:

tbvRandomT random;

int i = random.next() % 10;

assert(i>=0 && i<10);

■ Generate a bit vector with random bit values:

tbvRandomT random;

tbvSignalT s(31,0);

s = random.next();

Table 5-2 below summarizes the type and range of generated values:

Table 5-2 Type and Range of Generated Values

Class Type Range (without constraints)tbvRandomT unsigned int 0x0 to 0xFFFFFFFF

tbvIntGeneratorT int-231 to 231-1, or [-231, 231)

tbvRealGeneratorT double user-specified in the constructortbvSignalGeneratorT tbvSignalT

0 to 2numberOfBits-1, or [0, 2numberOfBits)tbvComplexGeneratorT custom custom (depends on custom unpack and

setup functions)

June 2000 102 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Internal Random int Stream for Initial Seeds

As you create multiple instances of tbvRandomT , supply them with different seeds. If twoinstances with the same algorithm use the same seed, they may execute in lock step and ruinthe effectiveness of a random simulation.

If you do not explicitly supply the seeds, the seeds are generated by calling an internalrandom int stream. Use the static method setSeedGenerationAlgorithm() to specifythe algorithm and the initial seed of this internal stream.

Seed Monitoring

Use the APIs in tbvRandomT to store and retrieve seed information from files. At any pointduring simulation, at most one file can be active for storing seed information. When you callthe tbvRandomT static method seedMonitorOn() , the TestBuilder library stores andretrieves the seeds of all future instances of tbvRandomT to and from a file you specify, untilyou call seedMonitorOff() .

If you call seedMonitorOn() twice without calling seedMonitorOff() , the second call toseedMonitorOn() automatically calls seedMonitorOff() to close the previous filebefore storing the seed information to the new file.

You can specify the seed information file in either of the following ways:

■ An explicit file name: If you supply a file name to seedMonitorOn() , that file isassumed to be exclusively used for storing and retrieving seed information.

■ A file pointer: If you supply a file pointer to seedMonitorOn() , it is assumed that thefile can contain other information. Therefore, a string tag is used to identify whichinformation is the seed information for the randomization facilities.

Matching Seeds to Generators

When a seed is retrieved from a file, the seed is matched to its corresponding tbvRandomTor tbvValueGeneratorT according the name of the instance:

■ Unique instance name. If the instance of tbvRandomT or tbvValueGeneratorThas a unique name, the seed is guaranteed to be retrieved correctly.

■ Non-unique instance name. If two instances of tbvRandomT ortbvValueGeneratorT have the same name, the seeds are retrieved in the order inwhich the instances were stored. If the order of instantiations has not changed, the seeds

June 2000 103 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

will be retrieved correctly. If the order of instantiations has changed (for example,because of a change in the DUV or the test), the seeds will not be retrieved correctly.

■ No instance name. If two instances of tbvRandomT or tbvValueGeneratorT do nothave user-specified names, the seeds are retrieved in the order in which the instanceswere stored. Similar to the case described above for instances that have the same name,the seeds will be retrieved correctly only if the order of instantiations has not changed.

Example: Unconstrained Random Integer Generation

The following example shows the usage of tbvRandomT :

void randomTest(bool retrieve) {

// Create two independent tbvRandomT instances with default settings

tbvRandomT ta("transaction a");

tbvRandomT tb("transaction b");

// Generate a random value for transaction a.

unsigned int va = ta.next();

// Because ta and tb are independent, no matter how many times

// ta.next() executes, tb.next() always gets the same random value.

unsigned int vb = tb.next();

// Specify custom settings.

tbvRandomT:: setSeedGenerationAlgorithm(tbvRandomT::RAND48,

NULL,1234,0);

tbvRandomT:: setDefaultAlgorithm(tbvRandomT::CUSTOM,

myRandomAlgorithm);

// Save/retrieve seeds to/from a file.

tbvRandomT::seedMonitorOn(retrieve,"seed.log");

// Body of the code that instantiates tbvRandomT.

// If a seed file is supplied, the seeds of the tbvRandomT instance

// are set to the seeds in the seed file.

tbvRandomT tc("transaction c");

// Wrap up the seed file.

tbvRandomT::seedMonitorOff();

}

June 2000 104 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Specifying Generation Mode

See “tbvValueGeneratorT::generatorModeT Enum” on page 116.

Specifying Constraints

Use the keepOnly() and keepOut() methods to specify simple constraints on the valuesto be generated by a tbvValueGeneratorT :

■ All derived classes of tbvValueGeneratorT have a set of methods calledkeepOnly() with different argument lists. Call this method to generate only the valuesspecified in the arguments.

■ All derived classes of tbvValueGeneratorT have a set of methods called keepOut()with different argument lists. Call this method to tell the generator not to generate thevalues specified in the arguments.

In all cases, the new constraints should be a further restriction upon previously specifiedconstraints. If the new constraint specifies some legal values that are forbidden by previousconstraints, an error is reported, and the resulting behavior is undefined.

June 2000 105 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvRandomT Class

You should use the tbvRandomT class instead of rand() from the standard C library.

By default, the tbvRandomT class uses jrand48() in the C library as the basis of thealgorithm to generate a random integer. The jrand48() function is a member in a family offunctions that generate pseudo-random numbers using the well known linear congruentalgorithm and 48-bit integer arithmetic. It returns signed long integers uniformly distributedover the interval [-231, 231), or from -231 to 231-1.

Features of the tbvRandomT class include:

■ While the jrand48() function is the basis of the default algorithm, the tbvRandomTdefault algorithm generates an unsigned integer uniformly distributed over the interval[0, 232), or from 0 to 232-1.

■ The operations of two instances of tbvRandomT are independent. If you add a newrandom test to run concurrently with an existing random test, the behavior of the existingtest does not change.

■ The tbvRandomT class provides a registry to record the seeds used for the randomgenerators. Using the APIs for this registry, you can save and restore the seeds of thegenerators to reproduce the same behavior in different simulation runs.

■ The tbvRandomT class provides the APIs to specify a custom algorithm.

Custom Algorithm

If you want to provide your own algorithm, specify it with the same type as the followingC-style function:

inline unsigned int myRand(unsigned long& next) {

next = next * 1103515245 + 12345;

return (unsigned int)(next/65536) % 32768;

}

To attach this algorithm to tbvRandomT , use setDefaultAlgorithm() .

Note: Make sure that your algorithm generates values over the interval [0, 232) with thedistribution that you want. When you use tbvRandomT directly, you may use a non-uniformdistribution. However, since tbvValueGeneratorT may use multiple calls to the algorithmto generate a single value, a non-uniform distribution in the algorithm could result inunpredictable distribution in the values generated by tbvValueGeneratorT . Make sure thatyour algorithm has a uniform distribution when a tbvValueGeneratorT is instantiated.

June 2000 106 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

If you do not specify the initial seed, the initial seed is generated using an internal randomint stream. To provide the seed for this stream, use the methodsetSeedGenerationAlgorithm() . If you do not provide a seed, the seed for the internalstream is generated by calling:

tbvDefaultGlobalInitSeed(unsigned long jobNumber = 0)

This function uses the current time (gettimeofday in the C library), the system-up time(times in the C library), and the argument jobNumber to generate a seed for this stream.The jobNumber is typically used with a server farm, in which multiple simulations may beinitiated in multiple servers at about the same time, to avoid two simulations with the sameseed.

tbvRandomT Public Base Class

tbvDataStructureT

June 2000 107 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvRandomT Public Member Types

tbvRandomT Public Static Methods (Main)

Table 5-3 tbvRandomT Public Member Types

Public Member Type Descriptionenum valueGenerationAlgorithmT {

RAND48,

CUSTOM }

This represents the different algorithms that can beused to generate a random number.

RAND48 uses the same algorithm as jrand48() inthe C library.

CUSTOM implies a user-supplied algorithm,encapsulated in a function of type algFuncT .

algFuncT The type of a custom algorithm function pointer:

unsigned int(*algFuncT)(unsigned long&)

Table 5-4 tbvRandomT Public Static Methods

Public Static Method (Main) Descriptionstatic voidsetSeedGenerationAlgorithm(valueGenerationAlgorithmTalg = RAND48,algFuncT customAlg = NULL,unsigned long seed = 0,unsigned long jobNumber = 0)

This method sets up the internal random numberstream for generating seeds for user-specifiedtbvRandomT instances.

If seed = 0 , thentbvGlobalInitSeed( jobNumber ) is called togenerate the initial seed for this stream. This istypically used when simulations are submitted to aserver farm, in which cases you should use adifferent jobNumber for each simulation to ensureindependent simulation sessions. On the otherhand, you may also use your own seed server todistribute different seeds to different simulationsessions, by calling the server and passing theassigned seed to this method.

static void setDefaultAlgorithm(valueGenerationAlgorithmT alg ,algFuncT customAlg = NULL)

Set the base algorithm for generating a randomnumber.

The customAlg is ignored unless alg isCUSTOM. If alg is CUSTOM and customAlg isNULL, RAND48 is used for alg .

June 2000 108 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Example Seed File

The seed file should include the name of each generator and the seed used for eachgenerator, in the following human-readable format:

"name1" :: 1204359l

"name4" :: 1200000l

Unnamed generators are named <anonymous> .

static void printSeeds(const char * fileName )

Print the current seed information in a file. Print it tocout if fileName is NULL.

static void printSeeds(ostream& = cout)

Print the current seed information in an outputstream.

static void seedMonitorOn(bool retrieve ,const char * fileName )

If retrieve is false, store future seed informationin a file, until seedMonitorOff() is called.

If retrieve is true, load the seed information intothe registry and use it to initialize subsequenttbvRandomT .

If this method is called twice without a call toseedMonitorOff() in between, a warning isissued and seedMonitorOff() is called beforeexecuting the second seedMonitorOn() .

Turns monitoring off if fileName is NULL.static void seedMonitorOn(bool retrieve ,const char * monitorName ,FILE * file );

This method is the same as the previousseedMonitorOn() method, except that it storesthe seed information in a user-created file pointer.The same pointer may be used by other code tostore other information.

The seed information stored in this file is prefixedby the monitorName . Make sure that otherinformation does not use a < without a matching >,and make sure that other information does notcontain the string “<monitorName> ”.

static void seedMonitorOff() Stop monitoring the seed information.

Table 5-4 tbvRandomT Public Static Methods, continued

Public Static Method (Main) Description

June 2000 109 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

If you use the second seedMonitorOn() method with the monitor namemy_seed_monitor , the seed used for each generator is stored in the following format:

<my_seed_monitor> "name 1" :: 123125

... other stuff ...

<my_seed_monitor> "name 2" :: 123125

To allow TestBuilder to match the generators with their seeds, provide a unique name to eachgenerator in the same seed file or with the same monitorName .

tbvRandomT Examples

Testbench Example

void initTest(bool retrieve) {

tbvRandomT::seedMonitorOn(retrieve,"myseed")

// start tests with seed recording or seed retrieval.

}

Debug Environment Example

debug> print tbvRandomT::printSeeds();

June 2000 110 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvRandomT Public Methods

tbvRandomT Examples: Setting Seeds and Algorithmsint main(int argc, char **argv) {

// Create two independent tbvRandomT instances using

// default settings.

tbvRandomT ta("transaction a");

tbvRandomT tb("transaction b");

Table 5-5 tbvRandomT Public Methods

Public Method DescriptiontbvRandomT(const char * name = NULL)

constructor with optional user-specified name

tbvRandomT( unsigned long seed ) constructor with user-specified seedtbvRandomT( const char * name,

unsigned long seed )constructor with user-specified name and seed

tbvRandomT(const tbvRandomT& other ,const char * name=NULL,unsigned long seed = 0);

copy constructor

The name and seed of other are not copied. Youcan provide a new name and seed in the secondand third arguments.

~tbvRandomT() destructorconst char * name() const Return the user-specified name for the generator.

This method returns NULL if no name has beenspecified. This method is inherited fromtbvDataStructureT .

unsigned long getSeed() const Return the seed for the generator.unsigned int next() Generate the next random integer.void setAlgorithm(ValueGeneratorAlgorithm alg =RAND48,algFuncT customAlg = NULL)

Change the algorithm to the new algorithm.customAlg is ignored unless alg = CUSTOM.

If alg is CUSTOM and customAlg is NULL,algorithm RAND48 is used.

void print(ostream& = cout) const Print onto the output stream. This method is inheritedfrom tbvDataStructureT .

June 2000 111 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

// Generate a random value for transaction a.

unsigned int va = ta.next();

// Because ta and tb are independent,

// regardless of how many times ta.next() is executed,

// tb.next() always get the same random value.

unsigned int vb = tb.next();

// Custom settings.

tbvRandomT:: setSeedGenerationAlgorithm(tbvRandomT::RAND48,

NULL, 3999, 2);

tbvRandomT:: setDefaultAlgorithm(tbvRandomT::CUSTOM,

myRandomAlgorithm);

// Save seeds to a file unless the first argument is "-r",

// in which case retrieve seeds from a file.

tbvRandomT::seedMonitorOn((argc>1 && 0==strcmp(argv[1],"-r")),

"seed.log");

// Body of the code that instantiates tbvRandomT.

// If a seed file is supplied, the seeds of the tbvRandomT

// instance are set to the seeds in the seed file.

tbvRandomT tc("transaction c");

// Wrap up the seed file.

tbvRandomT::seedMonitorOff();

}

June 2000 112 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Value Generators with Constraints

This section discusses:

■ tbvValueGeneratorT Class

■ tbvValueGeneratorT::generatorModeT Enum

■ tbvIntGeneratorT Class

■ tbvRealGeneratorT Class

■ tbvSignalGeneratorT Class

■ tbvComplexGeneratorT Template

June 2000 113 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvValueGeneratorT Class

This is the base class for all random value generators with the capability of handlingconstraints and multiple modes of value generation.

tbvValueGeneratorT Public Base Class

tbvDataStructureT

tbvValueGeneratorT Public Enum

generatorModeT

tbvValueGeneratorT Public Static Methods (Main)

tbvValueGeneratorT Public Methods

Table 5-6 tbvValueGeneratorT Public Static Methods

Public Static Method (Main) Descriptionstatic voidsetDefaultGeneratorMode(generatorModeT m = PURE_RANDOM)

Set the default randomization mode for futuregenerators created through the registry interface. Theinitial mode for the registry is PURE_RANDOM.

Table 5-7 tbvValueGeneratorT Public Methods

Public Method Description~tbvValueGeneratorT destructorconst char * name() const Return the user-specified name for the generator.

This method returns NULL if no name has beenspecified. This method is inherited fromtbvDataStructureT .

void setMode(generatorModeT m = PURE_RANDOM)

Set the generator to a different algorithm forgenerating the values. The default is determined bythe registry when this generator is created.

June 2000 114 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

generatorModeT getMode() const Get the current mode of operation.unsigned long getSeed() const Return the seed for the generator.

Table 5-7 tbvValueGeneratorT Public Methods, continued

Public Method Description

June 2000 115 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvValueGeneratorT::generatorModeT Enum

The tbvValueGeneratorT::generatorModeT enum specifies the mode in which togenerate a random value. It consists of the following members (see also “PerformanceConsiderations,” “Changing Generator Modes,” “Example: Constrained Value Generation,”and “Future Developments” below):

DISTRIBUTION Mode

The primary way to specify a distribution is to pass a bag to thesetWeightDistribution() method.

If a value in the bag does not satisfy the constraints, it is not generated. The integer value isgenerated by a weighted random selection over the objects in the bag.

The setWeightDistribution() method has a useMarking option. If you do not specifyuseMarking , successive generations are independent. If you specify useMarking ,successive generations reduce the chance of generating a previously generated value untilall objects in the bag have been generated.

In future releases, other ways of specifying a distribution may be added, such as generatingvalues using a normal distribution function.

Table 5-8 tbvValueGeneratorT::generatorModeT Members

Member DescriptionPURE_RANDOM Pure random generation.DISTRIBUTION Random generation according to a distribution function.

See “DISTRIBUTION Mode” below.RANDOM_AVOID_DUPLICATE Random generation while avoiding repetition. For a

generator of floating point values, by default, a value is aduplicate of another if their difference is smaller than 1.This can be configured to use a different value todetermine whether two generated values are duplicates.

SCAN Scan through the possible values systematically. When thescan is complete, start from the beginning again. Bydefault, a generator (Int/Real/tbvSignalT /Complex)generates the lower bound value first, and then incrementsit by one for each successive generation. This generatorcan also be configured to use a different increment or arandom increment. See “SCAN Mode” below.

June 2000 116 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

SCAN Mode

You can customize value generation in SCANmode by using the setInterval() method tospecify the interval to increase for successive generations.

If you provide a specific value, each time next() is called, a new value is selected byrepeatedly adding the specified value to the previous value until the new value satisfies theconstraints.

If you specify a range, each time next() is called, a random value within the range is addedto the previous value repeatedly until the new value satisfies the constraints.

Performance Considerations

The distribution mode is primarily used for weighted-random value generation. There issignificant overhead in both run time and memory fortbvValueGeneratorT::RANDOM_AVOID_DUPLICATE andtbvValueGeneratorT::SCAN when compared totbvValueGeneratorT::PURE_RANDOM and tbvValueGeneratorT::DISTRIBUTION .

Changing Generator Modes

You can change the mode of a generator after some values have been generated. The effectof changing the mode on-the-fly is summarized as follows:

Table 5-9 Effects of Changing Generator Modes

Change PURE_RANDOM orDISTRIBUTION

RANDOM_AVOID_DUPLICATE SCAN

change to:

PURE_RANDOM orDISTRIBUTION

N/A Generation history isignored, but noterased.

Generation history isignored, but noterased.

change to:

RANDOM_AVOID_DUPLICATE

Values generatedduring Pure Randommode are not checkedfor duplicates.

N/A Values generatedduring Scan modeare also avoided.

June 2000 117 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Example: Constrained Value Generation

An example of the usage of tbvValueGeneratorT and tbvIntGeneratorT is shownbelow:

void randomTest(bool retrieve) {

// Custom setting for tbvRandomT.

tbvRandomT:: setSeedGenerationAlgorithm(tbvRandomT::RAND48,

NULL, 1234, 0);

tbvRandomT:: setDefaultAlgorithm(tbvRandomT::CUSTOM,

myRandomAlgorithm);

// Save/retrieve seeds to/from a file.

tbvRandomT::seedMonitorOn(retrieve,"seed.log");

// Set default mode of constrainted value generation.

tbvValueGeneratorT::setDefaultGeneratorMode(

tbvValueGeneratorT::PURE_RANDOM);

// Instantiate a constrainted integer generator (for values

// [0,100]).

tbvIntGeneratorT a("testing_constraints",0,1,100);

// Add some constraints.

a.keepOut(70,79); // Do not generate [70.79].

tbvListT<int> l;

l.pushBack(2);

l.pushBack(3);

l.pushBack(4);

a.keepOut(l); // Do not generate 2,3,4.

change to:

SCAN

Values generatedduring Pure Randommode are ignored.

Values generatedduring RandomAvoid Duplicatemode are alsoavoided.

N/A

Table 5-9 Effects of Changing Generator Modes, continued

Change PURE_RANDOM orDISTRIBUTION

RANDOM_AVOID_DUPLICATE SCAN

June 2000 118 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

for (int i=0; i<1000; ++i) {

doTest(a.next());

}

// Wrap up the seed file.

tbvRandomT::seedMonitorOff();

}

Future Developments

In a future release, the randomization facilities will include the following modes:

■ tbvValueGeneratorT::CORNER_CASES

Random generation biased toward the corner cases (INT_MAX, INT_MIN , for example).

■ tbvValueGeneratorT::MISSING_VALUES

Random generation biased toward missing values from supplied value coverageinformation (from previous and current simulation runs).

■ tbvValueGeneratorT::TST

Transformation of random values toward missing design coverage.

June 2000 119 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvIntGeneratorT Class

tbvIntGeneratorT Public Base Class

tbvValueGeneratorT

tbvIntGeneratorT Public Methods (Main)

Table 5-10 tbvIntGeneratorT Public Methods (Main)

Public Method (Main) DescriptiontbvIntGeneratorT(const char * name = NULL)

Create an integer generator with an optional user-specified name.

tbvIntGeneratorT(unsigned long seed )

Create an integer generator with a user-specifiedseed. If seed is 0, a new seed is generated using thedefault algorithm in tbvRandomT .

tbvIntGeneratorT(const char * name,unsigned long seed ,int lowerbound = 0,int upperbound = INT_MAX)

Create an integer generator with optional user-specified name, seed, lower bound, and upperbound.

tbvIntGeneratorT(const tbvIntGeneratorT& other ,const char * name = NULL,unsigned long seed = 0);

copy constructor

The name and seed of other are not copied. Youcan provide a new name and seed in the secondand third arguments.

~tbvIntGeneratorT() destructorbool satisfyConstraints( int v )const

Return true if v satisfies the constraints.

int next() Generate the next random value.

June 2000 120 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvIntGeneratorT Example

The following example...

tbvIntGeneratorT randomInt;

int i = randomInt.next();

randomInt.setMode(tbvValueGeneratorT::SCAN);

randomInt.setScanInterval(2);

for (int i=0; i<1000; ++i)

tbvOut << randomInt.next() << endl; // print 0,2,4,6,... up to 1998.

Simple constraints can be specified through another set of public methods of this class. Everytime a new constraint is added, it should satisfy all existing constraints associated with thecorresponding generator; otherwise it is an error.

void setWeightDistribution(const tbvBagT<int>&,bool useMarking = FALSE)

Set the weight distribution for the DISTRIBUTIONmode.

If a value in the bag does not satisfy the constraints, itis not generated. The integer value is generated by aweighted random selection over the objects in thebag.

If useMarking is false, successive generations areindependent.

If useMarking is true, successive generationsreduce the chance of generating a previouslygenerated value until all objects in the bag have beengenerated.

void setScanInterval(int lb , int ub )

Change the interval setting for the SCAN mode.

In scan mode, by default the next value is generatedby incrementing the previous value by 1. When thismethod is called, the difference between the nextvalue and the previous value is a random numberbetween lb and ub , inclusive. When ub <= lb , theupper bound is the same as the lower bound. It is anerror if lb < 1 .

Table 5-10 tbvIntGeneratorT Public Methods (Main), continued

Public Method (Main) Description

June 2000 121 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvIntGeneratorT Public Methods (Constraints Related)

tbvIntGeneratorT Examples

Example of Invalid Usage

The following example is incorrect because the subrange specified in the second keepOnlycall is larger than the subrange specified in the first keepOnly call.

tbvIntGeneratorT random;

random.keepOnly(0,99);

random.keepOnly(100,121); // error!

Example of Limiting Generated Values

The following example prints a random number within [0,99] except 8 and 80:

tbvIntGeneratorT randomInt;

randomInt.keepOnly(0,99);

tbvListT<int> badValue; badValue.push(8); badValue.push(80);

randomInt.keepOut(badValue);

tbvOut << randomInt.next() << endl;

Table 5-11 tbvIntGeneratorT Public Methods (Constraints)

Public Method (ConstraintsRelated) Description

void keepOnly(int lb , int ub ) Further limit the values to the specified smallersubrange. The subrange includes lb and ub . That is,the generated value could be lb or ub .

void keepOnly(const tbvListT<int>&)

Further limit the values to one of the values in the list.

void keepOnly(int v ) Further limit the values so that the value is always v.void keepOut(int lb , int ub ) Further limit the values to be outside the specified

subrange. The subrange includes lb and ub . That is,the generated value cannot be either lb or ub .

void keepOut(int v ) Further limit the values so that a value cannot be v.void keepOut(const tbvListT<int>&)

Further limit the values so that a value cannot be oneof the values in the list.

June 2000 122 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Scanning with Constraints

The following example demonstrates scanning with constraints.

tbvIntGeneratorT randomInt;

randomInt.keepOnly(0,10);

randomInt.keepOut(8);

randomInt.setMode(tbvValueGeneratorT::SCAN);

randomInt.setScanInterval(2);

for (int i=0; i<5; ++i)

tbvOut << randomInt.next() << endl;

// print 0,2,4,6,10 (8 is skipped)

June 2000 123 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvRealGeneratorT Class

tbvRealGeneratorT Public Base Class

tbvValueGeneratorT

tbvRealGeneratorT Public Methods (Main)

Table 5-12 tbvRealGeneratorT Public Methods (Main)

Public Method (Main) DescriptiontbvRealGeneratorT(const char * name,unsigned long seed ,int lowerbound = 0,int upperbound = DBL_MAX)

Create a floating point number generator withoptional user-specified name, seed, lower bound,and upper bound.

tbvRealGeneratorT(const tbvRealGeneratorT& other ,const char * name = NULL,unsigned long seed = 0);

copy constructor

The name and seed of other are not copied. Youcan provide a new name and seed in the secondand third arguments.

~tbvRealGeneratorT() destructorbool satisfyConstraints(double v ) const

Return true if v satisfies the constraints.

double next() Generate the next random value.void setWeightDistribution(

const tbvBagT<double>&,bool useMarking = FALSE)

Set the weight distribution for the DISTRIBUTIONmode.

If a value in the bag does not satisfy the constraints, itis not generated. The integer value is generated by aweighted random selection over the objects in thebag.

If useMarking is false, successive generations areindependent.

If useMarking is true, successive generationsreduce the chance of generating a previouslygenerated value until all objects in the bag have beengenerated.

June 2000 124 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvRealGeneratorT Examples

In the following examples...

tbvRealGeneratorT randomReal;

double i = randomReal.next();

The following example uses SCAN mode:

randomReal.setMode(tbvValueGeneratorT::SCAN);

randomReal.setScanInterval(0.5);

int i;

for (i=0; i<5; ++i)

tbvOut << randomReal.next() << endl;

// print 0, 0.5, 1, 1.5, and 2

The following example is a continuation of the previous example. This example changes themode to RANDOM_AVOID_DUPLICATEmode. This example does not print any value between0 and 22 since these values are considered to be duplicates of 2, which has been generatedbefore.

randomReal.setMode(tbvValueGeneratorT::RANDOM_AVOID_DUPLICATE);

randomReal.setDuplicateDistance(20);

tbvOut << randomReal.next() << endl;

void setDuplicateDistance(double distance = 1)

Change the distance setting for theRANDOM_AVOID_DUPLICATE mode.

If the difference between two values is smaller thanthe specified distance , the two values areduplicates.

void setScanInterval(double lb , double ub )

Change the interval setting for the SCAN mode.

In scan mode, by default the next value is generatedby incrementing the previous value by 1. When thismethod is called, the difference between the nextvalue and the previous value is a random numberbetween lb and ub , inclusive. When ub <= lb , theupper bound is the same as the lower bound. It is anerror if lb <= 0 .

Table 5-12 tbvRealGeneratorT Public Methods (Main), continued

Public Method (Main) Description

June 2000 125 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Simple constraints can be specified through another set of public methods of this class. Everytime new a constraint is added, it should satisfy all existing constraints associated with thecorresponding generator; otherwise it is an error.

tbvRealGeneratorT Public Methods (Constraints Related)

tbvRealGeneratorT Examples

The following is an example of invalid usage since the second subrange specified is outsidethe range of the first subrange specified:

tbvRealGeneratorT random;

random.keepOnly(0.5,25.5);

random.keepOnly(100.5,120.5); // error!

The following example prints a random number within [0.5,23.5] except between [3.6,5.5].

tbvRealGeneratorT randomReal;

randomInt.keepOnly(0.5,23.5);

randomInt.keepOut(3.6,5.5);

tbvOut << randomInt.next() << endl;

// Scanning with constraints:

randomInt.setMode(tbvValueGeneratorT::SCAN);

randomInt.setScanInterval(1.5);

for (int i=0; i<4; ++i)

tbvOut << randomInt.next() << endl;

// print 0.5, 2, 3.5, 6.5 (5 is skipped)

Table 5-13 tbvRealGeneratorT Public Methods (Constraints)

Public Method (ConstraintsRelated) Description

void keepOnly(double lb , double ub )

Further limit the values to the specified smallersubrange. The subrange includes lb and ub . That is,the generated value could be lb or ub .

void keepOnly(double v ) Further limit the values so that the value is always v.void keepOnly(const tbvListT<double>&)

Further limit the values to one of the values in the list.

void keepOut(double lb , double ub )

Further limit the values to be outside the specifiedsubrange. The subrange excludes lb and ub .

June 2000 126 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvSignalGeneratorT Class

You can use tbvSignalGeneratorT to create a value generator for a tbvSignalT (anunsigned 2-state signal of arbitrary size).

Note: You can use an unsigned integer constant in place of an unsigned 2-state signal intbvSignalGeneratorT methods that take an unsigned 2-state signal as an argument. Youcannot use negative integer constants in this way; the resulting behavior is undefined.

The signals generated by a tbvSignalGeneratorT always have a most-significant-bit(msb) of numBits -1 and a least-significant-bit (lsb) of 0. For example:

tbvSignalGeneratorT gen(32); // gen is a 32-bit signal

assert(gen->next().msb() == 31); // the msb of gen is 31

assert(gen->next().lsb() == 0); // the lsb of gen is 0

assert(gen->next().size() == 32); // the number of bits in gen is 32

tbvSignalGeneratorT Public Base Class

tbvValueGeneratorT

tbvSignalGeneratorT Public Member Type

tbvSignalGeneratorT Public Methods (Main)

Table 5-14 tbvSignalGeneratorT Public Member Type

Public Member Type DescriptionfieldManipulatorT A class from which a simple constraint on selected bits can be

specified.

An object of this type is returned bytbvSignalGeneratorT::operator()(int,int) .

Table 5-15 tbvSignalGeneratorT Public Methods (Main)

Public Method (Main) DescriptiontbvSignalGeneratorT(int numBits ,const char * name = NULL)

Create a signal value generator.

June 2000 127 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvSignalGeneratorT(int numBits ,unsigned long seed )

Create a signal value generator with an explicit seed.

tbvSignalGeneratorT(int numBits ,const char * name = NULL,unsigned long seed )

Create a signal value generator with a name and anexplicit seed.

tbvSignalGeneratorT(const tbvSignalGeneratorT&other ,const char * name = NULL,unsigned long seed = 0);

copy constructor

The name and seed of other are not copied. Youcan provide a new name and seed in the secondand third arguments.

~tbvSignalGeneratorT() destructorbool satisfyConstraints(const tbvSignalT&) const

Return true if tbvSignalT& satisfies the constraints.

tbvSignalT next() Generate the next random value.void setWeightDistribution(const tbvBagT<tbvSignalT>&,bool useMarking = FALSE)

Set the weight distribution for the DISTRIBUTIONmode.

If a value in the bag does not satisfy the constraints, itis not generated. The integer value is generated by aweighted random selection over the objects in thebag.

If useMarking is false, successive generations areindependent.

If useMarking is true, successive generationsreduce the chance of generating a previouslygenerated value until all objects in the bag have beengenerated.

void setScanInterval(const tbvSignalT& lb ,const tbvSignalT& ub )

Change the interval setting for SCAN mode.

In scan mode, the next value is by default generatedby incrementing the previous value by 1. When thismethod is called, the difference between the nextvalue and the previous value is a random numberbetween lb and ub , inclusive. When ub < lb , theupper bound is the same as the lower bound. It is anerror if lb < 1 .

Table 5-15 tbvSignalGeneratorT Public Methods (Main), continued

Public Method (Main) Description

June 2000 128 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvSignalGeneratorT Examples

The following example uses next() :

tbvSignalGeneratorT randomSignal(32);

tbvSignalT s(32) = randomSignal.next();

The following example uses SCAN mode:

randomSignal.setMode(tbvValueGeneratorT::SCAN);

randomSignal.setScanInterval("0xFF","0xFF");

tbvSignalT * s = getSignal();

for (int i=0; i<1000; ++i)

*s = randomSignal.next(); // assign *s to 0, 0xFF, 0x1FE, ...

tbvWait(30);

}

Simple constraints can be specified through another set of public methods of this class. Everytime new a constraint is added, it should satisfy all existing constraints associated with thecorresponding generator; otherwise it is an error.

tbvSignalGeneratorT Public Methods (Constraints Related)

fieldManipulatorT operator()(int msb, int lsb )

An operator to return a fieldManipulatorT . Themsb is the most significant bit and the lsb is theleast significant bit.

The field contains the bits between msb and lsb ,including msb and lsb .

Table 5-16 tbvSignalGeneratorT Public Methods (Constraints)

Public Method (ConstraintsRelated) Description

void keepOnly(const tbvSignalT& lb ,const tbvSignalT& ub )

Further limit the values to the specified smallersubrange. The subrange includes lb and ub . That is,the generated value could be lb or ub .

void keepOnly(const tbvListT<tbvSignalT>&)

Further limit the values to one of the values in the list.

Table 5-15 tbvSignalGeneratorT Public Methods (Main), continued

Public Method (Main) Description

June 2000 129 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvSignalGeneratorT::fieldManipulatorT Public Methods

void keepOnly(const tbvSignalT& v )

Further limit the values so that the value is always v.

void keepOut(const tbvSignalT& lb ,const tbvSignalT& ub )

Further limit the values to be outside the specifiedsubrange. The subrange includes lb and ub . That is,the generated value cannot be either lb or ub .

void keepOut(const tbvSignalT& v )

Further limit the values so that a value cannot be v.

void keepOut( const tbvListT<const tbvSignalT>&)

Further limit the values so that a value cannot be oneof the values in the list.

Table 5-17 tbvSignalGeneratorT::fieldManipulatorT Public Methods

fieldManipulatorT Public Methods Descriptionvoid keepOnly(const tbvSignalT& lowerbound ,const tbvSignalT& upperbound )

Same as the correspondingtbvSignalGeneratorT::keepOnly() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

void keepOnly(const tbvSignalT& v )

Same as the correspondingtbvSignalGeneratorT::keepOnly() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

void keepOnly(const tbvList<tbvSignalT>&)

Same as the correspondingtbvSignalGeneratorT::keepOnly() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

Table 5-16 tbvSignalGeneratorT Public Methods (Constraints), continued

Public Method (ConstraintsRelated) Description

June 2000 130 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

void keepOut(const tbvSignalT& lowerbound ,const tbvSignalT& upperbound )

Same as the correspondingtbvSignalGeneratorT::keepOut() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

void keepOut(const tbvSignalT& v )

Same as the correspondingtbvSignalGeneratorT::keepOut() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

void keepOut(const tbvList<tbvSignalT>&)

Same as the correspondingtbvSignalGeneratorT::keepOut() , but onlyapply the constraints to the selected bits in thefieldManipulatorT .

It is an error if a constraint exists that includes thesebits and also other bits outside this field.

void setWeightDistribution(const tbvBagT<tbvSignalT>&,bool useMarking = FALSE)

Set the weight distribution for the DISTRIBUTIONmode.

If a value in the bag does not satisfy the constraints, itis not generated. The integer value is generated by aweighted random selection over the objects in thebag.

If useMarking is false, successive generations areindependent.

If useMarking is true, successive generationsreduce the chance of generating a previouslygenerated value until all objects in the bag have beengenerated.

Table 5-17 tbvSignalGeneratorT::fieldManipulatorT Public Methods, continued

fieldManipulatorT Public Methods Description

June 2000 131 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvSignalGeneratorT Constraints Examples

The following is an example of invalid usage since the second subrange specified is outsidethe range of the first subrange specified:

tbvSignalGeneratorT random(32);

random.keepOnly("0xFF", "0xFF00");

random.keepOnly("0xEE00", "0xFFFF"); // ERROR!

The following example prints a random number within 0xFF and 0xFF00 , except 0xEEEEandbetween 0xEFF and 0xFFF.

tbvSignalGeneratorT randomSignal(32);

randomSignal.keepOnly("0xFF", "0xFF00");

randomSignal.keepOut("0xEFF", "0xFFF");

tbvListT<const char *> badValue; badValue.push("0xEEEE");

randomSignal.keepOut(badValue);

tbvOut << randomSignal.next() << endl;

The following example uses SCAN mode:

tbvSignalGeneratorT randomSignal(32);

randomSignal.setMode(tbvValueGeneratorT::SCAN);

randomSignal.setScanInterval("0xF");

for (int i=0; i<1000; ++i)

tbvOut << randomSignal.next() << endl;

// print 0, 0xF, 0x1E, 0x2D, ...

void setScanInterval(const tbvSignalT& lb ,const tbvSignalT& ub )

Change the interval setting for SCAN mode.

In scan mode, the next value is by default generatedby incrementing the previous value by 1. When thismethod is called, the difference between the nextvalue and the previous value is a random numberbetween lb and ub , inclusive. When ub < lb , theupper bound is the same as the lower bound. It is anerror if lb < 1 .

Table 5-17 tbvSignalGeneratorT::fieldManipulatorT Public Methods, continued

fieldManipulatorT Public Methods Description

June 2000 132 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Specifying Simple Constraints for Selected Bits

Using the methods discussed in this section, you can specify constraints for selected bits. Theuse model is very simple. Consider the following example:

tbvSignalGenerator gen(32);

gen(7,0).keepOnly(0x0,0xF);

gen(15,8).keepOnly(0x2F, 0x4F);

gen(31,16).keepOnly(0xFFFF);

The first call to keepOnly() is specified for bits 7 to 0, the second call is specified for bits 15to 8, and the third call is specified for bits 31 to 16. A signal generated from gen can havevalues such as 0xFFFF2F00 and 0xFFFF4F0F, but cannot have values such as0x00002F00 , 0xFFFF1000 , or 0xFFFF2F1F.

These methods are particularly useful when you are packing a complex datatype into a largesignal. See “tbvComplexGeneratorT Example” on page 135 for an example.

There are some restrictions to the use of these methods. These methods partition the signalinto a fixed set of fields, and you cannot specify constraints across fields. For example, thefollowing code will produce errors:

tbvSignalGenerator gen(32);

gen.keepOnly(0x0,0xFFFF);

gen(7,0).keepOnly(0x0,0xF); // ERROR

Or:

tbvSignalGenerator gen(32);

gen(15,0).keepOnly(0x0,0xF);

gen(23,8).keepOnly(0x0,0xF0F); // ERROR

June 2000 133 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvComplexGeneratorT Template

This template customizes a tbvSignalGeneratorT to a generator for generating acomplex value for a user-defined data type. This template is derived fromtbvSignalGeneratorT , and it has the same interface for constraints.

tbvComplexGeneratorT Template Parameters

tbvComplexGeneratorT Public Base Class

tbvSignalGeneratorT

tbvComplexGeneratorT Public Member Types

Table 5-18 tbvComplexGeneratorT Template Parameters

Template Parameter DescriptionData the type of the variables whose values are to be generated

Table 5-19 tbvComplexGeneratorT Public Member Types

Public Member Type DescriptionunpackFuncT The pointer to a function for unpacking the values from a bit

vector to the values in a variable of type Data . It is defined as:

typedef Data (*unpackFuncT)(const tbvSignal2StateT& s );

packFuncT The pointer to a function for packing the values from a variableof type Data to a bit vector. It is defined as:

typedef tbvSignal2StateT (*packFuncT)(const Data& d);

setUpFuncT The pointer to a function for initializing the generator withconstraints. It is defined as:

typedefvoid (*setUpFuncT)(tbvComplexGeneratorT<Data>& g);

June 2000 134 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

tbvComplexGeneratorT Public Methods (Main)

tbvComplexGeneratorT Example

The following example...

struct myComplexT : public tbvCstructMethodsT<myComplexT> {

int a;

int b;

};

Table 5-20 tbvComplexGeneratorT Public Methods (Main)

Public Method (Main) DescriptiontbvComplexGeneratorT(int numBits , const char * name,unsigned long seed ,packFuncT func1 ,unpackFuncT func2 ,setUpFuncT func3 = NULL)

Create a generator for Data . It is an error if func1or func2 is NULL. It is also an error if func1 andfunc2 use a tbvSignalT of more than numBitsbits.

tbvComplexGeneratorT(const tbvComplexGeneratorT&other ,const char * name = NULL,unsigned long seed = 0)

copy constructor

The name and seed of other are not copied. Youcan provide a new name and seed in the secondand third arguments.

~tbvComplexGeneratorT() destructorbool satisfyConstraints(const Data&) const

Return true if Data& satisfies the constraints.

Data next() Generate the next random value.void setWeightDistribution(const tbvBagT<Data>&,bool useMarking = FALSE)

Set the weight distribution for the DISTRIBUTIONmode.

If a value in the bag does not satisfy the constraints, itis not generated. The integer value is generated by aweighted random selection over the objects in thebag.

If useMarking is false, successive generations areindependent.

If useMarking is true, successive generationsreduce the chance of generating a previouslygenerated value until all objects in the bag have beengenerated.

June 2000 135 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

myComplexT unpackComplex(const tbvSignal2StateT& s) {

myComplexT tmp;

tmp.a = *s(15,0).getValueP();

tmp.b = *s(31,0).getValueP();

return tmp;

}

tbvSignal2StateT packComplex(const myComplexT& c) {

tbvSignal2StateT s(31,0);

s(15,0) = c.a;

s(31,16) = c.b;

return s;

}

void testComplexGenerator() {

tbvComplexGeneratorT<myComplexT> gen(32,NULL,0,packComplex,unpackComplex);

tbvOut << gen.next() << endl;

}

Specifying Type Information and Simple Constraints for tbvComplexGeneratorT

When you create a tbvComplexGeneratorT , you can specify the type information andsimple constraints for each field in the function of type setUpFuncT .

Add the following code to the previous example to change the generator to generate valuesthat satisfy the specified constraints:

void setUpComplex(tbvComplexGeneratorT<myComplexT>& gen) {

gen(15,0).keepOnly(0x1000,0x2000);

gen(31,16).keepOnly(0xFF00,0xFFFF);

}

void testConstraintedComplexGenerator() {

tbvComplexGeneratorT<myComplexT> gen(32,NULL,0,packComplex,unpackComplex,

setUpComplex);

tbvOut << gen.next() << endl;

}

In this example, gen.next() generates values for myComplexT such that field a only hasvalues within 0x1000 and 0x2000 , and field b only has values within 0xFF00 and 0xFFFF.

Note the similarity among packComplex , unpackComplex , and setUpComplex .

June 2000 136 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

Randomization Exceptions

The following table describes the exception messages you may see from the Randomizationfacility. All of these exception messages are members of the enumtbvExceptionT:: exceptionTypeT .

Table 5-21 Randomization Facility Exceptions

Message and Description

RANDOM_ALGORITHM_WARNING

You requested the use of tbvRandomT:: CUSTOM without providing a custom algorithmpointer. See “Custom Algorithm” on page 106.

RANDOM_SEED_WARNING

You have a problem with seed manipulation in the seed registry within tbvRandomT . See“Overview of the Randomization Facilities” on page 101.

Causes of such problems include (but are not limited to): seeds are retrieved from a file in anon-sequential order, the seeds cannot be retrieved with the correct name, the seeds maynot be matched to the right tbvRandomT , APIs for seed manipulation are not called in theright order.

VALUE_GENERATOR_CONSTRAINT_ERROR

You have a problem related to the constraints in tbvValueGeneratorT and its derivedclasses. See “Specifying Constraints” on page 105.

VALUE_GENERATOR_SCAN_ERROR

You specified incorrect information for the operation of tbvValueGeneratorT:: SCANmode.

VALUE_GENERATOR_DISTRIBUTION_ERROR

You specified incorrect information for the operation oftbvValueGeneratorT:: DISTRIBUTION mode.

VALUE_GENERATOR_AVOID_DUPLICATE_ERROR

You specified incorrect information for the operation oftbvValueGeneratorT:: RANDOM_AVOID_DUPLICATE mode.

VALUE_GENERATOR_PARTITION_ERROR

You specified incorrect information to partition the values generated bytbvSignalGeneratorT into a set of independent fields.

June 2000 137 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualRandomization

VALUE_GENERATOR_INTERNAL_ERROR

TestBuilder detected inconsistent internal data. If you see this kind of exception message(internal), please contact your Cadence representative to report the problem.

Table 5-21 Randomization Facility Exceptions, continued

Message and Description

June 2000 138 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

6Data Structures

This section describes the library classes for various data structures. These classes areprovided in the TestBuilder C++ library for:

■ Ease of programming a testbench

■ Hidden connection to the SST2 database, Signalscan, and TransactionExplorer

Some of the data structures are similar to the container classes provided by the C++ STL(Standard Template Library). Instead of requiring you to learn the C++ STL, we have includedand enhanced the subset that is useful for writing a transaction-based testbench. A C usercan start writing a TestBuilder testbench without learning the C++ STL.

This chapter discusses:

■ Overview of the Data Structure Classes

■ Public Common Interfaces

■ Data Structure Specifications

June 2000 139 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Data Structures Class Diagram

tbvDataStructureT

tbvPriorityQueueT<T>

tbvQueueT<T>

tbvPriorityListT<T>

tbvStringT

tbvSparseArrayT<T>

tbvBagTtbvListT<T>

tbvSmartQueueT<Key,T>

tbvAssociativeArrayT<Key,T>less<Key>

n

1

less<T> is an STL class

June 2000 140 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Overview of the Data Structure Classes

All TBV data structures (except tbvStringT ) have a common base class calledtbvDataStructureT , which defines the set of methods that every derived class mustimplement in order to connect to other tools. (The tbvStringT class is a TestBuilder stringclass that is used as a parameter to many of the data structures templates. See “tbvStringTClass” on page 157.)

Most data structures described in this chapter are container classes. That is, each datastructure is an object that stores other objects (its elements), and has methods for accessingits elements. In particular, each has an associated iterator type that can be used to iteratethrough the container’s elements. These iterators have the same interface as iterators in theC++ STL, as discussed in “Iterator Interface” on page 153.

The data structures concrete classes templates provided by the TestBuilder C++ library are:

Table 6-1 TBV Data Structures Concrete Classes Templates

Class Template DescriptiontbvStringT TestBuilder string class that is used as a parameter to many

of the data structures templates.tbvSparseArrayT An array indexed by integers, with most array elements

having the same default value.tbvAssociativeArrayT A sparse array indexed by integers, strings or data of a user-

specified high-level data type.tbvListT A doubly-linked list with iterators for accessing each

element.tbvPriorityListT A doubly-linked list with user-defined insertion arbitration.tbvStackT A LIFO queue.tbvQueueT A FIFO queue.tbvPriorityQueueT A queue with user-defined insertion arbitration.tbvSmartQueueT A set of FIFO queues. The actual queue associated with an

element is decided by a selector function.tbvBagT An enhanced multi-set: a collection of objects, possibly with

duplicates.

June 2000 141 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

The interfaces for templates tbvSparseArrayT and tbvAssociativeArrayT areintentionally designed to be similar, and the interfaces for templates tbvListT ,tbvPriorityListT , tbvStackT , tbvQueueT , and tbvPriorityQueueT areintentionally designed to be similar.

Some of these concrete classes are very similar to their corresponding classes in the C++STL. See http://www.sgi.com/Technology/STL . The templatetbvAssociativeArrayT corresponds to a map in STL; tbvListT corresponds to list ;tbvStackT , tbvQueueT , and tbvPriorityQueueT correspond to stack , queue , andpriority_queue . The data structures described in this chapter have a simplified interface,enhanced with new methods for testbench writing.

You can specify the desired insertion mechanism for both tbvPriorityListT andtbvPriorityQueueT and specify the object selection algorithm for tbvBagT . The availableoptions are defined in enum tbvDataStructureT::priorityMode .

Requirements for Template Parameters

In general, TBV data structures template parameters can be any C or C++ built-in data type.Most of the data structures templates take user-specified classes as parameters.

In most cases, a parameter declaration such as the following is sufficient:

struct myClass {

int field1;

int field2;

}

int main() {

tbvListT<myClass> a;

...

}

The remainder of this section describes cases where the above example may not besufficient. To ensure that the data structure template functions correctly, the parameters you

tbvSafeHandleT A safe handle performs reference counting for heap objectsso that multiple threads and data structures can share heapobjects without worrying about when to delete them.

Table 6-1 TBV Data Structures Concrete Classes Templates, continued

Class Template Description

June 2000 142 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

define must meet certain requirements. Please review “Using Pointers as TemplateParameters” below and “Requirements for Complex Types” on page 143.

Using Pointers as Template Parameters

Note: If you need to specify a string as a parameter, use tbvStringT instead of char* .

Be careful if you use pointers as parameters to a template:

■ Two elements are the same when the two pointers point to the same object.

■ When two pointers point to two separate objects, the two elements are not the same,even when the two objects have the same value.

For example, if you use char* to represent a string, two identical strings may beconsidered not equal because they are stored in two different memory locations.

■ Pointer elements may not print as expected:

Typically when you print a container, each element prints using the C++ operator <<.Different compilers may have different behavior when you print a pointer this way. Manycompilers print a pointer as an integer of the form 0x???? . Other compilers give adifferent result. For example, g++ 2.7.2.2, prints the pointer as 1 regardless of what thepointer is.

Requirements for Complex Types

If you use a complex type T such as a struct or class, review the requirements discussed inthis section for a copy constructor, assignment operator, equality testing operator, and printfunction.

Copy Constructor

Your C++ compiler will automatically generate a bitwise copy constructor for you. This shouldbe sufficient for most cases. If you use pointers in a struct or class, be sure bitwise copy is avalid way to copy your parameter. Otherwise, you need to supply the correct copy constructorin an override of the form:

struct myClass {

int field1;

int field2;

myClass ( const myClass& o ) {

field1 = o.field1;

field2 = o.field2;

June 2000 143 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

}

}

Assignment Operator

Your C++ compiler will automatically generate a bitwise assignment operator for you. Thisshould be sufficient for most cases. If you use pointers in a struct or class, be sure bitwiseassignment is a valid way to assign your parameter. Otherwise, you need to supply the correctassignment operator in an override of the form:

struct myClass {

int field1;

int field2;

myClass& operator=( const myClass& o ) {

field1 = o.field1;

field2 = o.field2;

return *this;

}

}

Equality Testing Operator

Some of the methods in a data structure template require equality comparison of theelements to check whether two instances of the parameter class contain the same value. Youcan use the bit compare method that is provided in tbvCstructMethodsT . To do this,declare your parameter as shown below:

struct myClass: public tbvCstructMethodsT<myClass> { ...

}

If the default bit compare behavior of this operator does not meet your needs, override it bydefining the equality comparison operator explicitly, similar to:

bool operator==(const myClass& a, const myClass& b) {

return 0==memcmp(&a,&b, sizeof(myClass));

}

Print Function

Some of the methods in a data structure template require printing the elements. You can usethe method that is provided in tbvCstructMethodsT to print a placeholder string. To dothis, declare your parameter as shown below:

struct myClass: public tbvCstructMethodsT<myClass> { ...

}

June 2000 144 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

If you need a specific print function and not just one that prints a placeholder, override theprint operator by defining it explicitly, similar to:

ostream& operator<<(ostream& os, const myClass& a) {

os << "field1:" << a.field1 << endl;

os << "field2:" << a.field2 << endl;

return os;

}

tbvCstructMethodsT

The base class that is used to enhance a user-defined C struct is:

template<myClass T>

struct tbvCstructMethodsT;

Default operators for myClass are created that provide the following operators and printfunctions:

bool operator==(const myClass&, const myClass&);

bool operator!=(const myClass&, const myClass&);

bool operator<(const myClass&, const myClass&);

bool operator>(const myClass&, const myClass&);

bool operator<=(const myClass&, const myClass&);

bool operator>=(const myClass&, const myClass&);

ostream& operator<< (ostream&, const myClass&);

The default comparison operators use a bitwise comparison to test the relationship betweenthe two instances of myClass . The default operator<< prints a placeholder string“<C-struct> ”.

If the default behavior of one of these operators does not meet your needs, override it bydefining that operator explicitly. If none of these operators meets your needs, do not usetbvCstructMethodsT ; implement all operators explicitly.

Iterators

An iterator allows you to traverse the elements in a container one by one. Typically, an iteratorcan be obtained through the following two methods in a container: begin() and end() . Thebegin() method returns an iterator that points to the first element in the list. The operator *of an iterator allows you to access the actual element. For example, the following codechanges the first element of a list to 1:

tbvListT<int> l = getList();

tbvListT<int>::iteratorT i = l.begin();

June 2000 145 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

*l = 1;

You can examine the whole set of elements in the container by using the end() method. Forexample:

tbvListT<int> l = getList();

for (tbvListT<int>::iteratorT i = l.begin(); i != l.end(); ++i)

printf(" %d ",*i); // print each element

For some containers, you can use the erase() method to remove from the container theelement that is referred to by an iterator. Typically, this is done with a while loop, as shownin the following example:

tbvListT<int> l = getList();

tbvListT<int>::iteratorT i = l.begin();

while (i != l.end()) {

if (*i == 10)

i = l.erase(i);

else

++i;

}

Note: Passing an iterator to the erase() method invalidates that iterator, since the elementis removed from the container. To reset the iterator to a valid iterator, use the return value fromerase() , as shown in the example above. The return value is an iterator that points to thenext element, so do not increment the iterator that is returned from erase() ; if you do, youwill skip an element.

Enhanced Queues and Stacks

To better handle the requirements of a testbench, some of the data structures have enhancedmethods that are not provided in the C++ STL.

In particular, the queues and stacks in the TestBuilder library have two methods calledsearch() and popUntil() . These methods are used primarily for error recovery in atestbench. If a transaction is corrupted, it may not correspond to an element in a queue. Whenthe next transaction comes along, it may correspond to an element not at the front of a queue.These methods allow you to search for a match in this case, and allow you to examinetransactions in front of such an element.

June 2000 146 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Data Structures Documentation

In the remainder of this chapter, the interfaces of the data structures are summarized intables, typically grouped as follows:

■ Parameter Type

■ Public Member Type

■ Main Public Methods

■ Extended Public Methods

■ Supporting Public Methods

June 2000 147 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Public Common Interfaces

The following sections describe:

■ tbvDataStructureT Class

■ tbvDataStructureT::priorityMode Enum

■ Iterator Interface

June 2000 148 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvDataStructureT Class

This class forms the base class for the data structure that needs hooks to the other tools.When a class is derived from this base class, the abstract methods are implemented by thederived class. This provides a consistent interface for all library data structures.

This is the base class of the templates in this chapter. It is also the base class for classtbvSignalT described in Chapter 2, “Signal Class” and for tbvRandomT andtbvValueGeneratorT described in Chapter 5, “Randomization.”

tbvDataStructureT Public Base Class

none

tbvDataStructureT Public Enum

priorityMode

tbvDataStructureT Public Methods and Friends

Table 6-2 tbvDataStructureT Public Abstract Methods

Public Abstract Method Descriptionvoid traceOn()=0 Turn on database recording.void traceOff()=0 Turn off database recording (default).void print(osteam&) const=0 Print current values on output stream.

Table 6-3 tbvDataStructureT Public Methods and Friends

Public Abstract Method Descriptionconst char * name() Get the user-specified name of this data structure.friend ostream& operator<<(ostream&,const tbvDataStructureT&);

Print current values on the output stream.

June 2000 149 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvDataStructureT Examples

Testbench Example

The following example uses a tbvDataStructureT in a testbench:

tbvQueueT<int> queue;

// tbvQueueT<int> is a derived class of tbvDataStructureT.

void initTest() {

queue.traceOn() // start database recording

}

Debug Environment Example

The following example uses a tbvDataStructureT in a debug environment:

debug> print queue.print()

June 2000 150 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvDataStructureT::priorityMode Enum

This enumeration specifies the priority mode for list-like structures with user-specifiedinsertion arbitration. It consists of the following members:

A priority list-like structure (for example, tbvPriorityQueueT ) with a FIFO mode behavesin the same way as a FIFO list-like structure (for example, tbvQueueT ), but the version usingpriority is probably less efficient. The same is true for LIFO.

Random Modes

When you specify one of the random modes (RANDOM or CUSTOM_RANDOM), the datastructure automatically registers the random generator used with the randomization facilities.Use the tbvRandomT static methods setDefaultAlgorithm() andsetSeedGenerationAlgorithm() to specify a randomization algorithm to use and torecord and restore the seed.

User-Specified Priority Function

For custom modes, you need to specify a priority function. This priority function takes twoelements as arguments; it returns a positive integer if the first element has higher priority,returns 0 if the two elements have the same priority, and returns a negative integer if the

Table 6-4 tbvDataStructureT::priorityMode Members

Member DescriptionFIFO Inserts the new element in a first-in-first-out (FIFO) manner.LIFO Inserts the new element in a last-in-first-out (LIFO) manner.RANDOM Uses a random number generator to determine the insertion point.CUSTOM_FIFO Inserts the element according to the priority determined by a user-

specified function. Two elements that have the same priority areinserted in a FIFO manner.

CUSTOM_LIFO Inserts the element according to the priority determined by a user-specified function. Two elements that have the same priority areinserted in a LIFO manner.

CUSTOM_RANDOM Inserts the element according to the priority determined by a user-specified function. Two elements that have the same priority areinserted in a random manner.

June 2000 151 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

second element has higher priority. For example, for an element type T, the type of the priorityfunction is specified as follows:

typedef int (*priorityFcnPtr)(const T&, const T&)

June 2000 152 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Iterator Interface

This section defines the interface for the iterators of the data structures described in thischapter. You do not need to know how to instantiate an iterator: An iterator can be obtainedby calling the begin() and end() methods of the corresponding data structure thatrepresents a container. However, you need to know the methods associated with an iteratorin order to use them.

In the container classes, up to two member iterator types may be defined. They are usuallycalled iteratorT and constIteratorT . Both types allow you to iterate through theelements in the container classes.

In C++, the keyword const can be used to declare that a variable cannot be modified. If acontainer is a const object, you must use constIteratorT instead of iteratorT . If acontainer is modifiable, you should use iteratorT .

iteratorT Member Type

iteratorT Public Base Class

none

iteratorT Public Methods

Table 6-5 iteratorT Member Type

iteratorT Member Type Description

value_type The type of the elements in the list.

Table 6-6 iteratorT Public Methods

Public Abstract Method DescriptioniteratorT operator++() Go to the next element (or the space after the last

element, if the current element is the lastelement).

iteratorT operator++(int) Same as above except post-increment.iteratorT operator--() Go to the previous element. If the current element

is the first element, do not change.

June 2000 153 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

iteratorT ExampletbvListT<int> l;

// tbvListT is a container class derived from tbvDataStructureT.

tbvListT<int>::iteratorT iter;

// "tbvListT<int>::iteratorT" is the iterator type for tbvListT<int>.

iter = l.begin();

// "iter" is set up to be the iterator returned by l.begin(),

// which points to the first element.

++iter;

// "iter" now points to the second element.

*iter = 3; // Changes the second element to 3.

struct packet {

// a complex user-defined data type

int srcPort;

int destPort;

};

tbvListT<packet> l2; // A list with complex elements.

tbvListT<packet>::iteratorT iter = l2.begin(); ++iter

// "iter" now points to the second element.

if (l2.size() >= 2) iter->srcPort = 3; // See Troubleshooting ->.

// Changes the srcPort of the second element to 3.

iteratorT operator--(int) Same as above except post-decrement.value_type & operator*() Return a reference to the current element.value_type * operator->() Return a pointer to the current element.

Note: See “Compiler Error on Iteratoroperator->()” in the “Troubleshooting” chapter ofthe TestBuilder User Guide.

const value_type & operator*()const

Return a const reference to the current element.

const value_type * operator->()const

Return a const pointer to the current element.

Note: See “Compiler Error on Iteratoroperator->()”.

Table 6-6 iteratorT Public Methods, continued

Public Abstract Method Description

June 2000 154 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

constIteratorT Example// Check whether any element has value 5:

bool hasFive(const tbvListT<int>& l) {

tbvListT<int>::constIteratorT i = l.begin();

while (i != l.end()) {

if (*i++==5)

return TRUE;

// Note that an assignment such as *i = 3 would be illegal,

// since i is a constIteratorT.

}

return FALSE;

}

June 2000 155 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Data Structure Specifications

The following sections describe:

■ tbvStringT Class

■ tbvSparseArrayT Template

■ tbvAssociativeArrayT Template

■ tbvListT Template

■ tbvPriorityListT Template

■ tbvStackT Template

■ tbvQueueT Template

■ tbvPriorityQueueT Template

■ tbvSmartQueueT Template

■ tbvBagT Template

■ tbvSafeHandleT Template

June 2000 156 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvStringT Class

You need to use the tbvStringT class when you want to use a string with any of the datastructure templates described in the remainder of this chapter. Use tbvStringT instead ofchar* when instantiating templates with strings. When one of the parameters of the templateneeds to be treated as a string, the usual C-style char* cannot be used because only apointer, not the string, would be manipulated by the template. Use the tbvStringT type ina parameter of a template whenever a string is intended.

tbvStringT Public Base Class

none

tbvStringT Public Methods

Table 6-7 tbvStringT Public Methods

Public Method DescriptiontbvStringT(const char *=NULL) Initialize a tbvStringT with a C-style string.

If the argument is NULL, the string is set to "".tbvStringT(const tbvStringT&) copy constructortbvStringT& operator=(const tbvStringT&)

Assign a string.

bool operator==( const tbvStringT&,const tbvStringT&)

Test for equality.

bool operator!=( const tbvStringT&,const tbvStringT&)

Test for inequality.

bool operator<( const tbvStringT&,const tbvStringT&)

Test for less than.

bool operator>( const tbvStringT&,const tbvStringT&)

Test for greater than.

bool operator<=( const tbvStringT&,const tbvStringT&)

Test for less than or equal to.

bool operator>=( const tbvStringT&,const tbvStringT&)

Test for greater than or equal to.

const char * c_str() Convert to a C-style string with type char* .void print(ostream& =cout) const Print to an output stream.friend ostream& operator<<( ostream&,const tbvStringT&)

Print to an output stream.

June 2000 157 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSparseArrayT Template

A sparse array is an efficient implementation of a large array indexed by a range of integers,when most of the elements have the same default value (for example, 0 or undefined).

tbvSparseArrayT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvSparseArrayT Public Base Class

tbvDataStructureT

tbvSparseArrayT Public Member Types

Each iterator element is of type pair<int,T> so that if i is an iterator of atbvSparseArrayT , then i->first returns the index of the current element, andi->second returns the element that corresponds to the current index.

See “tbvSparseArrayT Example” on page 159 for the usage of these member types.

Table 6-8 tbvSparseArrayT Template Parameters

Template Parameter DescriptionT The type of the array elements.

Table 6-9 tbvSparseArrayT Public Member Types

Public Member Type DescriptioniteratorT Iterator type for accessing and modifying non-default

elements.constIteratorT A const version of iteratorT for accessing non-

default elements.

June 2000 158 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSparseArrayT Public Methods (Main)

tbvSparseArrayT Example

The following example...

tbvSparseArrayT<int> sa("my_array",0);

sa[454] = 10;

sa[458] = sa[454] + 100;

Table 6-10 tbvSparseArrayT Public Methods (Main)

Public Method (Main) DescriptiontbvSparseArrayT( const char * name,const T& defaultValue ,int indexLB = 0,int indexUB = INT_MAX)

Create a sparse array with default valuedefaultValue . It is indexed by a range ofintegers specified by indexLB andindexUB . Use NULL for name if don’t care.

~tbvSparseArrayT() destructorT& operator[](int i ) Allocate storages for element i , and return a

reference to the storage. If i is out-of-bounds,a warning is issued and the default value isreturned. Modifying the object referred to doesnot effect the array.

const T& operator[](int i ) const Return a const reference for element i . Nonew storage is allocated. If i is out-of-bounds,a warning is issued and the default value isreturned.

void erase(int i ) Free up the storage for element i , if allocated.Element i now has value defaultValue .

void clear() Clear all elements to the default valueiteratorT begin() Return an iterator that points to the explicit

element with the smallest index.iteratorT end() Return an iterator that points to the explicit

element with the largest index.constIteratorT begin() const Return a const iterator that points to the

explicit element with the smallest index.constIteratorT end() const Return a const iterator that points to the

explicit element with the largest index.

June 2000 159 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

// at this point we have memory allocated for two elements

// with "sa[454]=10, sa[458]==110, sa[others]==0"

sa.erase(454);

// at this point we have memory allocated for one elements

// with "sa[458]==110, sa[others]==0"

for (tbvSparseArrayT<int>::iteratorT iter = sa.begin(); iter != sa.end(); ++iter) {

int i = iter->first; // index — See Troubleshooting ->.

int e = iter->second; // element

}

sa.clear();

tbvSparseArrayT Public Methods (Supporting)

Table 6-11 tbvSparseArrayT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvSparseArrayT(const tbvSparseArrayT&)

copy constructor

tbvSparseArrayT& operator=(const tbvSparseArrayT&)

assignment

friend bool operator==(const tbvSparseArrayT&,const tbvSparseArrayT&)

equality testing

friend bool operator!=(const tbvSparseArrayT&,const tbvSparseArrayT&)

inequality testing

int indexLB() const Return the lower-bound of valid indices.int indexUB() const Return the upper-bound of valid indices.const T& defaultValue() const Return the default value for the elements.bool hasNonDefaultElt() const Return TRUE if any element has a non-default

value (expensive).int numNonDefaultElt() const Return the number of elements that have non-

default values (expensive).bool hasExplicitElt() const Return TRUE if an explicit memory buffer has

been allocated to any of the array elements.int numExplicitElt() const Return the number of explicit memory buffers

allocated to array elements.

June 2000 160 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvAssociativeArrayT Template

An associative array is an array indexed by integers, strings, or high-level data types. It canbe perceived as a sparse array with indices being strings or high-level data types instead ofintegers. However, the index is never out-of-bounds, and different optimizations in theimplementation may be used. Two similar classes, mapand hash_map , are in the STL. Theinterface defined here reflects the decision that template tbvAssociativeArrayT will beimplemented using a map.

tbvAssociativeArrayT Template Parameters

The following is a requirement for Key, in addition to the requirements given in “Requirementsfor Template Parameters” on page 142:

■ A less than operator:

operator<(const Key&, const Key&)

The requirements for Data are given in “Requirements for Template Parameters” onpage 142.

tbvAssociativeArrayT Public Base Class

tbvDataStructureT

tbvAssociativeArrayT Public Member Types

Table 6-12 tbvAssociativeArrayT Template Parameters

Template Parameter DescriptionKey the type of the indicesData the type of the array elements

Table 6-13 tbvAssociativeArrayT Public Member Types

Public Member Type DescriptioniteratorT Iterator type for accessing and modifying non-default

elements.

June 2000 161 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Each iterator element is of type pair<Key,Data> so that if i is an iterator of atbvAssociativeArrayT , then i->first returns the key for the current element, andi->second returns the current array element. See “tbvAssociativeArrayT Example” onpage 163.

tbvAssociativeArrayT Public Methods (Main)

constIteratorT A const version of iteratorT for accessing non-default elements.

Table 6-14 tbvAssociativeArrayT Public Methods (Main)

Public Method (Main) DescriptiontbvAssociativeArrayT(const char * name,const Data& defaultValue )

Create an associative array with default valuedefaultValue .

~tbvAssociativeArrayT() destructorData& operator[](const Key& k ) Allocate storages for an element

corresponding to k , and return a reference tothe storage.

const Data& operator[](const Key& k )const

Return a const reference for elementcorresponding to k . No new storage isallocated.

void erase(const Key& k ) Free up the storage for element k , if allocated.Element k now has value defaultValue .

void clear() Clear all elements to the default value.iteratorT begin() Return an iterator that points to the first

element. The ordering may change arbitrarilywhen other methods are called.

iteratorT end() Return an iterator that points to the lastelement. The ordering may change arbitrarilywhen other methods are called.

constIteratorT begin() Return a const iterator that points to the firstelement.

Table 6-13 tbvAssociativeArrayT Public Member Types, continued

Public Member Type Description

June 2000 162 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvAssociativeArrayT Example

In the following example...

struct packet {

int srcPort;

int destPort;

}

tbvAssociativeArrayT<packet,int> aa("array",0);

for (int i=0;i<100; ++i) {

packet p = getPacket();

aa[p]++;

}

// At this point, the number of occurrences of each packet are

// counted, and the values are stored in the corresponding entry

// in "aa".

int max = 0;

packet p2;

for (tbvAssociativeArrayT<packet,int>::iteratorT iter = aa.begin();

iter != aa.end(); ++aa){

if (iter->second > max) {

max = iter->second; // See Troubleshooting ->.

p2 = iter->first;

}

}

// At this point, the most frequent packet is stored in p2.

constIteratorT end() Return a const iterator that points to the lastelement.

Table 6-14 tbvAssociativeArrayT Public Methods (Main), continued

Public Method (Main) Description

June 2000 163 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvAssociativeArrayT Public Methods (Supporting)

Table 6-15 tbvAssociativeArrayT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvAssociativeArrayT(const tbvAssociativeArrayT&)

copy constructor

tbvAssociativeArrayT& operator=(const tbvAssociativeArrayT&)

assignment

friend bool operator==(const tbvAssociativeArrayT&,const tbvAssociativeArrayT&)

equality testing

friend bool operator!=(const tbvAssociativeArrayT&,const tbvAssociativeArrayT&)

inequality testing

const Data& defaultValue () const Return the default value of the elements.bool hasNonDefaultElt() const Return TRUE if any element has a non-default

value (expensive).int numNonDefaultElt() const Return the number of elements that have non-

default values (expensive).bool hasExplicitElt() const Return TRUE if an explicit memory buffer has

been allocated to any of the array elements(expensive).

int numExplicitElt() const Return the number of explicit memory buffersallocated to array elements (expensive).

June 2000 164 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvListT Template

A TBV list is a doubly linked list that supports:

■ Forward and backward traversal.

■ Amortized constant time insertion.

■ Removal of elements at the beginning, the end, or the middle of the list.

tbvListT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvListT Public Base Class

tbvDataStructureT

tbvListT Public Member Type

See “tbvListT Example” on page 167 for the usage of these member types.

Table 6-16 tbvListT Template Parameters

Template Parameter DescriptionT the type of the list elements

Table 6-17 tbvListT Public Member Types

Public Member Type DescriptioniteratorT Iterator type for accessing and modifying list elements.constIteratorT A const version of iteratorT for accessing list elements.

June 2000 165 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvListT Public Methods (Main)

Table 6-18 tbvListT Public Methods (Main)

Public Method (Main) DescriptiontbvListT(const char * name=NULL) Create an empty list.~tbvListT(); destructorT& front() Return a reference to the front element. It is an

error if the list is empty.const T& front() const Return a const reference to the front element.

It is an error if the list is empty.T& back() Return a reference to the back element. It is

an error if the list is empty.const T& back() const Return a const reference to the back element.

It is an error if the list is empty.bool empty() const Return TRUE if it is an empty list.int size() const Return the number of elements in the list.void pushFront(const T&) Add to the front of the list.void pushBack(const T&) Add to the back of the list.void popFront() Remove the front element of the list. It is an

error if the list is empty.void popBack() Remove the back element of the list. It is an

error if the list is empty.void remove(const T&) Remove all elements of the same values as

the argument.void clear() Remove all elements.iteratorT begin() Return an iterator pointing to the front

element.iteratorT end() Return an iterator pointing to the space past

the back element.constIteratorT begin() const Return a const iterator pointing to the first

element.constIteratorT end() const Return a const iterator pointing to the space

past the last element.

June 2000 166 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvListT Example

The following example...

tbvListT<int> L; // The list is empty.

L.pushBack(0); // The list is (0).

L.pushFront(1); // The list is (1,0).

L.insert(++L.begin(), 2); // The values in the list are 1 2 0.

tbvListT Public Methods (Supporting).

iteratorT insert( iteratorT pos ,const T&)

Add the argument to the current position thatpos points to.

For example, if pos == begin() , theargument is added to the front.

If pos == end() , the argument is added tothe back. The returned iterator points to thenew element.

iteratorT erase(iteratorT pos ) Remove the current element at pos from thelist. It is an error if pos does not point to avalid element. The returned iterator points tothe next element. The argument passed to thismethod becomes invalid and should not beused after this.

Table 6-19 tbvListT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvListT(const tbvListT&) copy constructortbvListT& operator=(const tbvListT&)

assignment

friend bool operator==(const tbvListT&, const tbvListT&)

equality testing

friend bool operator!=(const tbvListT&, const tbvListT&)

inequality testing

Table 6-18 tbvListT Public Methods (Main), continued

Public Method (Main) Description

June 2000 167 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityListT Template

A priority list is a doubly linked list, supporting insertion and removal of elements. Theordering of the elements in the list is determined by the elements’ priorities. The highestpriority element is located at the front of the list, and the lowest priority element is located atthe back of the list. Elements with the same priority are arranged according to the specifiedtbvDataStructureT::priorityMode .

Modification of elements within the list is forbidden, since the modification may change itspriority. To modify an element, remove the element, modify it, and then reinsert it.

tbvPriorityListT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

Public Base Class

tbvDataStructureT

tbvPriorityListT Public Member Types

See “tbvPriorityListT Example” on page 171 for the usage of these member types.

Table 6-20 tbvPriorityListT Template Parameters

Template Parameter DescriptionT the type of the list elements

Table 6-21 tbvPriorityListT Public Member Types

Public Member Type DescriptionpriorityFcnPtr A pointer to a function for comparing the priority of

two list elements. See “User-Specified PriorityFunction” on page 151.

constIteratorT Const iterator type for accessing list elements.

June 2000 168 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityListT Public Methods (Basic)

Table 6-22 tbvPriorityListT Public Methods (Basic)

Public Method (Basic) DescriptiontbvPriorityListT(const char * name = NULL,tbvDataStructureT::priorityMode mode =FIFO_CUSTOM,priorityFcnPtr customPriority = NULL,unsigned long seed = 0)

Create an empty priority list using mode asthe priority mode, seed as the seed for therandom generator (if applicable), andcustomPriority as the user-specifiedpriority function (if applicable). If moderequires a user-specified priority function andcustomPriority is NULL, all elements areregarded as the same priority. If seed is 0, arandom seed is generated.

~tbvPriorityListT(); destructorconst T& front() const Return a const reference to the front element.

It is an error if the list is empty.const T& back() const Return a const reference to the back element.

It is an error if the list is empty.bool empty() const Return TRUE if it is an empty list.iteratorT erase(iteratorT pos ) Remove the current element at pos from the

list. It is an error if pos does not point to avalid element. The returned iterator points tothe next element. The argument passed to thismethod becomes invalid and should not beused after this.

int size() const Return the number of elements in the list.void push(const T&) Add to the list according to its priority.void popFront() Remove the front element of the list. It is an

error if the list is empty.void popBack() Remove the back element of the list. It is an

error if the list is empty.void remove(const T&) Remove all elements of the same values as

the argument.void clear() Remove all elements.

June 2000 169 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityListT Public Methods (Extended)

constIteratorT begin() const Return a const iterator pointing to the firstelement.

constIteratorT end() const Return a const iterator pointing to the spacepast the last element.

Table 6-23 tbvPriorityListT Public Methods (Extended)

Public Method (Extended) DescriptionconstIteratorT topPriorityBegin() const Return a const iterator to the list of

elements with the same priority as the frontelement.

constIteratorT topPriorityEnd() const Return a const iterator pointing to thespace past the last element with the samepriority as the front element.

int topPrioritySize() const Return the number of elements with thesame priority as the front element.

constIteratorT leastPriorityBegin() const Return a const iterator to the list ofelements with the same priority as the backelement.

constIteratorT leastPriorityEnd() const Return a const iterator pointing to thespace past the last element with the samepriority as the back element.

int leastPrioritySize() const Return the number of elements with thesame priority as the back element.

constIteratorT samePriorityBegin(const T&) const

Return a const iterator to the list ofelements with the same priority as theargument.

constIteratorT samePriorityEnd(const T&)const

Return a const iterator pointing to thespace past the last element with the samepriority as the argument.

Table 6-22 tbvPriorityListT Public Methods (Basic), continued

Public Method (Basic) Description

June 2000 170 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityListT Example

In the following example...

struct packet {

int packetPriority;

int srcPort;

}

int packetPriority(const packet& a, const packet& b) {

if (a.packetPriority > b.packetPriority) return 1;

else return a.packetPriority < b.packetPriority;

}

tbvPriorityListT<packet> L("my_list",

tbvDataStructureT::FIFO_CUSTOM,

packetPriority);

// the list is empty

packet p1 = getPacket(); p1.packetPriority = 3;

L.push(p1); // the list is (p1)

packet p2 = getPacket(); p2.packetPriority = 10;

L.push(p2); // the list is (p2,p1)

packet p3 = getPacket(); p3.packetPriority = 3;

L.push(p3); // the list is (p2,p1,p3)

int samePrioritySize(const T&) const Return the number of elements with thesame priority as the argument.

void popTopPriority() Remove the elements with the samepriority as the front element. It is an error ifthe list is empty.

void popLeastPriority() Remove the elements with the samepriority as the back element. It is an error ifthe list is empty.

void removeSamePriority(const T&) Remove all elements of the same priorityas the argument.

Table 6-23 tbvPriorityListT Public Methods (Extended), continued

Public Method (Extended) Description

June 2000 171 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityListT Public Methods (Supporting).

The copy constructor and the assignment operator copy everything except the seed (ifapplicable) for the random modes. The copy constructor has a second argument that allowsyou to specify a seed. If the seed is not provided, a random seed is generated using therandomization facilities.

Table 6-24 tbvPriorityListT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvPriorityListT(const tbvPriorityListT&,unsigned long seed = 0)

copy constructor

tbvPriorityListT& operator=(const tbvListT&)

assignment

friend bool operator==(const tbvPriorityListT&,const tbvPriorityListT&)

equality testing

friend bool operator!=(const tbvPriorityListT&,const tbvPriorityListT&)

inequality testing

June 2000 172 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvStackT Template

A stack is a last in, first out (LIFO) data structure that supports insertion, removal, andinspection of the element at the top of the stack. The element at the top of a stack is the onethat was most recently added.

The template tbvStackT does not support iteration through its elements. If you need thisfunctionality, use template tbvListT .

tbvStackT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvStackT Public Base Class

tbvDataStructureT

tbvStackT Public Methods (Main)

Table 6-25 tbvStackT Template Parameters

Template Parameter DescriptionT the type of the list elements

Table 6-26 tbvStackT Public Methods (Main)

Public Method (Main) DescriptiontbvStackT(const char * name = NULL,int initStorageSize = 100)

Create an empty stack, with storage forinitStorageSize elements allocatedinitially.

~tbvStackT(); destructorT& top() Return a reference to the front element. It is an

error if the stack is empty.const T& top() const Return a const reference to the front element.

It is an error if the stack is empty.bool empty() const Return TRUE if it is an empty stack.

June 2000 173 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Search

The search() method is typically used in error recovery in a transaction-based testbench.If a transaction is corrupted, it may not correspond to an element in a stack. When the nexttransaction comes along, it may correspond to an element not at the front of a stack. Thismethod allows the search for a match in this case, and allows examination of thosetransactions in front of such an element.

The following example prints the elements from e to the top of the stack:

for (tbvStackT::constIteratorT i = stack.search(e);

i != stack.end();

i++) {

i->print();

}

int size() const Return the number of elements in the stack.void push(const T&) Add to the front of the stack.void pop() Remove the front element of the stack. It is an

error if the stack is empty.void clear() Remove all elements.constIteratorT search(const T& e)const

Search for element e. If e is not found, returnthe iterator that points to the top of the stack(the same as the iterator returned by end() ).If e is found, return an iterator that points at e.To access the other elements between e andthe top of the stack, increment this iterator untilend() . See the example below.

void popUntil(const T& e) Remove all entries in front of element e. If e isnot found, then the selected stack is emptied.To avoid emptying the stack, use this methodin conjunction with search() .

constIteratorT begin() const Return a const iterator that points to theexplicit element with the smallest index.

constIteratorT end() const Return a const iterator that points to theexplicit element with the largest index.

Table 6-26 tbvStackT Public Methods (Main), continued

Public Method (Main) Description

June 2000 174 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

The tbvStackT::popUntil() method pops the list that was printed by the loop shownabove.

tbvStackT Public Methods (Supporting).

tbvStackT Example

The following simple example creates a TBV stack, adds three elements to it, and thenremoves each of the three elements:

tbvStackT<int> S;

S.push(8); S.push(7); S.push(4);

assert(S.size() == 3); assert(S.top() == 4);

// The stack contains three elements, and

// the value of the top element is 4.

S.pop(); assert(S.top() == 7);

S.pop(); assert(S.top() == 8);

// The stack contains one element, and

// the value of the top element is 8.

S.pop(); assert(S.empty());

// The stack is empty.

Table 6-27 tbvStackT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvStackT(const tbvStackT&) copy constructortbvStackT& operator=(const tbvStackT&)

assignment

friend bool operator==(const tbvStackT&, const tbvStackT&)

equality testing

friend bool operator!=(const tbvStackT&, const tbvStackT&)

inequality testing

June 2000 175 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvQueueT Template

A queue is a first in, first out (FIFO) data structure: Elements are added to the back of thequeue and may be removed from the front.

tbvQueueT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvQueueT Public Base Class

tbvDataStructureT

tbvQueueT Public Methods (Main)5

Table 6-28 tbvQueueT Template Parameters

Template Parameter DescriptionT the type of the queue elements

Table 6-29 tbvQueueT Public Methods (Main)

Public Method (Main) DescriptiontbvQueueT(const char * name = NULL,int initStorageSize = 100)

Create an empty queue, with storage forinitStorageSize elements allocatedinitially.

~tbvQueueT(); destructorT& front() Return a reference to the front element. It is an

error if the queue is empty.const T& front() const Return a const reference to the front element.

It is an error if the queue is empty.T& back() Return a reference to the back element. It is

an error if the queue is empty.const T& back() const Return a const reference to the back element.

It is an error if the queue is empty.

June 2000 176 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Search

The search() method is typically used in error recovery in a transaction-based testbench.If a transaction is corrupted, it may not correspond to an element in a queue. When the nexttransaction comes along, it may correspond to an element not at the front of a queue. Thismethod allows the search for a match in this case, and allows examination of thosetransactions in front of such an element.

The following example prints the elements from the front to e:

tbvQueueT::constIteratorT ei = queue.search(e);

if (ei != queue.end()) {

++ei;

bool empty() const Return TRUE if it is an empty queue.int size() const Return the number of elements in the queue.void push(const T&) Add to the back of the queue.void pop() Remove the front element of the queue. It is

an error if the queue is empty.void clear() Remove all elements.constIteratorT search(const T& e)const

Search for element e. If e is not found, returnthe iterator that points to the back of thecontainer (the same as the iterator returned byend() ). If e is found, return an iterator thatpoints at e. To access the other elementsbetween e and the front of the queue,increment the iterator returned by begin() .See the example below.

void popUntil(const T& e) Remove all entries in front of element e. If e isnot found, then the selected queue is emptied.To avoid emptying the queue, use this methodin conjunction with search() .

constIteratorT begin() const Return a const iterator that points to theexplicit element with the smallest index.

constIteratorT end() const Return a const iterator that points to theexplicit element with the largest index.

Table 6-29 tbvQueueT Public Methods (Main), continued

Public Method (Main) Description

June 2000 177 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

for (tbvQueueT::constIteratorT i = queue.begin();

i != ei;

i++) {

i->print();

}

}

The tbvQueueT::popUntil() method pops the list that was printed by the loop shownabove.

tbvQueueT Public Methods (Supporting).

tbvQueueT Example

The following example...

tbvQueueT<int> Q;

Q.push(8); Q.push(7); Q.push(6); Q.push(2);

assert(Q.size() == 4); assert(Q.back() == 2); assert(Q.front() == 8);

Q.pop(); assert(Q.front() == 7);

Q.pop(); assert(Q.front() == 6);

Q.pop(); assert(Q.front() == 2);

Q.pop(); assert(Q.empty());

Table 6-30 tbvQueueT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvQueueT(const tbvQueueT&) copy constructortbvQueueT& operator=(const tbvQueueT&)

assignment

friend bool operator==(const tbvQueueT&, const tbvQueueT&)

equality testing

friend bool operator!=(const tbvQueueT&, const tbvQueueT&)

inequality testing

June 2000 178 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityQueueT Template

A priority queue provides insertion of elements and inspection and removal of the topelement. It is guaranteed that the top element is the element with the highest priority.

tbvPriorityQueueT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvPriorityQueueT Public Base Class

tbvDataStructureT

tbvPriorityQueueT Public Member Types

Table 6-31 tbvPriorityQueueT Template Parameters

Template Parameter DescriptionT the type of the queue elements

Table 6-32 tbvPriorityQueueT Public Member Types

Public Member Type DescriptionpriorityFcnPtr A pointer to a function for comparing the priority of

two list elements. See “User-Specified PriorityFunction” on page 151.

constIteratorT An iterator for accessing individual elements.

June 2000 179 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityQueueT Public Methods (Basic)

Table 6-33 tbvPriorityQueueT Public Methods (Basic)

Public Method (Basic) DescriptiontbvPriorityQueueT(const char * name = NULL,tbvDataStructureT::priorityMode mode =FIFO_CUSTOM,priorityFcnPtr customPriority = NULL,unsigned long seed = 0,int initStorageSize = 100)

Create an empty priority queue using mode asthe priority mode, seed as the seed forrandom generator (if applicable), andcustomPriority as the user-specifiedpriority function (if applicable). It is an error ifmode requires a user-specified priorityfunction and customPriority is NULL. Ifseed is 0, a random seed is generated. Thenumber of elements allocated initially isinitStorageSize .

~tbvPriorityQueueT(); destructorconst T& front() const Return a const reference to the front element.

It is an error if the queue is empty.const T& back() const Return a const reference to the back element.

It is an error if the queue is empty.bool empty() const Return TRUE if it is an empty queue.int size() const Return the number of elements in the queue.void push(const T&) Add to the queue according to its priority.void popFront() Remove the front element of the queue. It is

an error if the queue is empty.void popBack() Remove the back element of the queue. It is

an error if the queue is empty.void clear() Remove all elements.constIteratorT search(const T& e)const

Search for element e. If e is not found, returnthe iterator that points to the back of thecontainer (the same as the iterator returned byend() ). If e is found, return an iterator thatpoints at e. To access the other elementsbetween e and the front of the queue,increment the iterator returned by begin() .See the example below.

June 2000 180 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Search

The search() method is typically used in error recovery in a transaction-based testbench.If a transaction is corrupted, it may not correspond to an element in a queue. When the nexttransaction comes along, it may correspond to an element not at the front of a queue. Thismethod allows the search for a match in this case, and allows examination of thosetransactions in front of such an element.

The following example prints the elements from the front to e:

tbvPriorityQueueT::constIteratorT ei = queue.search(e);

if (ei != queue.end()) {

++ei;

for (tbvPriorityQueueT::constIteratorT i = queue.begin();

i != ei;

i++) {

i->print();

}

}

The tbvPriorityQueueT::popUntil() method pops the list that was printed by the loopshown above.

tbvPriorityQueueT Public Methods (Extended)

void popUntil(const T& e) Remove all elements with higher priority thanelement e. This method is typically used inconjunction with search() .

Table 6-34 tbvPriorityQueueT Public Methods (Extended)

Public Method (Extended) DescriptionconstIteratorTtopPriorityBegin() const

Return a const iterator to the list of elements with thesame priority as the front element.

constIteratorT topPriorityEnd()const

Return a const iterator pointing to the space past thelast element with the same priority as the frontelement.

Table 6-33 tbvPriorityQueueT Public Methods (Basic), continued

Public Method (Basic) Description

June 2000 181 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvPriorityQueueT Public Methods (Supporting).

tbvPriorityQueueT Example

The following example...

struct packet {

int packetPriority;

int srcPort;

}

int topPrioritySize() const Return the number of elements with the same priorityas the front element.

constIteratorTleastPriorityBegin() const

Return a const iterator to the list of elements with thesame priority as the back element.

constIteratorTleastPriorityEnd() const

Return a const iterator pointing to the space past thelast element with the same priority as the backelement.

int leastPrioritySize() const Return the number of elements with the same priorityas the back element.

void popTopPriority() Remove the elements with the same priority as thefront element.

void popLeastPriority() Remove the elements with the same priority as theback element.

Table 6-35 tbvPriorityQueueT Public Methods (Supporting)

Public Method (Supporting) DescriptiontbvPriorityQueueT(const tbvPriorityQueueT&)

copy constructor

tbvPriorityQueueT& operator=(const tbvPriorityQueueT&)

assignment

friend bool operator==(const tbvPriorityQueueT&,const tbvPriorityQueueT&)

equality testing

friend bool operator!=(const tbvPriorityQueueT&,const tbvPriorityQueueT&)

inequality testing

Table 6-34 tbvPriorityQueueT Public Methods (Extended), continued

Public Method (Extended) Description

June 2000 182 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

int packetPriority(const packet& a, const packet& b) {

if (a.packetPriority > b.packetPriority) return 1;

else return a.packetPriority < b.packetpriority;

}

tbvPriorityQueueT<packet> q("my_queue",

tbvDataStructureT::FIFO_CUSTOM,

packetPriority);

// the queue is empty

packet p1 = getPacket(); p1.packetPriority = 3;

q.push(p1); // the list is (p1)

packet p2 = getPacket(); p2.packetPriority = 10;

q.push(p2); // the list is (p2,p1)

packet p3 = getPacket(); p3.packetPriority = 3;

q.push(p3); // the list is (p2,p1,p3)

June 2000 183 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSmartQueueT Template

Conceptually, a SmartQueue is similar to an associative array of FIFO queues. Given aninteger, a string, or a piece of data of a high-level data type, you can select a queue from theSmartQueue. You can also look at the list of elements at the front of the queues.

tbvSmartQueueT Template Parameters

The following is a requirement for Key, in addition to the requirements given in “Requirementsfor Template Parameters” on page 142:

■ A less than operator:

operator<(const Key&, const Key&)

The requirements for T are given in “Requirements for Template Parameters” on page 142.

tbvSmartQueueT Public Base Class

tbvDataStructureT

tbvSmartQueueT Public Member Types

Table 6-36 tbvSmartQueueT Template Parameters

Template Parameter DescriptionKey the key to select a FIFO queueT the type of the elements in the queues

Table 6-37 tbvSmartQueueT Public Member Types

Public Member Types DescriptionselectorFcnPtr The type of a function pointer to generate a key from an

element, defined as the following typedef:

typedef const Key& (*selectorFcnPtr)(const T&)

frontIteratorT An iterator that points to the explicit element with thesmallest index.

June 2000 184 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSmartQueueT Public Methods (Main)

constFrontIteratorT A const iterator that points to the explicit element with thesmallest index.

backIteratorT An iterator that points to the explicit element with the largestindex.

constBackIteratorT A const iterator that points to the explicit element with thelargest index.

constSearchIteratorT A const iterator type for accessing and modifying anelement. See the search() method below.

Table 6-38 tbvSmartQueueT Public Methods (Main)

Public Method (Main) DescriptiontbvSmartQueueT(const char * name=NULL,selectorFcnPtr selector ,int initStorageSize = 100)

Create an empty SmartQueue, with storage forinitStorageSize elements allocated for eachnew member queue. The selector is a functionpointer for selecting a queue index from an element.

~tbvSmartQueueT() destructorT& front(const Key&) Return the front element (if one exists) from the

queue corresponding to a key. The iterator has eitherone or zero elements.

T& back(const Key&) Return the back element (if one exists) from thequeue corresponding to a key. The iterator has eitherone or zero elements.

const T& front(const Key&) const Return the front element (if one exists) from thequeue corresponding to a key. The iterator has eitherone or zero elements.

const T& back(const Key&) const Return the back element (if one exists) from thequeue corresponding to a key. The iterator has eitherone or zero elements.

bool empty() const Return TRUE if all the queues are empty.int size() const Return the total number of elements in the queues.

Table 6-37 tbvSmartQueueT Public Member Types, continued

Public Member Types Description

June 2000 185 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

int size(const Key&) const Return the number of elements in the queuecorresponding to a key.

int numNonEmptyQueues() const Return the number of non-empty queues. Thisnumber is the same as the number of front elementsor the same as the number of back elements.

void push(const T&) Add the argument to one of the queues selected bythe selector function.

void pop() Remove the front elements.void pop(const Key&) Remove the front element of the queue that

corresponds to a Key.void clear() Remove all elements.constSearchIteratorTsearch(const T& e) const

Search for element e. If e is not found, return theiterator that points to the back of the internal queuethat corresponds to the key of e (the same as theiterator returned by end(e) ). If e is found, return aniterator that points at e. To access the other elementsbetween e and the front of the internal queue thatcorresponds to the key of e, increment this iteratoruntil end(e) . See the example below.

void popUntil(const T& e) Remove all entries in front of element e. If e is notfound, then the selected queue is emptied. To avoidemptying the queue, use this method in conjunctionwith search() .

frontIteratorT frontBegin() Return an iterator for the beginning of the list of frontelements.

frontIteratorT frontEnd() Return an iterator for the end of the list of frontelements.

constFrontIteratorT frontBegin()const

Return a const iterator for the beginning of the list offront elements.

constFrontIteratorT frontEnd()const

Return a const iterator for the end of the list of frontelements.

backIteratorT backBegin() Return an iterator for the beginning of the list of backelements.

Table 6-38 tbvSmartQueueT Public Methods (Main), continued

Public Method (Main) Description

June 2000 186 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Search

The search() method is typically used in error recovery in a transaction-based testbench.If a transaction is corrupted, it may not correspond to an element in a queue. When the nexttransaction comes along, it may correspond to an element not at the front of a queue. Thismethod allows the search for a match in this case, and allows examination of thosetransactions in front of such an element.

The following example prints the elements from e to the top of the queue.

tbvSmartQueueT::constSearchIteratorT ei = queue.search(e);

if (ei != queue.end(e)) {

++ei;

for (tbvSmartQueueT::constSearchIteratorT i = queue.begin(e);

i != ei;

i++) {

i->print();

}

}

The tbvSmartQueueT::popUntil() method pops the list that was printed by the loopshown above.

backIteratorT backEnd() Return an iterator for the end of the list of backelements.

constBackIteratorT backBegin()const

Return a const iterator for the beginning of the list ofback elements.

constBackIteratorT backEnd()const

Return a const iterator for the end of the list of backelements.

constSearchIteratorT begin(const T& e) const

Return an iterator for the front of the internal queuethat corresponds to the key of e.

constSearchIteratorT end(const T& e) const

Return an iterator for the end of the internal queuethat corresponds to the key of e.

Table 6-38 tbvSmartQueueT Public Methods (Main), continued

Public Method (Main) Description

June 2000 187 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSmartQueueT Public Methods (Supporting).

tbvSmartQueueT Example

The following example...

struct packet {

int srcPort;

int destPort;

};

int select_srcPort(const packet& p) {

return p.srcPort;

}

tbvSmartQueueT<int,packet> sq("my_smart_queue",select_srcPort);

// Create a SmartQueue, in which packets with the same srcPort are

// maintained in a FIFO manner.

packet p1 = getPacket(); p1.srcPort = 1; sq.push(p1);

packet p2 = getPacket(); p2.srcPort = 1; sq.push(p2);

packet p3 = getPacket(); p3.srcPort = 2; sq.push(p3);

tbvSmartQueueT<int,packet>::frontIteratorT f_iter;

for (f_iter = sq.frontBegin(); f_iter != sq.frontEnd(); ++f_iter)

tbvOut << *f_iter << endl;

// p1 and p3 are printed onto the screen.

tbvSmartQueueT<int,packet>::backIteratorT b_iter;

for (b_iter = sq.backBegin(); b_iter != sq.backEnd(); ++b_iter)

tbvOut << *b_iter << endl;

// p2 and p3 are printed onto the screen.

Table 6-39 tbvSmartQueueT Public Methods (Supporting)

Public Methods (Supporting) DescriptiontbvSmartQueueT(const tbvSmartQueueT&)

copy constructor

tbvSmartQueueT& operator=(const tbvSmartQueueT&)

assignment

friend bool operator==(const tbvSmartQueueT&,const tbvSmartQueueT&)

equality testing

friend bool operator!=(const tbvSmartQueueT&,const tbvSmartQueueT&)

inequality testing

June 2000 188 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvOut << sq.front(1) << endl;

// p1 is printed onto the screen

June 2000 189 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvBagT Template

A bag is a collection of objects, where two objects may look exactly the same (as in a set).You can add multiple copies of an object to a bag. You have random access to the objects ina bag, and you can associate a count with each object. You can iterate through the bag toexamine its contents. You can mark and unmark objects in a bag to avoid repeated access tothe same object. The bag facility is a basic building block of random test generation.

tbvBagT Template Parameters

The requirements for T are given in “Requirements for Template Parameters” on page 142:

tbvBagT Public Base Class

tbvDataStructureT

tbvBagT Public Methods

Table 6-40 tbvBagT Template Parameters

Template Parameter DescriptionT the type of the list elements

Table 6-41 tbvBagT Public Methods

Public Method DescriptiontbvBagT(const char * nameP=NULL,unsigned long seed =0)

Constructor for tbvBagT . Create a bag withname nameP and seed seed for the randomnumber generator. The random numbergenerator uses the class tbvRandomT togenerate a positive integer, which is used toselect an unmarked element from the bag.

tbvBagT(const tbvBagT& other ,const char * nameP=NULL)

Copy constructor for tbvBagT . Create a bagwith name nameP and initialize it with thecontents of the other bag.

tbvBagT& operator=(const tbvBagT& other )

Copy the contents of the other bag to thecurrent bag.

June 2000 190 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

~tbvBagT() destructorvoid add(const T& e, int count =1) Add count elements e of type T to the bag. It

takes O(1) time to add an element to the bag.

See “Entries in a Bag” on page 193 for adiscussion of storing and accessing elementsand entries in a bag.

int size() const Return the total number of elements in the bag.For example, if you call add(e1,3) andadd(e2,2) , size() returns 5.

int uSize() const Return the total number of unmarked copies ofelements in the bag. If there are 2 unmarkedcopies of e1 and 1 unmarked copy of e2 in thebag, uSize() returns 3.

int mSize() const Return the total number of marked copies ofelements in the bag. The following equality isalways true:

uSize() + mSize() == size()

int dSize() const Return the number of entries in a bag.

See “Entries in a Bag” on page 193 for adefinition of entry.

bool empty() const Return TRUE if size()== 0 .const T& peekRandom(bool mark =FALSE) Return a reference to an unmarked element of

type T. The unmarked element is selected by arandom number between 0 and uSize() .

Set an internal flag so that validPeek() isnow TRUE.

If you set mark to TRUE, then the peeked itemis marked.

const T& peekRandom() const Return a reference to an unmarked element oftype T. The unmarked element is selected by arandom number between 0 and uSize() .

Set an internal flag so that validPeek() isnow TRUE.

Table 6-41 tbvBagT Public Methods, continued

Public Method Description

June 2000 191 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

void resetPeek() const Reset the internal peek iterator so that asubsequent call to peekNext() returns the firstelement in the bag. Set an internal flag so thatvalidPeek() is now FALSE.

const T& peekNext(char eType = ‘a’,bool distinct = FALSE) const

Return a constant reference to an object next tothe one returned by a previous call to eitherpeekRandom() or peekNext() .

Set an internal flag so that validPeek() isnow TRUE.

See “Peeking at Elements in a Bag” onpage 194 for explanations of eType anddistinct .

void remove(bool AllCopies = FALSE) If validPeek() is TRUE, remove the lastelement returned by peekNext() orpeekRandom() .

Set an internal variable so that validPeek() isnow FALSE.

If you set AllCopies to TRUE, all copies ofthe element are removed from this entry in thebag. See the example in “Entries in a Bag” onpage 193.

void mark(bool AllCopies = FALSE) Mark the last element returned by peekNext()or peekRandom() . If AllCopies is TRUE,mark all copies of the element in this entry of thebag. A marked element is not returned whenyou call peekRandom() .

void unMark(bool AllCopies = FALSE) Unmark the last element returned bypeekNext() or peekRandom() . IfAllCopies is TRUE, unmark all copies of theelement in this entry of the bag.

void markAll() Mark the entire bag. After this call, the equalitymSize()==size() is TRUE.

void unmarkAll() Unmark the entire bag.

Table 6-41 tbvBagT Public Methods, continued

Public Method Description

June 2000 192 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

Entries in a Bag

A tbvBagT consists of entries of value/quantity pairs. Each add() call results in a separateentry in the bag, even if the value added is the same as the value added to this bag with aprevious add() call. Each value in an entry is an element in the bag. The size() ,uSize() , mSize() , peekRandom() , peekNext() , remove() , mark() , and unMark()methods operate on elements in a bag. The add() , dSize() , remove(1) , mark(1) ,unMark(1) , and count() methods operate on entries in a bag. ThepeekNext( eType ,1) method skips to an element in the next entry of the bag. ThemarkAll() , unmarkAll() , and clear() methods operate on the entire bag.

void clear() Remove all copies of all elements from the bag.After this call, the equality size()==0 is TRUE.

bool validPeek() const Return TRUE after a call to peekNext() orpeekRandom() .

Return FALSE after a call to remove() orresetPeek() .

const T& peek() const If validPeek() is TRUE, return the lastelement returned by peekNext() orpeekRandom() .

If validPeek() is FALSE, return an error.print(ostream& os ) Print the contents of the bag to output stream

os .operator<<(ostream& os ,tbvBagT& bag )

Print the contents of the bag to the outputstream os .

const int& count() const If validPeek() is TRUE, return the number ofcopies of the peeked element in that entry of thebag. See the examples in “Entries in a Bag”below.

friend bool operator==(const tbvBagT& bag1 ,const tbvBagT& bag2 )

Return TRUE if bag1 and bag2 are equal.

bool operator!=( const tbvBagT& bag ,other )

Return TRUE if bag and other are not equal.

Table 6-41 tbvBagT Public Methods, continued

Public Method Description

June 2000 193 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

If you add the same value to a bag multiple times using separate add() calls, each additionresults in a separate entry in the bag: Additions of the same value are not combined into asingle entry. For example, you may have a bag of integers and add elements as shown below:

tbvBagT<int> b;

b.add(0,5); b.add(1,10); b.add(0,15); b.add(1,20);

In this example, you have twenty elements with value 0 and thirty elements with value 1, butthese elements are in four entries in the bag, not two. If you call size() on this bag, thereturn value is 50 (elements); if you call dSize() on this bag, the return value is 4 (entries).

If you call peekNext() and then call count() , the return value is 5. If you callpeekNext(‘a’,1) and then call count() , the return value is 10. If you then callremove(1) , ten elements with value 1 are removed from the bag. If you then call mark(1) ,fifteen elements with value 0 are marked. If you then call peekNext(‘u’) , an element withvalue 1 is returned. If you then call peekNext(‘a’,1) , an element with value 0 (an elementfrom the next entry) is returned.

Peeking at Elements in a Bag

If you call resetPeek() and then call peekNext() , the first element in the bag isreturned. Subsequent calls iterate through the bag so that size() calls to peekNext()eventually return all elements in a bag. Subsequent calls to peekNext() start returning thesame set of elements again.

If you set eType to ‘u’ , peekNext() returns the next unmarked element. If you seteType to ‘m’ , peekNext() returns the next marked element. If eType is set to ‘a’ (thedefault value), peekNext() returns the next element.

Making mSize() calls to peekNext(‘m’) returns all marked objects in the bag, and makinguSize() calls to peekNext(‘u’) returns all unmarked objects in the bag. Subsequentcalls to peekNext() start returning the same set of marked or unmarked elements again.

If distinct is TRUE, an element from the next entry in the bag is returned. See “Entries ina Bag” above.

tbvBagT Examples

The following examples add objects to a bag and then peek at them, print and mark objects,and conditionally mark and print objects.

Example 1. Add and Peek at Objects

tbvBagT<int> b; // The bag is empty, with random peeking.

b.add(0,50); b.add(1,30); b.add(2,20); // There are 100 objects in the bag.

June 2000 194 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

int i = b.peekRandom();

// There is a 50 percent chance of selecting value 0,

// a 30 percent chance of selecting value 1, and

// a 20 percent chance of selecting value 2.

Example 2. Print and Mark Objects

while (b.mSize() <= 100)

tbvOut << b.peekRandom(true) << endl;

// Print 50 copies of 0, 30 copies of 1, and 20 copies of 2 in random order.

Example 3. Conditionally Mark and Print Objects

int i = -1;

while (b.mSize() <= 20) {

i = b.peekRandom();

if (i > 0) {

b.mark();

tbvOut << i << ‘\n’;

// Mark and print 20 of the 100 objects whose value is 1 or 2.

}

}

June 2000 195 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSafeHandleT Template

The tbvSafeHandleT template allows you to share data among multiple threads. A testmay generate hundreds of threads before it terminates.

Any data structures declared as local variables in the test are destroyed when the testterminates. Such structures are not suitable for sharing among the threads.

A data structure can be declared on the heap by calling new. However, once the testterminates, it is unclear which thread will call delete to reclaim the memory when all thethreads are done. A safe handle helps address this problem. A safe handle is a handle withautomatic reference counting so that even when multiple C++ threads share the underlyingobject, the system knows when to destroy the underlying object and reclaim the memory.

tbvSafeHandleT Public Base Class

tbvDataStructureT

tbvSafeHandleT Template Parameters

tbvSafeHandleT Public Methods

Table 6-42 tbvSafeHandleT Template Parameters

Template Parameter DescriptionT The type of the shared objects.

Table 6-43 tbvSafeHandleT Public Methods

Public Method DescriptiontbvSafeHandleT(T * core = NULL) Constructor. The core argument is a pointer to

the shared object. Make sure that no other codeis accessing the underlying object exceptthrough safe handles. For example:

tbvSafeHandleT<tbvIntQueueT> myQueue(newtbvIntQueueT("my integer queue",100);

tbvSafeHandleT(const tbvSafeHandleT<T>&)

copy constructor

~tbvSafeHandleT() destructor

June 2000 196 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

tbvSafeHandleT Examples

One typical use of tbvSafeHandleT objects is for memory management when you usethrow and catch .

When an exception is thrown, the following code does not delete the object packet from theheap:

try {

myPacket * packet = new myPacket;

...

delete packet;

} catch (tbvExceptionT& e) {

...

}

Instead, use a local variable, as shown below:

try {

myPacket packet;

...

} catch (tbvExceptionT& e) {

...

}

tbvSafeHandleT& operator=(const tbvSafeHandleT&)

Assign a safe handle.

T& operator*() Get a shared object with the appropriate type.const T& operator*() const Get a shared constant object with the

appropriate type.T* operator->() Get a shared object pointer with the appropriate

type.const T* operator->() const Get a shared constant object pointer with the

appropriate type.bool operator==(const tbvSafeHandleT&,const tbvSafeHandleT&)

Test for equality.

bool operator!=(const tbvSafeHandleT&,const tbvSafeHandleT&)

Test for inequality.

Table 6-43 tbvSafeHandleT Public Methods, continued

Public Method Description

June 2000 197 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

When you need to have the queue on the heap, use a tbvSafeHandleT object:

try {

tbvSafeHandleT< myPacket > packet(new myPacket);

...

} catch (tbvExceptionT& e) {

...

}

To access the element in the underlying object, use operator* and operator-> , as shownbelow (see “Compiler Error on Iterator operator->()” in the “Troubleshooting” chapter of theTestBuilder User Guide):

packet->address = 3;

*packet = queue.front();

A tbvSafeHandleT object used as shown above is sometimes referred as an auto pointeror a smart pointer.

Another way to use a tbvSafeHandleT object is to share data among multiple C++ threads,as shown below:

struct myPacketT {

int address;

int dataA;

int dataB;

}

class myArgT : public tbvTaskContextT {

public:

tbvSafeHandleT<myPacketT> packet;

...

}

void myTest() {

// Set up packet to be shared by multiple threads.

tbvSafeHandle< myPacketT > packet(new myPacket);

packet->address = 0xFFFF; // See Troubleshooting ->.

packet->dataA = 0x1F;

packet->dataB = 0x2F;

// Set up a local argument to be passed to related threads.

// Turn on auto copy, so that myTest() can terminate before the children

// terminate.

June 2000 198 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualData Structures

// Each thread will have its own copy of the arguments,

// which is a safe handle to the same packet.

myArgT arg(packet);

arg.setAutoCopy(true);

// Two spawned tasks may read/modify the same packet concurrently.

// The packet will be deleted from the heap when both threads terminate.

myTvm1.readDataA.spawn(&arg);

myTvm1.readDataB.spawn(&arg);

}

June 2000 199 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

7TestBuilder Miscellaneous Facilities

This chapter discusses important facilities provided in TestBuilder that do not fit into the otherchapters in this manual:

■ TestBuilder Stream Class: tbvOut

■ Exiting TestBuilder: tbvExit()

■ TestBuilder Exceptional Condition Handling

TestBuilder Stream Class: tbvOut

TestBuilder has a stream object called tbvOut that sends text to both the HDL simulator logfile and standard out.

Use tbvOut exactly the same way that you use the built-in C++ object cout . The onlydifference is that tbvOut also puts the output into the Verilog log file. For example:

tbvOut << "Hello" << endl;

tbvSignal4StateT s4_8(7,0);

tbvOut << s4_8 << endl;

Exiting TestBuilder: tbvExit()

TestBuilder includes a function called tbvExit() to end Verilog simulation. The functionlooks like this:

tbvExit(int exitCode = 0)

This function prints a warning that tbvExit() has been called, and then it calls the finishfunction for the HDL simulator, tf_dofinish() . TestBuilder and the simulation exit,returning the exitCode as a status. The simulator finish function calls the end of simulationcallback that TestBuilder has registered, and, as a result, TestBuilder TVMs and threads aredeleted as their destroy functions are called.

June 2000 200 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

TestBuilder Exceptional Condition Handling

TestBuilder includes an exception handling class and API for user-defined exceptionhandling. Use this mechanism to control the actions that TestBuilder takes when any of thefollowing exceptional conditions occur:

■ An incorrect argument value is passed to a TestBuilder API call.

■ An incorrect sequence of TestBuilder API calls occurs.

■ An internal TestBuilder error occurs.

When one of the above occurs, the default TestBuilder actions are:

1. Print the error/warning message to stdout and append it to the simulation log file.

2. Assure the integrity of internal TestBuilder data structures.

3. Return to the calling code. If the API method or function that was executing when theexception occurred returns a value, then check the description of that method or functionin this manual for the returned value for an exceptional condition.

The TestBuilder exception handling facility includes two classes:

Use the tbvExceptionT class to customize the actions that TestBuilder takes when it findsan exceptional condition.

Use the tbvExceptionEnvironmentT class to “push” a new TestBuilder exceptionsettings environment. When your tbvExceptionEnvironmentT object is deleted, theTestBuilder exception settings revert to the “popped” settings environment.

tbvExceptionT Class

The tbvExceptionT class has static methods that you can use to enable and suppresserror and warning messages.

You can also enable a C++ style throw from TestBuilder for any or all exception types.TestBuilder wraps a try /catch around the call to tbvMain() , and also around the body ofa task after it has been spawned. You also can insert try /catch around your own code.

When TestBuilder does a throw , it throws a tbvExceptionT object in which members havebeen set to appropriate values that depend on the condition.

If the throw is caught in your catch , then you can take appropriate action, such as reportingthe error, exiting, or resuming.

June 2000 201 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

If the throw is caught in a TestBuilder catch because you did not have a try /catch wherethe exception occurred, then TestBuilder will print the message and then terminate.

The tbvExceptionT class also provides methods you can use to add your own messages,which can be informative, warnings, or errors, to the TestBuilder exception condition facility.Your message types are specified as strings, rather than as TestBuilder built-in enums.

tbvExceptionT enum Types

Table 7-1 tbvExceptionT enum Types

Public Member Type Descriptionenum severityLevelT {

MESSAGE,

WARNING,

ERROR

};

The kind of message.

enum exceptionTypeT {

ALL_USER_EXCEPTIONS,

ALL_USER_MESSAGES,

ALL_USER_WARNINGS,

ALL_USER_ERRORS,

ALL_EXCEPTIONS,

ALL_MESSAGES,

ALL_WARNINGS,

ALL_ERRORS

// and facility-specific

// exceptions

};

The kind of exception.

See also “TVMs, Tasks, and Fibers Exceptions” onpage 98 and “Randomization Exceptions” onpage 137.

enum exceptionResponseT {

NONE_SPECIFIED,

ENABLE_MESSAGE,

SUPPRESS_MESSAGE,

THROW

};

The response that TestBuilder makes when anexception occurs.

June 2000 202 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

tbvExceptionT Public Methods

The following methods allow you to add your own messages to the TestBuilder exceptionhandling facility. Your user-defined messages are referenced by using char* strings.

Table 7-2 tbvExceptionT Public Methods

Public Method Descriptionstatic void setExceptionResponse(exceptionResponseT=ENABLE_MESSAGE,exceptionTypeT = ALL_EXCEPTIONS)

Use setExceptionResponse() to specify theactions for TestBuilder to take on a specifiedexception.

See “Using setExceptionResponse()” onpage 205 for more information on how to use thesetExceptionResponse() method.

static exceptionResponseTgetExceptionResponse(exceptionTypeT, severityLevelT)

Return what the response would be if thespecified exception occurred with the specifiedseverity level.

static voidsetUserExceptionTypeString(const char* _userExceptionTypeStringP ,exceptionResponseT_exceptionResponse =ENABLE_MESSAGE,severityLevelT _severityLevelT =MESSAGE)

Add your own exception type to the TestBuilderexception handling facility.

static voidsetUserExceptionResponse(exceptionResponseT_exceptionResponse , const char* _userExceptionTypeStringP )

Use setUserExceptionResponse() tospecify what TestBuilder will do when you report amessage of the specified user-defined exception.

static exceptionResponseTgetUserExceptionResponse(const char* _userExceptionTypeStringP )

Return what the response would be if thespecified user-defined exception occurred.

static void reportUserMessage(char * userMessageP ,char * messageStringP )

Use reportUserMessage() to indicate anexceptional condition in your code. TestBuilderresponds with the response you specified for thisparticular user-defined message usingsetUserExceptionResponse() .

June 2000 203 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

static void reportUserException(const char* _userExceptionTypeStringP ,const char * _messageStringP , ...)

Use reportUserException() to indicate anexceptional condition in your code. TestBuilderresponds according to theexceptionResponseT setting of the specifieduser-defined exception type string. If you did notpreviously callsetUserExceptionTypeString() to first addthe _userExceptionTypeStringP toTestBuilder, then the exceptionResponseT isNO_EXCEPTION_SPECIFIED, theseverityLevelT is MESSAGE, and TestBuildersends your message to tbvOut() . The_messageStringP argument and theva_args variable number of arguments thatfollow it are similar to arguments for printf() .

const char*getUserExceptionTypeStringP()

If the exceptionTypeT for this object isALL_USER_MESSAGES, ALL_USER_WARNINGS,or ALL_USER_ERRORS, then you can call thismethod to get the user-defined exception string.

static void setMessageLimit(int max, severityLevelT = WARNING)

TestBuilder exits when more than the specifiedmax number of messages of the specifiedseverity level have been enabled.

void reportMessage() Put the severity message and message string intostdout and the log file.

severityLevelT getServerityLevel();

exceptionTypeT getExceptionType();

char *getMessage()

Return the severity level, exception type, andmessage string for this exception object.

static const char*getSeverityLevelStringP(severityLevelT _severityLevel )

Return the string equivalent of the given severitylevel enum.

static const char*getExceptionTypeStringP(exceptionTypeT _exceptionType )

Return the string equivalent of the given exceptiontype string.

const char *getMessageStringP() Return the message string.

Table 7-2 tbvExceptionT Public Methods, continued

Public Method Description

June 2000 204 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

Using setExceptionResponse()

Calls to setExceptionResponse() are cumulative. If you use:

setExceptionResponse(THROW, UNKNOWN_TVM);

setExceptionResponse(THROW, UNCONNECTED_TVM_PORT);

Then TestBuilder will do a throw if either condition occurs.

To cause TestBuilder to do a throw on all exceptions, use:

setExceptionResponse(THROW, ALL_EXCEPTIONS);

To cause TestBuilder to never do a throw, you should enable or suppress messages. Thedefault TestBuilder setting is:

setExceptionResponse(tbvException::ENABLE_MESSAGE,

tbvException::ALL_EXCEPTIONS);

To suppress messages, use:

setExceptionResponse(tbvException::SUPPRESS_MESSAGE,

tbvException::ALL_EXCEPTIONS);

You can make calls to setExceptionResponse() at the beginning of simulation, in yourtbvInit() function.

tbvExceptionEnvironmentT Class

To customize your exception handling within a scope and then return to the previous settings,declare an object of class tbvExceptionEnvironmentT . (You are not permitted to new atbvExceptionEnvironmentT object.) This establishes a new error handling environment.

void enableAllMessages() Use enableAllMessages() to override anysettings that disable message reporting. Use thisas a debugging aid to enable you to see allmessages, regardless of anysetExceptionResponse() calls. If you havespecified that a throw will be done for anyexceptions, then TestBuilder first outputs themessage and then executes the throw.

Table 7-2 tbvExceptionT Public Methods, continued

Public Method Description

June 2000 205 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference ManualTestBuilder Miscellaneous Facilities

After you declare a tbvExceptionEnvironmentT object, calls totbvExceptionT::setExceptionResponse apply to the new environment.

The new error environment that is entered after you declare atbvExceptionEnvironmentT object inherits all error settings from the previousenvironment. Additional settings in the new environment override inherited settings, andthese settings also propagate down into any new subordinate error environments.

When a new TestBuilder process thread is spawned, TestBuilder declares a newtbvExceptionEnvironmentT object at the spawn of the process thread. (Thus, this newenvironment has inherited the error environment in effect where the spawn was made.)

tbvExceptionEnvironmentT Public Methods

When the destructor for tbvExceptionEnvironmentT is called, which can happen whenyour tbvExceptionEnvironmentT object goes out of scope or when a throw is done,then the previous TestBuilder exception settings are restored.

Table 7-3 tbvExceptionEnvironmentT Public Methods

Public Method DescriptiontbvExceptionEnvironmentT(); constructor~tbvExceptionEnvironmentT(); destructor

June 2000 206 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

Index

Symbols$tbv_main() 10$tbv_task_add_arg() 12$tbv_task_decl() 12$tbv_task_decl_done() 13$tbv_task_done() 13$tbv_task_set_arg_format() 10, 13$tbv_task_trigger() 12$tbv_tvm_connect() 9, 43

Aactive threads 69arg block

task argument blockSee task context object,

tbvTaskContextT, tbvProfileTargTypeT 87arrays 141

associative 161sparse 158

Bbags 190barriers 47, 49begin() 145

Ccatch 197children 45, 46collections 141, 190collections of resources 58concurrency 36

see also threadsconstraints 85, 90, 101, 102

checking 93specifying 105

container classes 141convertXZ() 28counters 52

cout 200CPU

simulator 71threads 71

Ddata structures 139, 149

classes 141database recording 149debug environment examples 150descendants 45, 46DISTRIBUTION mode 116

Eedge detection 39edges 39, 56

see also tbvThreadT, edgeT enumend() 145erase() 146examples

debug environment 150testbench 150Verilog 13

exception handlingenvironment 205throw 201

exception messagesrandomization 137TVMs 98

exiting simulation 200

Ffibers 82, 85, 96fieldManipulatorT 127, 129

public methods 130FIFO_PRIORITY 47from2To4State() 28

June 2000 207 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

GgetArbitration() 38, 44, 47getAutoCopy() 95getChildren() 46getFiberP() 83getNameP() 37getNumDescendants() 46getParent() 46getPriority() 45getSignal() 129getStackSize() 44getStatus() 45getTvmByInstanceName() 82getTvmByInstanceNameP() 82

Hhandles 196

see also tbvSafeHandleThash_map 161

Iiterators 145, 153, 158, 159, 161, 162, 165,

166, 168, 170, 174, 177, 181, 184,186

begin() 145end() 145erase() 146iterator types 141operator * 145

Jjrand48() 106, 108

KkeepOnly() 105, 122, 126, 132keepOut() 105, 122, 126, 132kill() 40, 45, 71

Llinked lists 141, 165

priority ordering 168lists 142

insertion mechanism 142priority mode 151

lsb 127, 129

Mmap 142, 161memory management 197msb 127, 129msbExtend() 23multithreading 36mutexes 47, 53

Nnames

getNameP() 37NBA 55, 56

non-blocking assignmentnext() 129

Oobjects

collections 190optimizations 161output

writing text output 200

Pparents 46pointers

auto pointer 198smart pointer 198

popUtil() 146postAll() 52priority function, custom 151priority mode 142, 151

see also tbvDataStructureT, priorityModepriority_queue 142

June 2000 208 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

profiles 84, 85, 87, 92, 93, 99, 102, 105setting 84, 93

Qqueues 141, 142, 146, 176

insertion mechanism 142priority ordering 179priority_queue 142smart queues 184

Rrand() 106random value generation

modes 116changing on the fly 117

random value generators 101see also tbv*GeneratorTconstraints 121, 123, 126, 129

RANDOM_AVOID_DUPLICATEmode 116

randomizationDISTRIBUTION mode 116exception messages 137RANDOM_AVOID_DUPLICATE

mode 116SCAN mode 116, 117

register() 70release() 61, 63, 64, 66resources

collections 58shared 58unshared 58

SsatisfyConstraints() 120, 124, 128, 135SCAN mode 116, 117, 125, 129, 132search() 146see also bagsseed file 109seeds

file 109getSeed() 111initial 103, 107matching to generators 103monitoring 103, 110

printSeeds() 109, 110seedMonitorOff() 109seedMonitorOn() 109, 110setSeedGenerationAlgorithm() 108setting 111

semaphores 47, 51counters 52

setArbitration() 38, 44, 47setAutoCopy() 95setDefaultAlgorithm() 106, 151setDuplicateDistance() 125setExceptionResponse() 203setPriority() 45sets 190setScanInterval() 121, 123, 125, 126, 129,

132setSeedGenerationAlgorithm() 103, 107,

151setStackSize() 44setUpFuncT 134, 136setWeightDistribution() 116, 121, 124,

128, 131, 135severityLevelT 202shared resources 58sigDirT enum 19, 31signal values

handler functions 70signals

assigning 22bit selects 23class 16efficiency 19HDL 19initial value 18naming 18operators 19

size of the operands 23range of indices 18read-only 19types 17widths 22write-only 19

Signalscan 37, 139simulator

control of CPU 71smart queues 184spawn() 41, 44, 45, 84

compile-time type checking 72type-safe 72, 85

SST2 database 139stack size 44

June 2000 209 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

stacks 142, 146, 173standard template library

See STLSTL 139, 141, 142, 146, 161

Standard Template Libraryhash_map 161list 142map 142, 161priority_queue 142queue 142stack 142

strings 143, 157see also tbvStringT

synchronization 47

Ttask context object 84, 85, 87, 88, 92, 96

automatic copy and delete 95duplicate() 95getAutoCopy() 95setAutoCopy() 95size 90

tasks 83arguments 87, 92profiles 87type-safe invoking 85

TBV 7$tbv_main() 10$tbv_task_add_arg() 12$tbv_task_decl() 12$tbv_task_decl_done() 13$tbv_task_done() 13$tbv_task_set_arg_format() 10, 13$tbv_task_trigger() 12$tbv_tvm_connect() 9, 43tbvAssociativeArrayT 141, 161tbvBagT 141, 190

object selection algorithm 142priorityMode 142

tbvBarrierT 49public methods 49wait() 49

tbvComplexGeneratorT 101, 134setWeightDistribution() 135

tbvCstructMethodsT 144tbvDataStructureT 101, 141, 149

priorityMode 142, 151tbvEnumsT

sigDirT 88

sigDirT enum 19, 31tbvEventT 58tbvExceptionEnvironmentT 201, 205tbvExceptionT 201tbvExit() 200tbvFiberT 82, 85, 96tbvGetWaiters() 47tbvGetWaiters(tbvEventT) 58tbvGetWaiters(tbvSignalHdlT) 55, 56tbvGetWaiters(tbvTimeT) 57tbvIntGeneratorT 101, 120

setWeightDistribution() 121tbvListT 40, 55, 141, 165tbvMain() 201tbvMutexT 53

lock() 53, 54public methods 53unlock() 53

tbvOut 200tbvPriorityListT 141, 168

priorityMode 142tbvPriorityQueueT 141, 179

priorityMode 142tbvProfileArgAssocArrayT 91tbvProfileT 87

argTypeT 87, 88setArgFormat() 13, 90

tbvQueueT 141, 176tbvRandomT 151

See also seedscustom algorithms 106setAlgorithm() 111setDefaultAlgorithm() 108setting algorithms 111setting seeds 111

tbvRealGeneratorT 101, 124setWeightDistribution() 124

tbvSafeHandleT 102tbvSemT 51

post() 52public methods 51wait() 52

tbvSignal2StateT 87tbvSignal4StateT 17, 24, 25, 28

public methods 30, 40tbvSignalArray4StateT

public methods 33tbvSignalArrayHdlT

public methods 33tbvSignalArrayT

public methods 32

June 2000 210 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

tbvSignalGeneratorT 101, 127, 134fieldManipulatorT 127setWeightDistribution() 128, 131

tbvSignalHdlT 18, 19, 25, 55public methods 30

tbvSignalT 16, 17, 127, 129, 135, 149public methods 24

tbvSmartQueueT 141, 184tbvSparseArrayT 141, 158tbvSpawnNoArgFunctionT 73, 75tbvSpawnNoArgMethodT 73, 76tbvSpawnOneArgFunctionT 73, 75tbvSpawnOneArgMethodT 73, 77tbvSpawnTwoArgFunctionT 73, 76tbvSpawnTwoArgMethodT 78tbvStackT 141, 173tbvStringT 143, 157tbvTaskContextT 43, 91, 92, 96

automatic copy and delete 95tbvTaskGroupT 91tbvTaskT 83

automatic copy and delete of args 96spawn() 45, 84, 96

tbvTaskTypeSafeT 85tbvThreadT

arbFuncT 40, 49, 51, 53arbModeT 38, 47doubleArgT 42edgeT 55edgeT enum 39, 56kill() 40, 45, 71public methods 40singleArgT 42spawn() 41, 42, 45statusT enum 39waitAllThreads() 41, 69, 71waitChildren() 41, 45, 69, 71waitDescendants() 41, 45, 69yield() 41, 45, 71

tbvTimeT 57tbvTvmT 43, 81tbvValueGeneratorT 101, 114

generatorModeT 101, 116SCAN mode 125, 129, 132setWeightDistribution() 116

tbvWait() 71tbvWait(tbvEventT) 57tbvWait(tbvThreadT) 42tbvWait(tbvTimeT) 57tbvWaitAllSharedT 59, 71tbvWaitAllUnsharedT 59, 71

release() 63tbvWaitAnyHybridT 59, 71

release() 64tbvWaitAnySharedT 59, 71tbvWaitAnyUnsharedT 59, 71

release() 66tbvWaitCycle() 55, 71tbvWaitEvent() 55, 56, 71tbvWatcherT 70

register() 70Type enum 70

testbench examples 150tests

suspending 45tf_dofinish() 200thread lists

ordering 38, 47priority 38

threading package 44see also threads and tbvThreadTeffectiveness 69

threadssee also tbvThreadTactivating 45, 52active 69, 72children 45, 46controlling 45creating 45delayed spawning 69descendants 45, 46edges 39, 56killiing 45multithreading 36parents 46priority 38, 45retaining/losing the CPU 71scheduler 45sharing data 198simulator events 55spawning C functions 42spawning TVM tasks 42stack size 44status 39, 45suspend until event 57suspend until signal change 55suspend until thread count 69suspend until time 57suspending 45, 47synchronizing 47, 49watching for conditions 70

throw 197, 201

June 2000 211 Product Version 1.10

Transaction-Based Verification: TestBuilder Reference Manual

Transaction Explorer 139Transaction-Based Verification

See TBVtryWait() 52TVMs 9

exception messages 98type checking 72type-safe spawning 72type-safe task invocation 85

Uunshared resources 58

Vvalue generators

constraints 120, 124, 128, 135valueGenerationAlgorithmT 108values

handler functions 70

Wwait

complex wait 67simple wait 67

wait() 69waitAllThreads() 41, 69, 71waitChildren() 41, 45, 69, 71waitCycle() 60waitDescendants() 41, 45, 69waitEvent() 60warning messages

enabling and suppressing 201watching for conditions 70

Yyield() 41, 45, 71

ZzeroExtend() 23

June 2000 212 Product Version 1.10