verification presentation 1

178
Verification Training Tuesday, Ma rch 15, 202 2 Verification Methodology System Verilog Fundamentals

Upload: hoa

Post on 09-Sep-2015

16 views

Category:

Documents


0 download

DESCRIPTION

Verification presentation

TRANSCRIPT

System Verilog

Verification Training7 April 2015Verification Methodology

System Verilog FundamentalsContentVerification MethodologyData types, procedural statements and routines in System VerilogBasic OOP and connecting test bench to the DUTSystem Verilog Assertion SVARandomization in System VerilogAdvanced OOP, thread and inter process communication2Dolphin Technology Inc.Methodology, Data types, Procedural statements and Routines 7 April 2015ContentVerification Methodology

System Verilog Fundamentals Data types Procedural statements and routines4Dolphin Technology Inc.Verification Methodology

ASIC designFunctional verification needTest benchSelf-checking test benchDoes a design work and how is it done?Code coverageFunctional coverageCoverage driven constraint random verification architectureVerification plan and phases of verification5Dolphin Technology Inc.ASIC design6Dolphin Technology Inc.

Physical DesignPhysical design process includes logic partitioning, floor planning, global routing, detailed routing, compaction, and performance-driven layout. PD team transforms net list representation of a system into layout representation.Timing AnalysisStatic timing analysis is an important step in analyzing the performance of a design. In the Timing analysis Setup time, hold time ,recovery time ,removal time , Clock latency, clock skew, clock uncertainty etc checks are done.TapeoutThis is the final stage of the design cycle of integrated circuits. Once all the checks are done, the design is ready to be sent to Foundry.6Functional verification need7Dolphin Technology Inc.Why we need functional verification?To build confidence and stay in business.A primary purpose for functional verification is to detect failures so that bugs can be identified and corrected before it gets shipped to costumer.

Linear Testbench. + Instantiate the design under test (DUT) + Stimulate the DUT by applying test vectors. + Output results waveform window or to a terminal for visual inspection manually.Flat testbenh: they probably looked like the low-level code, all in one file.Layered testbench : dividing the code into smaller pieces

Testbench

Self-checking test bench

Code coverageStatement coverage: also known as line coverage. This is required to be 100% for every project. Block coverage: The block coverage considers branched blocks of if/else, case branches, wait, while, for etc. Conditional coverage: also called as expression coverage, will reveals how the variables or sub-expressions in conditional statements are evaluated. Brand coverage: reports the true or false of the conditions like if-else, case and the ternary operator (? :) statements in every branch.Code coverage (Cont)Path coverage is considered to be more complete than branch coverage because it can detect the errors related to the sequence of operations.Analysis of path coverage report is not so easy task.

Code coverage (Cont)Toggle coverage: It makes assures that how many times variables and nets toggled.FSM coverage: It is the most complex type of code coverage. We look for how many times states are visited, transited and how many sequence are covered in a Finite state machine.SystemVerilog provides a mechanism to know the untested feature using functional coverage.Summary of functional coverage advantages:+ Functional coverage helps determine how much of your specification was covered.+ Functional coverage qualifies the testbenchs.+ Considered as stopping criteria for unit level verification.+ Gives feedback about the untested features.+ Gives the information about the redundant tests which consume valuable cycle.+ Guides to reach the goals earlier based on grading.Functional coverage

SystemVerilog provides a mechanism to know the untested feature using functional coverage.Summary of functional coverage advantages:+ Functional coverage helps determine how much of your specification was covered.+ Functional coverage qualifies the testbenchs.+ Considered as stopping criteria for unit level verification.+ Gives feedback about the untested features.+ Gives the information about the redundant tests which consume valuable cycle.+ Guides to reach the goals earlier based on grading.Coverage driven constraint random14Dolphin Technology Inc.

Coverage driven constraint random Generators create inputs at a high level of abstraction namely, as transactions like read write operation. The drivers convert this input into actual design inputs, as defined in the specification of the designs interface.Monitor reports the protocol violation and identifies all the transactions.Scoreboard is sometimes referred as tracker. Scoreboard stores the expected DUT output.Environment contains the instances of all the verification component.15Dolphin Technology Inc.Phases of verification16Dolphin Technology Inc.

