Lecture14ObjectOrientedProgramming.pdf - ECE 571 Introduc\/on to SystemVerilog Portland State University Mark G Faust Object Oriented Programming 2

Lecture14ObjectOrientedProgramming.pdf - ECE 571...

This preview shows page 1 out of 31 pages.

You've reached the end of your free preview.

Want to read all 31 pages?

Unformatted text preview: ECE 571 Introduc/on to SystemVerilog Portland State University Mark G. Faust Object Oriented Programming 2 Outline •  •  •  •  •  •  •  •  •  •  •  OOP Terminology An example class Crea/ng new objects Dealloca/ng objects Using objects Sta/c class variables Scope Classes containing classes Copying objects Packing/unpacking objects Public vs. local 3 OOP Terminology Class Basic building block containing rou/nes and variables (a data type and the opera/ons on it) Object An instance of a class Handle A pointer to an object Property A variable Method Procedural code (embodied in tasks and func/ons) that manipulates variables Prototype Header of rou/ne showing name, type, and argument list Constructor Method used to create an instance of a class 4 display the packet address, and another that computes the CRC (cyclic redundancy check) the data. New Objects 5.6 of Creating To make it easier to match the beginning and end of a named block, puthave a label on the end of it. In Sample these Both Verilogyou and can OOP the concept of instantiation, but 5.1 there are end somelabels differences in the details. A Verilog module, a counter, is instantiated whentheyou may look redundant, but insuch real as code with many nested blocks, compile your labels design.help A SystemVerilog class, for sucha as a network packet, is instantiated endtask , endyou find the mate simple end or at run-time when needed the testbench. Verilog instances are static, as the hardfunction , orbyendclass . ware does not change during simulation; only signal values change. Stimulus objects Sample 5.1 Simplebeing transaction class are constantly created and used to drive the DUT and check the results. Later, the objects may be freed so that their memory can be used by new ones.1 class Transaction; A Class Proper/es Method Method bit analogy [31:0] between addr, crc, data[8]; The OOP and Verilog has a few other exceptions. The top-level Verilog module is not usually explicitly instantiated. However, a SystemVerilog class function void display; must be instantiated before it can be used. Next, a Verilog instance name only refers $display("Transaction: %h", addr); to a single instance, whereas a SystemVerilog handle can refer to many objects, endfunction : display Class though only one at a time. function void calc_crc; 5.6.1 News crcNo = News addr is ^ Good data.xor; endfunction : calc_crc In Sample 5.2, tr is a handle that points to an object of type Transaction. You can endclass : Transaction simplify this by just calling tr a Transaction handle. Every company its own naming style. This book uses the followSample 5.2 Declaring and usinghas a handle Handle Constructor ing convention: Class names start with a capital letter and avoid using Transaction tr; // Declare a handle underscores, as in Transaction or Packet. Constants are all upper tr = new(); // Allocate a Transaction object case, as in CELL_SIZE, and variables are lower case, as in count or trans_type. You are free to use whatever style you want. When you declare the handle tr, it is initialized to the special value null. Next, you call the new() function to construct the Transaction object. new allocates space for the Transaction, initializes the variables to their default value (0 for 2-state vari- and X to for Define 4-state ones), and returns the address where the object is stored. For 5.4ables Where a Class every class, SystemVerilog creates a default new to allocate and initialize an5 object. See Section forinmore details on this You can define5.6.2 a class SystemVerilog in afunction. program, module, package, or outside of any of these. Classes can be used in programs and modules. This book only shows 5.6.2that Custom Constructor classes are used in a program block, as introduced in Chap. 4. Until then, think of logic [31:0] addr, crc, data[8]; 130 function new(); Chapter 5:Basic OOP addr = 3; foreach (data[i]) data[i] = 5; function. (Note that SystemVerilog uses additional memory for 4-state variables and endfunction housekeeping information such as the objectBs type.) Crea/ng new objects The constructor does more than allocate memory; itendclass also initializes the values. By default, variables are set to their default values I 0 for 2-state variables and X for 4Default constructor for new() classes: new() ayour llocates storage for new bject of tbut ype function to setSample own values. That isdata why state. You can define your own 5.3 sets addr and to o fixed values leaves crc at matching the ishandle. Sthe imilar to malloc() new() function also called Nconstructor,O asX. it builds the object, allocates just as your the (SystemVerilog the space for the object automatic house is constructed from wood and nails. Note thatarguments you should give values a returnto make a more flexible constructor withnot default Now can specify value type as the constructor always returns a handle ple to an5.4. object of you the same type as the value for addr and data Classes to not orouse nly the allocate memory but constructor, default values. the class. can define their own constructors ini/alize variables class Transaction; logic [31:0] addr, Sample 5.3 Simple user-defined new() function crc, data[8]; function new(); addr = 3; foreach (data[i]) data[i] = 5; endfunction Sample 5.4 A new() function with arguments class Transaction; logic [31:0] addr, crc, data[8]; function new(logic [31:0] a=3, d=5); addr = a; foreach (data[i]) data[i] = d; endfunction endclass endclass initial begin Transaction tr; value of Sample 5.3 sets addr and data to fixed values but leaves crc at its default tr = new(10); X. (SystemVerilog allocates the space for the object automatically.) You// candata use uses default of 5 arguments with default values to make a more flexibleend constructor, as shown in Sam- ple 5.4. Now you can specify the value for addr and data when you call the 6 to call? It How does SystemVerilog know which new() function constructor, or use the default values. the handle on the left side of the assignment. In Sample 5.5, the ca Sample 5.4 A new() function with arguments function. (Note that SystemVerilog uses additional memory for 4-state variables and housekeeping information such as the objectBs type.) The constructor does more than allocate memory; it also initializes the values. By default, variables are set to their default values I 0 for 2-state variables and X for 4state. You can define your own new() function to set your own values. That is why the new() function is also called the Nconstructor,O as it builds the object, just as your house is constructed from wood and nails. Note that you should not give a return value type as the constructor always returns a handle to an object of the same type as the class. Crea/ng new objects Sample 5.3New Simple user-defined new() function Creating Objects 131 class Transaction; logic [31:0] addr, crc, data[8]; Driver constructor calls the new() function for Transaction, even though the one Driver is new(); closer. Since tr is a Transaction handle, SystemVerilog does the forfunction right thing creates an object of type Transaction. addr and = 3; foreach (data[i]) Sample 5.5 Calling the right new() function data[i] = 5; endfunction class Transaction; ... endclass endclass : Transaction Sample 5.3 sets addr and data to fixed values but leaves crc at its default value of class Driver; X. Transaction (SystemVerilogtr; allocates the space for the object automatically.) You can use arguments withnew(); default values to a more flexible constructor, as shown in Samfunction //make Driver’s new function addr and data when you call the ple 5.4. you can specify//theCall valuethe for Transaction tr Now = new(); new function constructor, or use the default values. endfunction endclass : Driver Sample 5.4 A new() function with arguments 5.6.3 Separating the Declaration and Construction class Transaction; logic [31:0] addr, crc, data[8]; You should avoid declaring a handle and calling the constructor, new, function new(logic [31:0] While a=3, this d=5); all in one statement. is legal syntax and less verbose, it can addr = a; create ordering problems, as the constructor is called before the first 7 Handles Handles a132 re not objects. They're pointers to objects. Chapter 5:Basic OOP Chapter 5:Basic OOP 132 Sample 5.6 Allocating multiple objects SampleTransaction 5.6 Allocating multiple objects// Declare two handles t1, t2; t1 = new(); Allocate Transaction object Transaction t1, t2; ////Declare twofirst handles t2 = t1; // t1 &first t2 point to it t1 = new(); // Allocate Transaction object t1 = new(); // Allocate second Transaction object t2 = t1; // t1 & t2 point to it t1 = new(); // Allocate second Transaction object Figure 5-1 Handles and objects after allocating multiple objects Figure 5-1 Handles and objects after allocating multiple objects t1 t2 Second First Transaction t1 t2 Second First Transaction object object Transaction Transaction object object Why would you want to create objects dynamically? During a simulation you may need to create thousands of transactions. letsmay you create Why would you wanthundreds to createorobjects dynamically? DuringSystemVerilog a simulation you ones automatically, when of youtransactions. need them. SystemVerilog In Verilog, youlets would need tonew create hundreds or thousands you have createto use a fixed-size array large enough to hold the maximum of transactions. new ones automatically, when you need them. In Verilog,number you would have to use a fixed-size array hold the of maximum of transactions. Note thatlarge this enough dynamicto creation objects number is different from anything else offered before the Verilog language. An instance of a from Verilog moduleelse andoffered its name are Note that thisindynamic creation of objects is different anything automatic variables, statically during compilation. Even with before bound in the together Verilog language. An instance of a Verilog module and its name are which come andstatically go during simulation, the name and storage are always tied together. automatic variables, which bound together during compilation. Even with 8 Dealloca/ng objects Unlike malloc()/free() Object Deallocation 133 Explicit free() not required Process of garbage collec/on iden/fies objects that no longer have handles and track of the number of handles that point to it. When the last handle no longer reclaims tkeeping heir s torage references an object, SystemVerilog releases the memory for it.2 Sample 5.7 Creating multiple objects Transaction t; t = new(); t = new(); t = null; // // // // Create a handle Allocate a new Transaction Allocate a second one, free the first Deallocate the second The second line in Sample 5.7 calls new() to construct an object and store the address in the handle t. The next call to new() constructs a second object and stores its address in t, overwriting the previous value. Since there are no handles pointing to the first object, SystemVerilog can deallocate it. The object may be deleted immediately, or wait a short wait. The last line explicitly clears the handle so that now the second object can be deallocated. If you are familiar with C++, these concepts of objects and handles might look familiar, but there are some important differences. A SystemVerilog can handle only point to objects of one type, and so they are called Jtype-safe.K In C, a typical void pointer is only an address in memory, and you can set it to any value or modify it with operators such as pre-increment. You cannot be sure that a pointer really is valid. A C++ 9 134 Using objects Chapter 5:Basic OOP 5.8 Using Objects Can reference variables (proper/es) directly much like fields in structs that you have allocated an object, you use it? Going back to the Verilog Can invoke fNow unc/ons/tasks (methods) via how "." ndoota/on module analogy, you can refer to variables and routines in an object with the @.A Can use methods eference variables (OOP purity) notationto as rshown in Sample 5.8. Sample 5.8 Using variables and routines in an object Transaction t; t = new(); t.addr = 32’h42; t.display(); // // // // Declare a handle to a Transaction Construct a Transaction object Set the value of a variable Call a routine In strict OOP, the only access to variables in an object should be through its public methods such as get() and put(). This is because accessing variables directly limits your ability to change the underlying implementation in the future. If a better (or simply different) algorithm comes along in the future, you may not be able to adopt it because you would also need to modify all of the references to the variables. The problem with this methodology is that it was written for large software applications with lifetimes of a decade or more. With dozens of programmers making modifications, stability is paramount. However, you are creating a testbench, where the goal is maximum control of all variables to generate the widest range of stimulus values. One of the ways to accomplish this is with constrained-random stimulus generation, which cannot be done if a variable is hidden behind a screen of methods. While the get() and put() methods are fine for compilers, GUIs, and APIs, you 10 5.9.1 A Simple Static Variable In SystemVerilog you can create a static variable inside a class. This variable is shared amongst all instances of the class, but its scope is limited to the class. In Sample 5.9, the static variable count holds the number of objects created so far. It is initialized to 0 in the declaration because there are no transactions at the beginning of the simulation. Each time a new object is constructed, it is tagged with a unique value, Objects have their own iscopies of their proper/es (variables) incremented. and count Sta/c (class) variables A class can also Sample declare proper/es (variables) that are shared among all objects 5.9 Class with a static variable in the class 136 class Transaction; Chapter 5:Basic OOP static int count = 0; // Number of objects created int id; // Unique instance ID function new(); 5.9.2 Accessing Static Variables Through the Class Name id = count++; // Set ID, bump count endfunction Sample endclass 5.9 showed how you can reference a static variable using a handle. You don?t need a handle; you could use the class name followed by ::, the class scope resolu tion operator as shown int1, Sample Transaction t2; 5.10 initial begin Sample 5.10t1The scope resolution operator = class new(); // 1st instance, id=0, count=1 t2 = new(); // 2nd instance, id=1, count=2 class Transaction; $display("Second id=%d, count=%d", t2.id, t2.count); static int count = 0; // Number of objects created end ... endclass In cSample there is only copy of the static variable count, regardless of how Class proper/es an be 5.9, accessed via one the class name Transaction objects are created. You can think that count is stored with the many initial begin class and not the object. The variable id is not static, and so every Transaction has run_test(); its own copy,transaction as shown in Figure Now you donLt need to make a global variable $display("%d were 5-2. created", Transaction::count); for the count. end Figure 5-2 Static variables in a class 5.9.3 Initializing Static Variables // Reference static w/o handle 11 138 Sta/c methods Chapter 5:Basic OOP Sample 5.12 Static method displays static variable class Transaction; static Config cfg; static int count = 0; int id; // Static method to display static variables. static function void display_statics(); $display("Transaction cfg.mode=%s, count=%0d", cfg.mode.name(), count); endfunction endclass Config cfg; initial begin cfg = new(MODE_ON); Transaction::cfg = cfg; Transaction::display_statics(); end // Static method call 5.10 Class Methods A method in a class is just a task or function defined inside the scope of the class. Sample 5.13 defines display() methods for the Transaction and PCI_Tran. 12 Defining Methods Outside of the Class Class methods 139 Sample 5.13 Routines in the class class Transaction; bit [31:0] addr, crc, data[8]; function void display(); $display("@%0t: TR addr=%h, crc=%h", $time, addr, crc); $write("\tdata[0-7]="); foreach (data[i]) $write(data[i]); $display(); endfunction endclass class PCI_Tran; bit [31:0] addr, data; // Use realistic names function void display(); $display("@%0t: PCI: addr=%h, data=%h", $time, addr, data); endfunction endclass Transaction t; PCI_Tran pc; initial begin t = new(); t.display(); pc = new(); pc.display(); end // // // // Construct Display a Construct Display a a Transaction Transaction a PCI transaction PCI Transaction A method in a class uses automatic storage by default, and so you don9t have to worry 13 140 Chapter 5:Basic OOP Defining methods outside the class two colons (:: the scope operator) before the method name. The above classes could be defined as follows. Sample 5.14 Out-of-block method declarations class Transaction; bit [31:0] addr, crc, data[8]; extern function void display(); endclass function void Transaction::display(); $display("@%0t: Transaction addr=%h, crc=%h", $time, addr, crc); $write("\tdata[0-7]="); foreach (data[i]) $write(data[i]); $display(); endfunction class PCI_Tran; bit [31:0] addr, data; // Use realistic names extern function void display(); endclass function void PCI_Tran::display(); $display("@%0t: PCI: addr=%h, data=%h", $time, addr, data); endfunction A common coding mistake is when the method prototype does not14 match the one in the body. SystemVerilog requires that the prototype be identical to the out-of-block method declaration, except for 142 Scope (review) Chapter 5:Basic OOP Sample 5.16 Name scope int limit; // $root.limit program automatic p; int limit; // $root.p.limit class Foo; int limit, array; // $root.p.Foo.limit // $root.p.Foo.print.limit function void print (int limit); for (int i=0; i<limit; i++) $display("%m: array[%0d]=%0d", i, array[i]); endfunction endclass initial begin int limit = $root.limit; // **see note above Foo bar; bar = new(); bar.array = new[limit]; bar.print (limit); end endprogram For testbenches, you can declare variables in the program or in the initial block. If a variable is only used inside a single initial block, such as a counter, you should 15 Scope Why declare classes in packages Scoping Rules 143 Sample 5.17 Class uses wrong variable program test; int i; // Program-level variable class Bad; logic [31:0] data; // Calling this function changes the program variable function void display; // Forgot to declare i in next statement for (i=0; i<data.size(); i++) $display("data[%0d]=%x", i, data[i]); endfunction endclass endprogram If you move the class into a package, the class cannot see the program-level variables, and thus won>t use them unintentionally. Sample 5.18 Move class into package to find bug package Mistake; class Bad; logic [31:0] data; // Will not compile because of undeclared i 16 function void display; // Forgot to declare i in next statement for (i=0; i<data.size(); i++) $display("data[%0d]=%x", i, data[i]); endfunction endclass endprogram Scope Why declare classes in packages If you move the class into a package, the class cannot see the program-level variables, and thus won>t use them unintentionally. Sample 5.18 Move class into package to find bug package Mistake; class Bad; logic [31:0] data; // Will not compile because of undeclared i function void display; for (i = 0; i<data.size(); i++) $display("data[%0d]=%x", i, data[i]); endfunction endclass endpackage program test; int i; // Program-level variable import Mistake::*; ... endprogram 5.12.1 What is this? When you use a variable name, SystemVerilog looks in the current scope for it, and17 then in the parent scopes until the variable is found. This is the same algorithm used by Verilog. What if you are deep inside a class and want to unambiguously refer to a classlevel object? This style code is most commonly used in constructors, where the pro- 14...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture