Functions in VHDL

Functions are central in VHDL. We’ll learn about functions with a few different examples.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity functions_example is
end functions_example;

architecture Behavioral of functions_example is
    -- Here's a function that takes two integers and returns their sum as an integer.
    function plus(a : integer; b : integer) return integer is
    begin
        -- VHDL requires explicit returns, i.e. it won't
        -- automatically return the value of the last
        -- expression.
        return a + b;
    end function;

    -- In VHDL, you can't omit the type name for parameters,
    -- even if they are of the same type.
    function plusPlus(a : integer; b : integer; c : integer) return integer is
    begin
        return a + b + c;
    end function;

begin
    process
        variable res : integer;
    begin
        -- Call a function just as you'd expect, with
        -- name(args).
        res := plus(1, 2);
        report "1+2 = " & integer'image(res);

        res := plusPlus(1, 2, 3);
        report "1+2+3 = " & integer'image(res);

        wait;
    end process;
end Behavioral;

To run this VHDL code, you would typically use a VHDL simulator. The output would look something like this:

# 1+2 = 3
# 1+2+3 = 6

There are several other features to VHDL functions. One is the ability to have multiple return values using “out” parameters, which we’ll look at next.

In VHDL, functions are typically used for operations that can be completed in a single simulation cycle, while procedures (similar to functions but can have side effects) are used for more complex operations that might take multiple cycles.

VHDL functions are often used in combinational logic design, while processes (which we used here to demonstrate the function calls) are more commonly used for sequential logic.

Remember that VHDL is primarily used for hardware description, so these functions are actually describing combinational logic circuits, not software functions as in many other languages.