Verification Plan The Verification Plan is the focal point for defining exactly what needs to be tested, and drives the coverage criteria.Verification Plan Contains The Following:OverviewResources, Budget and ScheduleVerification EnvironmentSystem Verilog Verification FlowFeature ExtractionStimulus Generation PlanChecker PlanCoverage PlanDetails of reusable components17Dolphin Technology Inc.4-state and 2-state data types4 state data type: (0,1,X,Z)Logic , wire . . . Interger, time . . . 2 state data type: (0,1)Byte, shortint, int, longint, bit . . .Signed and unsigned18Dolphin Technology Inc.Fixed-Size ArraysDeclaring:int fix_arr1[0:15]bit fix_arr2[7:0][3:0] bit fix_array3[8][4]

Packed vs Unpacked

PackedUnpacked19Dolphin Technology Inc.

Fixed-Size ArraysInitializing:int fixed_arr[5];fixed_arr = {0,1,2,3,4};fixed_arr[0:2] = {7,6,5};fixed_arr = {4{5}};fixed_arr = {defaut:42};Array Operator:ForForeachint array[0:4];for (int i =0;i Difficult to understand the functionality of a programThere are no structures, only bit vectors and arrays => Limited in modeling and organizing dataThe arrays are all static => Less flexibility and compatibility

46Dolphin Technology Inc.OOP BriefOOP - Object Oriented ProgrammingCreate complex data types and tie them together with the routines that work with themCreate testbenches and system-level models by calling routines to perform an actionWorking at a higher level, code is more easily written and understoodMore robust and easier to maintain and reuse on future projects

47Dolphin Technology Inc.OOP BriefTerminology

ClassObjectHandleAttributeMethod48Dolphin Technology Inc.InheritanceEncapsulationAbstractionPolymorphismetcOOP BriefClassContains data and codes with behaviorDescribes all the properties, behavior, and identity of objects

ObjectAn instance of class with behavior, identityExpressed by the variable and methods 49Dolphin Technology Inc.OOP BriefHandleA pointer to an object

AttributeA variable that holds data

MethodProcedural code that manipulates variables, are tasks and functionsDefine the abilities and behaviors of an object50Dolphin Technology Inc.OOP briefExample51Dolphin Technology Inc.

Attribute

MethodHandleObjectObject CreationDeclare a handleTransaction tr;tr points to an object of type Transaction, initialized to the special value nullCan refer to many objects, but only one at a timeConstruct a objecttr = new();Allocates space for the TransactionInitializes the variables to their default valueReturns the address where the object is stored

52Dolphin Technology Inc.Object Creationnew() functionMaking an instance of the classFor every class, SystemVerilog creates a default new function to allocate and initialize an objectCustom constructor

53Dolphin Technology Inc.

Object Creation54Dolphin Technology Inc.Allocating multiple objects

Using objects

Object DeallocationLong simulation might run out of memoryWhen a object is no longer use, should reclaim the memoryGarbage collection is the process of automatically freeing objects that are no longer referencedWhen the last handle no longer references an object, SystemVerilog releases the memory for it

55Dolphin Technology Inc.

Class Methods Just a taskor functiondefinedinside thescope ofthe class

56Dolphin Technology Inc.

Defining Methods Outside of the ClassClass scope resolution operator :: should be usedadd the extern keyword at the beginning while defining

57Dolphin Technology Inc.

Static Variables vs. Global VariablesSimple Static VariableSystemVerilog allow to create a static variable inside a class.Shared amongst all instances of the class, but its scope is limited to the class

58Dolphin Technology Inc.

Static Variables vs. Global VariablesAccessing Static VariablesUsing a handleUsing class name followed by ::

GlobalVisible to the entire testbench59Dolphin Technology Inc.

Static Variables vs. Global VariablesStatic MethodsRead and write static variables60Dolphin Technology Inc.

Using One Class Inside AnotherA class can contain an instance of another class, using a handle to an object

The outer class can refer to things in the inner class using syntax .

61Dolphin Technology Inc.

Using One Class Inside AnotherCompilation OrderDeclare the class name with a typedef statement before use.

62Dolphin Technology Inc.

Dynamic ObjectsIn Verilog, every signal has a unique variable associated with itIn OOP, there can be many objects, but only a few named handles to manipulate themFlexibility in allocate and de-allocated to save memory in storing objects and during a simulation

63Dolphin Technology Inc.Dynamic ObjectsPassing Objects and Handles to Methods

64Dolphin Technology Inc.

Dynamic ObjectsModifying a Handle in a TaskUsing ref on method argumentsSystemVerilog passes the address of the variable so the method can modify it

65Dolphin Technology Inc.

Dynamic ObjectsModifying Objects in FlightNeed to create a new object for each transaction in the testbench

66Dolphin Technology Inc.

Dynamic ObjectsArrays of HandlesThe array made of handles, not objectsNeed to construct each object in the array before using itCan not call new on an entire array of handles67Dolphin Technology Inc.

Copying ObjectsCopying an Object with the New OperatorMemory for the new object is allocatedall variables from the existing object are copied

68Dolphin Technology Inc.

Copying ObjectsAny new() function that have defined is not called

69Dolphin Technology Inc.

Copying ObjectsWriting Your Own Simple Copy FunctionIf class that does not contain any references to other classes

70Dolphin Technology Inc.

Copying ObjectsWriting a Deep Copy FunctionIf class that contain any references to other classes

71Dolphin Technology Inc.

Public vs. LocalIn SystemVerilog, everything is public unless labeled local or protectedVariables are kept local to the class by default to keep one class from poking around inside another.A class provides a set of accessor methods to access and modify the dataPublic: Everyone can see it, can be accessed by any object of this class.Local: Only the class in which it is declared can see it (Can only be used in the methods of this class)

72Dolphin Technology Inc.Connect the test bench to DUT

Separating the test bench and designThe interface constructStimulus timingInterface driving and samplingSeparating the test bench and designThe communication between blocks of a digital system is a critical area. For large modules, this is not productive as it involves.Manually connecting hundreds of ports may lead to errors.Detailed knowledge of all the port is required.Difficult to change if the design changes.More time consuming.Most port declaration work is duplicated in many modules.74Dolphin Technology Inc.Separating the test bench and design75Dolphin Technology Inc.Example:moduleDut(inputclk,read,enable,input[7:0]addr,output[7:0]data);....assigndata=temp1?temp2:temp3;always@(posedgeclk)....endmodule

moduleTestbench( inputclk,output read,enable,output[7:0]addr,input[7:0]data);endmodule

moduletop();regclk;wireread,enable;wire[7:0]addr;wire[7:0]data; Dut D (clk,read,enable,Addr,data); TestbenchTB(clk,read,enable,Addr,data);endmodule

The interface construct76Dolphin Technology Inc.SystemVerilog added a new powerful features called interface. Interface encapsulates the interconnection and communication between blocks.

Interface declaration for the above example:

interfaceintf#(parameterBW=8)(inputclk); logicread,enable; logic[BW-1:0]addr,data;endinterface:intf

The interface constructDUT and Testbench modules using the above declared interface:77Dolphin Technology Inc.moduleDut(intf dut_if);assigndut_if.data=temp1?temp2:temp3;always@(posedgedut_if.clk)endmodulemoduleTestbench(intf tb_if);endmodulemoduletop();bitclk;initialforever#5clk=~clk; intf bus_if(clk); Dut d(bus_if); Testbench TB(bus_if);endmoduleThe interface constructConnecting Interfaces and Ports

78Dolphin Technology Inc.moduletop();bitclk;initialforever#5clk=~clk; intf bus_if(clk); Dut d( .clk (clk), .read (bus_if.read), .enable (bus_if.enable), .addr (bus_if.addr), .data (bus_if.data) ); Testbench TB(bus_if);endmoduleThe interface constructGrouping Signals in an Interface Using ModportsThe modport construct in an interface lets you group signals and specify directions.

79Dolphin Technology Inc.interfaceintf(inputclk);logicread,enable,logic[7:0]addr,data; modportdut (input read,enable,addr, outputdata); modporttb (output read,enable,addr, inputdata);endinterface:intfmoduletop();logicclk; intf bus_if(clk); Dut d(bus_if.dut); Testbench TB(bus_if.tb);endmoduleStimulus timingThe timing between the testbench and the design should be maintained to avoid race conditions.

80Dolphin Technology Inc.

Stimulus timingClocking block:Identify clock signals, and captures the timing and synchronization requirements of the blocks being modeled.Assembles signals that are synchronous to a particular clock, and makes their timing explicit.Clocking blocks can only be declared inside a module, interface or program.81Dolphin Technology Inc.Stimulus timingA testbench can contain one or more clocking blocks.Example interface use clocking block.

82Dolphin Technology Inc.

Stimulus timingReferencing signals in the Clocking Block

Default input and default output in clocking block

83Dolphin Technology Inc.

Stimulus timingSkew:Input skew is specified then the signal is sampled at skew time units before the clock event.Output skew is specified, then output (or inout) signals are driven skew time units after the corresponding clock event.

84Dolphin Technology Inc.

Stimulus timingSkew can be specified in 3 ways:#d: The skew is d time units. #dns: The skew is d nano seconds.#1step: specifies that signals be sampled in the postpone region before any design activity.

If skew is not specified, default input skew is 1step and output skew is 0.85Dolphin Technology Inc.Stimulus timingSignal Synchronization:Synchronize to active clock edge

Synchronize to any edge of signal

Wait for N clock cycles with ##n

86Dolphin Technology Inc.

SystemVerilog AssertionVerification Training7 April 2015SystemVerilog Assertion Terminology88Dolphin Technology Inc.- Based on clock cycles-Test expression is evaluated at clock edges based on the sampled values of the variables involved.- Placed in a procedural block, a module, an interface or a program definition.Concurrent Assertionsa_cc: assert property( @( posedge clk ) not ( a && b ) ) ;

SystemVerilog Assertion Terminology89Dolphin Technology Inc.Based on simulation event semantics

Have to be placed in a procedural block definition.Immediate Assertionsalways_combbegina _ i a : assert (a && b ) ;end

SVA Building Block90Dolphin Technology Inc.

SystemVerilog Assertion CheckerSequence Assertion 91Dolphin Technology Inc.sequence name_of_sequence;;endsequenceSequence with edge definitionsSrose {boolean expression or signal name)

$fell ( boolean expression or signal name)

$stable {boolean expression or signal name)sequence s2 ; @(posedge elk) $rose(a) ;endsequence

Sequence Assertion 92Dolphin Technology Inc.Sequences with timing relationshipsequence s4 ; @( posedge clk ) a ##2 b;endsequence

Success: start at 5, end at 7; start at 14, end at 16;Property Assertion 93Dolphin Technology Inc.Syntax:property name_of_property; ; or < complex sequence expression>endpropertyassertion_name: assert property (property_name);Forbidding a propertysequence s6; @ (posedge clk) a ##2 b;endsequenee

property p6; not s6;endproperty

a6 : assert property(p6) ;Property Assertion94Dolphin Technology Inc.property p7; @ (posedge clk) a ##2 b;endpropertya7 : assert property(p7) $display("Property p7 succeeded\n") ;else $ display (" Property p7 failed \ n " ) ;Implication operator Overlapped implication Non-overlapped implicationProperty Assertion95Dolphin Technology Inc.Implication operatorOverlapped implication

property p8 ; @(posedge clk) a |-> b;endpropertya8 : assert property(p8) ;

Property Assertion96Dolphin Technology Inc.Implication operatorNon-overlapped implicationproperty p9 ; @(posedge clk) a |= > b;endproperty

a9 : assert property (p9) ;

SVA constructs97Dolphin Technology Inc.$past (signal_name, number of clock cycles)property p19; @(posedge clk) ( c && d ) |->($past((a&&b) , 2) == 1b1) ;endproperty

a19: assert property (p19) ;

Connecting SVA to the Design98Dolphin Technology Inc.Two different methods:1. Embed or in-line the checkers in the module definition.2. Bind the checkers to a module, an instance of a module or multiple instances of a modulemodule inline (clk, a, b, d1, d2 , d ) ;input logic clk, a, b;input logic [7:0] d1, d2;output logic [7:0] d;always @( posedge clk )beginif (a)d 5 ; } endclass

Constraint Details Implication Constraints 112Dolphin Technology Inc.The expression A->B is equivalent to the expression (! A || B)

Ex:class LogImp; rand bit d,e; constraint c { (d == 1) -> (e ==1); } endclass => when d==1, the variable e must be 1, but when e==1, d can be 0 or 1Constraint Details Implication Constraints 113Dolphin Technology Inc.An if-else implication constraintclass BusOp; rand operand_e op; rand length_e len; constraint c_len_rw { if (op == READ) { len inside {[BYTE:LWRD]}; else { len == LWRD; } } endclass Constraint Details Equivalence Operator 114Dolphin Technology Inc.The equivalence operator is bidirectional. ABis defined as ((A->B) && (B->A))

Ex: rand bit d,e;constraint c {d == 1} (e == 1); }=> When dis true, emust also be true, and when dis false, emust also be falseSolution Probabilities Unconstrained 115Dolphin Technology Inc.class unconstrained;rand bit x; // 0 or 1rand bit [1:0] y; // 0 ,1,2 or 3endclass

Implication class Imp1;rand bit x;rand bit [1:0] y;constraint c_xy {(x == 0) -> (y == 0);}

Solution Probabilities Implication and Bidirectional Constraint 116Dolphin Technology Inc.class Imp2;rand bit x;rand bit [1:0] y;constraint c_xy {y >0;(x == 0) -> (y == 0);}endclass

Solution Probabilities Guiding Distribution with Solve .. Before 117Dolphin Technology Inc.class SolveXBeforeY; rand bit x; // 0 or 1 rand bit [1:0] y; // 0,1,2 or 3 constraint c_xy { (x == 0) -> (y == 0); solve x before y; } endclass

Control Multiple ConstrainsSyntax:Control a single constrainhandle.constrain.constrain_mode(arg)Control all constrainhandle.constrain_mode(arg)

arg = - 0 : constrain is turned off - 1 : constrain is turned on118Dolphin Technology Inc.Control Multiple ConstrainsExample :

119Dolphin Technology Inc.class rand_mode;rand integer Var1;rand integer Var2;constraint Var_1 { Var1 == 20;}constraint Var_2 { Var2 == 10;}endclassprogram rand_mo_p_38;rand_mo obj = new();initialbeginobj.randomize(); $display(" Var1 : %d Var2 : %d ",obj.Var1,obj.Var2);obj.constraint_mode(0); //Both constraints Var_1 and Var_2 are turned off.obj.randomize();$display(" Var1 : %d Var2 : %d ",obj.Var1,obj.Var2);obj.constraint_mode(1); //Both constraints Var_1 and Var_2 are turned on.obj.randomize();$display(" Var1 : %d Var2 : %d ",obj.Var1,obj.Var2);endendprogram Var1 : 20 Var2 : 10 Var1 : 733126180 Var2 : -119008195 Var1 : 20 Var2 : 10 In-Line ConstraintsInline constraints allows to add extra constraints to already existing constraints which are declared inside class.Syntax : using randomize withExample120Dolphin Technology Inc.class inline;rand integer Var;constraint default_c { Var > 0 ; Var < 100;}endclass

