ReturnType FunctionName(Type1 Arg1, Type2 Arg2, Type3 Arg3 = DefaultValue3)
{
function_body;
}
Functions can be templated and the template arguments can be derived from the call context.
A function can contain assignment statements, function calls and the following statements:
Functions can be declared inside classes, entities, namespaces and in the global scope.
Function arguments can have default values similar to C++ and can contain direction modifiers (
Note that if a function modifies its input arguments, a local copy is created. This behavior is similar to C/C++.
logic[8] AddOne(logic[8] x)
{
return x + 1;
}
entity Test
{
port in logic clk;
signal logic[8] Counter;
process count (clk.rising)
{
Counter = AddOne(Counter);
}
}
generate_vhdl(Test);
The following VHDL code will be generated:
function Add_One (x: std_logic_vector(7 downto 0)) return std_logic_vector is
variable thp_typed_result_buffer : std_logic_vector(7 downto 0);
begin
thp_typed_result_buffer := (x + X"01");
return thp_typed_result_buffer;
end function Add_One;
...
count : process (clk) is
begin
if rising_edge(clk) then
Counter <= Add_One(Counter)(7 downto 0);
end if;
end process count;
The thp_typed_result_buffer variable is a workaround for Xilinx synthesis tools bug.
template <any _DataType> _DataType AddOne(_DataType x)
{
return x + 1;
}
Normally, the template arguments should be specified in the function calls:
Counter = AddOne<logic[8]>(Counter);
However, if a template argument defines the type of a function argument, it will be derived automatically. The following code will produce the same result:
Counter = AddOne(Counter);
It is also equivalent to the following construct:
Counter = AddOne<typeof(Counter)>(Counter);
THDL++ compiler will convert functions called by other synthesized code into VHDL functions. Note that the functions are converted "on demand". I.e. the following algorithm is performed for every function used by any synthesized entity:
1. If the function with the same template arguments is already converted to VHDL, do nothing.
2. If not, convert the function to VHDL, statement after statement.
3. For all functions called from the function, recursively invoke the same algorithm.