Search code examples
verilogsystem-verilogtest-bench

Invoking function present in a higher module


My SystemVerilog (non-UVM) code has the below structure:

tb instantiates wrapper which instantiates another module A.

From a function inside module A, how I can call a function inside tb?

I tried invoking tb.function; however during simulation stage, we run into the below error:

NULL pointer dereference, Verilog stack trace for tb_top.function


Solution

  • You can directly call the function declared in the higher module from the lower module, without using a hierarchical path. Or, you can use the top module name. Both of these calls work:

    module A;
        function void afunc;
            $display("Hello from %m");
            tbfunc();
            tb.tbfunc();
        endfunction
        initial afunc();
    endmodule
    
    module tb;
        function void tbfunc;
            $display("Hello from %m");
        endfunction
    
        A A ();
    endmodule
    

    Prints:

    Hello from tb.A.afunc
    Hello from tb.tbfunc
    Hello from tb.tbfunc
    

    Refer to IEEE Std 1800-2017, section 23.8 Upwards name referencing:

    A lower level module can reference items in a module above it in the hierarchy. ... For tasks, functions, named blocks, and generate blocks, SystemVerilog shall look in the enclosing module for the name until it is found or until the root of the hierarchy is reached.

    Note: from your error message (tb_top.function), it looks like you are using the function keyword instead of the name that you gave to the function. That is not allowed.