program inline_test;inline obj;initialbeginobj = new();repeat(2)if(obj.randomize() with { Var == 50;})$display(" Randodmize sucessful Var %d ",obj.Var);else$display(" Randomization failes");endendprogram # Randodmize sucessful Var 50# Randodmize sucessful Var 50 Pre_randomize and Post_randomizeWhen randomize() is called,it first invokes the pre_randomize() then randomize() finally if the randomization is sucesusful only post_randomize is invoked. Example:

121Dolphin Technology Inc.program pre_post_test;class simple;function void pre_randomize;$display(" PRE_RANDOMIZATION ");endfunctionfunction void post_randomize;$display(" POST_RANDOMIZATION ");endfunctionendclasssimple obj = new();initialobj.randomize();endprogram# PRE_RANDOMIZATION# POST_RANDOMIZATION Random Number FunctionsIn System Verilog, we have some random functions $random Flat distribution, returning signed 32-bit random $urandom Flat distribution, returning unsigned 32-bit random $urandom_range Flat distribution over a range

Example :

a = $urandom_range(3,10); //Pick a value from 3 to 10 b = $urandom_range(5); // Pick a value from 0 to 5122Dolphin Technology Inc.Constraints Tips and TechniquesConstraints with VariablesUsing Nonrandom ValuesChecking Values Using ConstraintsRandomizing Individual Variables

123Dolphin Technology Inc.Constraints Tips and TechniquesConstraints with VariablesTo make constrains more readable and flexiable

124Dolphin Technology Inc.class Packet; rand bit [31:0] length; bit [3:0] max_length =100; constrain c_length {length inside {[1:max_length]} }endclassConstraints Tips and TechniquesUsing Nonrandom ValuesIf there are just a few random variables that you want to override, use the rand_mode function to make them nonrandom

125Dolphin Technology Inc.class Packet; rand bit [7:0] length, payload[]; constrain c_valid { length > 0; payload.size() = length;} function void display (input string msg) endfunctionendclassPacket p;Initial begin p = new(); p.randomize(); p.display( simple randomization); p.length.rand_mode(0); p.length = 40; p.randomize(); p.display (randomization with rand_mode);end

Constraints Tips and TechniquesChecking Values Using ConstraintsWhen randomize() method is called by passing null, randomize() method behaves as checker instead of random generator. It evaluates all the constraints and returns the status.

126Dolphin Technology Inc.class Eth_rx;rand integer Pkt_len;rand integer Var;constraint var_c { Var < 1518 ;Var > 64 ;}endclass

program Eth_test;Eth_rx rx = new();initialbeginrx.Pkt_len = 32;rx.Var = 871;if(rx.randomize(null))$display(" VALID PKT IS RECIVED ");else$display(" INVALID PKT IS RECIVED ");endendprogram# VALID PKT IS RECIVED Constraints Tips and TechniquesRandomizing Individual VariablesTo randomize the subset of variables, we can pass the argument to randomize().Only those variables passed in the argument list will be randomized; the rest will be treated as state variables and not randomized

127Dolphin Technology Inc.class Rising; bit [7:0] low; rand bit [7:0] med, hi; constrain up { low < med ; med < hi;}endclassinitial beginRising r;r = new(); r.randomize(); // random all variable r.randomize(med); //only med is randomized r.randomize(low); //random only low through it isnt randendCommon Randomization ProblemsUse Signed Variables with CareDont use int, byte or other signed type unless if you really want signed value.Example:class Vars;rand byte var1, var2;constraint total {var1 + var2 == 64;}endclass: Vars//You could get pairs of values such as (-63, 127)128Dolphin Technology Inc.Common Randomization ProblemsUse Signed Variables with Care (cont)Solve: use unsigned random variables and make them as wide as needed.Example:class Vars;rand bit [5:0] var1, var2;constraint total {var1 + var2 == 6d64;}endclass: Vars

129Dolphin Technology Inc.Common Randomization ProblemsChoose the Right Arithmetic Operator to Boost EfficiencyExample:rand bit [31:0] addr;constraint c {addr % 4096 inside {[0:20], [4075:4095]};}Efficient constraintrand bit [31:0] addr;constraint c {addr [11:0] inside {[0:20], [4075:4095]};}

130Dolphin Technology Inc.Iterative and Array ConstraintsArray SizeThe easiest array constraint to understand is the size function.Example:class dyn_size;rand bit [31:0] d[];constraint d_size {d.size() inside {[1:10]};}endclass: dyn_size131Dolphin Technology Inc.Iterative and Array Constraints (cont)Sum of ElementsExample:class sum_arr;rand bit v [10];constraint v_sum {v.sum()==4h4;}endclass: sum_arr132Dolphin Technology Inc.Iterative and Array Constraints (cont)Issues with Array ConstraintsExample:class bad_sum;rand byte len [];constraint c_len {len.sum() < 1024;len.size() inside {[1:8]};}function void display(); $write(sum=%d val=, len.sum()); foreach(len[i]) $write(%d, len[i]); $display;endfunction: displayendclass: bad_sum133Dolphin Technology Inc.Iterative and Array Constraints (cont)Issues with Array Constraints (cont)# sum =-120,val=-120# sum = 50,val= 123 53 60 59 11# sum = 80,val= 80# sum = 5,val=-113 26 87 5# sum = 13,val=-111-123 -87 78Drawback: the sum is somtime negative and is always less than 127134Dolphin Technology Inc.Iterative and Array Constraints (cont)Issues with Array Constraints (cont)class good_sum; rand uint len[]; constraint c_len {foreach(len[i]) len inside {[1:255]};len.sum() 16) + state;return state;endfunction138Dolphin Technology Inc.Random Number Generators Random StabilityIn Verilog, if the source code does not change ,with the same seed, the simulator producess the same random stimulus on any mechine or any operating system and we miss the bug.139Dolphin Technology Inc.Random Number Generators Random Stability (cont)Example:module random_v ;initialrepeat(5) $display (random = %d, $random(2));endmodule: random_v

# random = -2147345408# random = -2147345408# random = -2147345408# random = -2147345408# random = -2147345408140Dolphin Technology Inc.Random Number Generators Random Stability (cont)In SystemVerilog seeding will be done hierachily. Every module instance, interface instance, program instance and package has initialization PRNG. Every thread and object has independent PRNG . When ever dynamic thread is created its PRNG is initialized with the next random value from its parent thread.141Dolphin Technology Inc.Random Number Generators Random Stability (cont)Example:

142Dolphin Technology Inc.class Ran_1;rand bit [2:0] Var;endclass

class Ran_2;rand bit [2:0] Var;endclassmodule Ran_Stb;Ran_1 r1 = new();Ran_2 r2 = new();initialbeginrepeat(5) beginvoid'(r1.randomize());$display("Ran_1.Var : %0d ", r1.Var);endrepeat(5) beginvoid'(r2.randomize());$display("Ran_2.Var : %0d ", r2.Var);endendendmoduleRandom Number Generators Random Stability (cont)Result:# Ran_1.Var : 0 # Ran_1.Var : 5 # Ran_1.Var : 0 # Ran_1.Var : 3 # Ran_1.Var : 4 # Ran_2.Var : 5 # Ran_2.Var : 5 # Ran_2.Var : 1 # Ran_2.Var : 7 # Ran_2.Var : 1 143Dolphin Technology Inc.Random Number Generators Random Stability (cont)Example:

