4. 使用UVM factory机制覆盖组件

任务目标

在UVM测试平台中,使用factory机制将基类driver替换为扩展driver,验证override功能生效。通过打印日志确认测试中实际创建的是扩展组件而非基类组件。

环境依赖

需要标准UVM库(UVM-1.2或IEEE 1800.2),仿真器支持UVM(如VCS、QuestaSim、Xcelium)。以下代码基于UVM-1.2编写。

关键完整代码

// 文件: tb_top.sv
`include "uvm_macros.svh"
import uvm_pkg::*;

// 基类driver
class base_driver extends uvm_driver #(int);
    `uvm_component_utils(base_driver)
    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction
    virtual task run_phase(uvm_phase phase);
        `uvm_info("BASE_DRV", "Base driver is running", UVM_LOW)
    endtask
endclass

// 扩展driver(override目标)
class ext_driver extends base_driver;
    `uvm_component_utils(ext_driver)
    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction
    virtual task run_phase(uvm_phase phase);
        `uvm_info("EXT_DRV", "Extended driver is running", UVM_LOW)
    endtask
endclass

// 环境:创建driver实例
class my_env extends uvm_env;
    `uvm_component_utils(my_env)
    base_driver drv;
    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction
    function void build_phase(uvm_phase phase);
        super.build_phase(phase);
        drv = base_driver::type_id::create("drv", this);
    endfunction
endclass

// 测试:在build_phase中执行override
class my_test extends uvm_test;
    `uvm_component_utils(my_test)
    my_env env;
    function new(string name, uvm_component parent);
        super.new(name, parent);
    endfunction
    function void build_phase(uvm_phase phase);
        super.build_phase(phase);
        // 关键:将base_driver替换为ext_driver
        base_driver::type_id::set_type_override(ext_driver::get_type());
        env = my_env::type_id::create("env", this);
    endfunction
    task run_phase(uvm_phase phase);
        phase.raise_objection(this);
        #10;
        phase.drop_objection(this);
    endtask
endclass

module tb_top;
    initial begin
        run_test("my_test");
    end
endmodule

运行方式

# 使用QuestaSim示例(其他仿真器命令类似)
vlib work
vlog +incdir+$UVM_HOME/src $UVM_HOME/src/uvm_pkg.sv tb_top.sv
vsim -c -do "run -all; quit" work.tb_top

验证方法与判定标准

仿真运行后,观察日志输出。若override机制生效,应看到:

UVM_INFO ext_driver.sv(12) @ 0: uvm_test_top.env.drv [EXT_DRV] Extended driver is running

同时不应出现BASE_DRV消息。若看到BASE_DRV消息,说明override未生效,需检查set_type_override调用是否在create之前执行,以及两个类是否都已正确注册到factory。

常见问题

  • override未生效:确认set_type_override在create之前调用,且两个类都使用了`uvm_component_utils宏注册。
  • 编译错误:检查UVM库路径是否正确,以及是否在模块前import uvm_pkg::*。
  • 只看到基类消息:若override调用位置正确但仍无效,检查是否在build_phase中先创建了env再执行override——必须先在build_phase中执行override,再创建需要被替换的组件。