Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Virtual Interface: A Complete Example

SystemVerilog Interfaces & Modports

Runnable example from the SystemVerilog Virtual Interface tutorial (A Complete Example)

Open in IDE
design.sv
interface req_gnt_if (input logic clk);
  logic req;
  logic gnt;
  logic rstn;

  clocking cb @(posedge clk);
    default input #1step output #2ns;
    output req;
    input  gnt;
  endclocking

  modport TB (clocking cb, output rstn);
endinterface

class Driver;
  virtual req_gnt_if.TB vif;   // handle only - no signals of its own

  function new (virtual req_gnt_if.TB vif);
    this.vif = vif;
  endfunction

  task drive_req (bit value);
    vif.cb.req <= value;
  endtask
endclass
testbench.sv
module des (input logic clk, req, rstn, output logic gnt);
  always @ (posedge clk or negedge rstn)
    if (!rstn) gnt <= 0;
    else       gnt <= req;
endmodule

module tb;
  logic clk;
  always #10 clk = ~clk;

  req_gnt_if vif (.clk(clk));
  des dut (.clk(clk), .req(vif.req), .rstn(vif.rstn), .gnt(vif.gnt));

  Driver drv;

  initial begin
    vif.rstn <= 0;
    repeat (3) @(posedge clk);
    vif.rstn <= 1;

    // Pass the physical interface instance into the class through its constructor -
    // SystemVerilog automatically converts it to a virtual interface handle here
    drv = new (vif);

    repeat (2) @(posedge clk);
    drv.drive_req(1);

    repeat (5) @(posedge clk);
    $finish;
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.