144Dolphin Technology Inc.class Ran_1;rand bit [2:0] Var;endclass

class Ran_2;rand bit [2:0] Var;endclassmodule Ran_Stb;Ran_1 r1 = new();Ran_2 r2 = new();initialbeginrepeat(5) beginvoid'(r2.randomize());$display("Ran_2.Var : %0d ", r2.Var);endrepeat(5) beginvoid'(r1.randomize());$display("Ran_1.Var : %0d ", r1.Var);endendendmoduleRandom Number Generators Random Stability (cont)Result:# Ran_2.Var : 5 # Ran_2.Var : 5 # Ran_2.Var : 1 # Ran_2.Var : 7 # Ran_2.Var : 1 # Ran_1.Var : 0 # Ran_1.Var : 5 # Ran_1.Var : 0 # Ran_1.Var : 3 # Ran_1.Var : 4 145Dolphin Technology Inc.Random Number Generators Random Stability (cont)Sometimes it is desirable to manually seed an objects RNG using the srandom()method.146Dolphin Technology Inc.Random Number Generators Random Stability (cont)Example:

147Dolphin Technology Inc.class Rand_seed; rand integer Var; function new (int seed); srandom(seed); $display(" SEED is initised to %0d ",seed); endfunction

function void post_randomize(); $display(": %0d :",Var); endfunction endclass module Rand_seed; Rand_seed rs; initial begin rs = new(20); repeat(5) void'(rs.randomize()); rs = new(1); repeat(5) void'(rs.randomize()); end endmodule Random Number Generators Random Stability (cont)Result:# SEED is initised to 20 # : 1189201676 :# : -50602121 :# : 1441010736 :# : 999569011 :# : -161019490 :# SEED is initised to 1 # : 1232952047 :# : 9295156 :# : -183300904 :# : -83119859 :# : 1832521658 :148Dolphin Technology Inc.Thread and Inter-process Communication7 April 2015ContentWorking with threadsEventsMailboxesSemaphoreBuilding a test bench with threads150Dolphin Technology Inc.Thread and IPCOverviewThread: To stimulate and check blocks (initial, always,)All running in parallel and run in their own threadScheduler chooses which thread runs nextIPC: To communicate with other threadsMethods:- Event- Mailbox- Semaphore151Dolphin Technology Inc.

Working With ThreadsforkjoinStatements in a forkjoin execute in parallelAll inside statements have to finish before the rest of the block can continue => limmitedNew ways to create threads: - forkjoin_none - forkjoin_any

152Dolphin Technology Inc.

Working With ThreadsUsing forkjoin and beginend

153Dolphin Technology Inc.

Working With Threadsforkjoin_none (Spawning Threads)

154Dolphin Technology Inc.

- Schedules each statement in the block

- Execution continues in the parent threadA forkjoin_none block schedules each statement in the block, but execution continues in the parent thread154Working With Threadsforkjoin_any (Synchronizing Thread)

155Dolphin Technology Inc.- Schedules each statement in the block.- Complete first statement.- Then, execute continue in the parent thread.

A forkjoin_any block schedules each statement in the block. Then, when the first statement completes, execution continues in the parent thread. All other remaining threads continue155Working With ThreadsCreating Threads in a Class156Dolphin Technology Inc.

The run task starts a thread in a forkjoin_none block

- Do not start any threads in new() functionuse a forkjoin_none to start a thread156Disabling ThreadsDisabling a Single Thread

157Dolphin Technology Inc.

- Labelling for the blocks to specify what to stop.

- Use disable function.If the correct bus data comes back quickly enough, the wait construct completes, the join_any executes, and then the disable kills off the remaining thread. However, if the bus data does not get the right value before the TIME_OUT delay completes, the error message is printed, the join_any executes, and the disable kills the thread with the wait.157Disabling ThreadsDisabling Multiple Thread

158Dolphin Technology Inc.- Use disable fork function.

- Stop threads 2,3,4If the correct bus data comes back quickly enough, the wait construct completes, the join_any executes, and then the disable kills off the remaining thread. However, if the bus data does not get the right value before the TIME_OUT delay completes, the error message is printed, the join_any executes, and the disable kills the thread with the wait.158IPC EventsA handle to a synchronization object that can be passed around to routinesTo share events across objects without having to make the events globalThe most common way is to pass the event into the constructor for an objectOperator:@ a thread waits for an event to change-> unblocking the first threadStatus e.triggered check whether an event has been triggered

159Dolphin Technology Inc.IPC EventsBlocking on the Edge of an Event

160Dolphin Technology Inc.

- One initial block starts, triggers its event, and then blocks on the other event- The second thread locks up because it missed the first event, as it is a zerowidth pulseOne initial block starts, triggers its event, and then blocks on the other eventThe second block starts, triggers its event (waking up the first), and then blocks on the first event.However, the second thread locks up because it missed the first event, as it is a zero width pulse160IPC EventsWaiting for an Event Trigger

161Dolphin Technology Inc.

- One initial block starts, triggers its event, and then blocks on the other event- The second block starts, triggers its event (waking up the first) and then blocks on the first eventOne initial block starts, triggers its event, and then blocks on the other event.The second block starts, triggers its event (waking up the first) and then blocks on the first event161IPC EventsPassingEvents

162Dolphin Technology Inc.

IPC SemaphoresSemaphore: to control access to a resource using a keysemaphore sem; //create a semaphoreTasksnew(num_key) create a semaphore with one or more keysget() get one or moreput() return one or more keystry_get() try to get a semaphore, obtains available keys and returns 1. returns 0 if there are not sufficient keys

163Dolphin Technology Inc.Semaphores can be used in a testbench when you have a resource, such as a bus, that may have multiple requestors from inside the testbench but, as part of the physical design, can only have one driver.163IPC SemaphoresExample164Dolphin Technology Inc.

There are three basic operations for a semaphore. You create a semaphore with one or more keys using the new method, get one or more keys with the blocking task get(), and return one or more keys with put(). If you want to try to get a semaphore, but not block, use the try_get() function. If keys are available, try_get() obtains them and returns 1. If there are not sufficient keys, it just returns a 0164IPC MailboxsMailbox: To pass information between two threads

mailbox #(obj_type) mbx; //create a parameterized mailboxTasksput() put data into a mailboxget() remove datatry_put() to see if the mailbox is full.try_get() to see if it is empty.peek() gets a copy of the data in the mailbox but does not remove it165Dolphin Technology Inc.

IPC MailboxsMailbox in a Testbench

166Dolphin Technology Inc.

Building a Testbench with Threads and IPCLayered testbench with environment

167Dolphin Technology Inc.

Building a Testbench with Threads and IPCExample

168Dolphin Technology Inc.

Building a Testbench with Threads and IPC169Dolphin Technology Inc.

ExampleAdvanced OOPAdvanced OOPIntroduction to inheritanceInheritance is the mechanism which allows aclassA to inherit properties of aclassB.A inherits fromclassB,then B is called superclass of A, A is called subclass of B.

171Dolphin Technology Inc.Advanced OOPExample

172Dolphin Technology Inc.class Transaction; rand bit [31:0] src,dst,data[8]; bit [31:0] csm;virtual function void calc_csm(); csm = src^dst^data.xor; endfunction

virtual function void display(input string prefix=""); $display("%sTr: src = %h, dst=%h, csm=%h, data=%p", prefix,src,dst,csm,data) ;endfunction endclass

class BadTr extends Transaction; rand bit bad_csm;

virtual function void calc_csm(); super.calc_csm(); if (bad_csm) csm = ~csm; endfunction

virtual function void display(input string prefix="");$write("%sBadTr: bad_csm=%b, " , prefix, bad_csm);super.display(); endfunction endclassAdvanced OOPA subclass inherits all the members (fields, methods, and nested classes) from its superclass. But constructor not inherited by subclasses.Example:

173Dolphin Technology Inc.

Advanced OOP Downcasting and Virtual MethodsDowncasting is the act of casting a base class handle to point to an object that is a class extended from that base type.

174Dolphin Technology Inc.Advanced OOPExample:175Dolphin Technology Inc.

Advanced OOPSystemVerilog provides the $cast system task to assign values to variables that might not ordinarily be valid because of differing data type.The syntax for $cast() is as follows:

task $cast( singular dest_handle, singular source_handle );

function int $cast(singular dest_handle, singular source_handle );176Dolphin Technology Inc.Advanced OOPExample:

177Dolphin Technology Inc.

THANK FOR WATCHING!178Dolphin Technology Inc.