Functions

Declaration ---- used in ----> Package
EntityProcess
Procedure
Function


Syntax

function function_name (parameter_list) return type is
	declarations
begin
	sequential statements
end function_name;

See LRM sections 2.1, 2.2 and 7.3.3


Rules and Examples

A function can only have input parameters, so the mode (direction) is not specified.
function BOOL_TO_SL(X : boolean)
              return std_ulogic is
begin
  if X then
    return '1';
  else
    return '0';
  end if;
end BOOL_TO_SL;

A function may declare local variables. These do not retain their values between successive calls, but are re-initialised each time. Array-type parameters may be unconstrained:
function PARITY (X : std_ulogic_vector)
                 return std_ulogic is
  variable TMP : std_ulogic := '0';
begin
  for J in X'range loop
    TMP := TMP xor X(J);
  end loop; -- works for any size X
  return TMP;
end PARITY;

A function may contain any sequential statement except signal assignment and wait. A type-conversion function may be called in a port map, to match port type to signal type.
If a function is defined in a package, its body (the algorithm part) must be placed in the package body:
package REF_PACK is
  function PARITY (X : bit_vector)
                   return bit;
end REF_PACK;

package body REF_PACK is
  function PARITY (X : bit_vector)
                   return bit is  
  begin
    -- function code
  end PARITY;
end REF_PACK;

A function is called as an expression, in either a concurrent or sequential statement:
architecture FUNCTIONS of PAR is
begin
  PARITY_BYTE <= PARITY(DATA_BYTE);
  PARITY_WORD <= PARITY(DATA_WORD);
end FUNCTIONS;


Synthesis Issues

User-defined functions are usually supported for synthesis, providing they act on suitable data types. Different synthesis tools recognise various different type conversion and resolution functions. Most accept those deined in the std_logic_1164 package.


Whats New in '93

In VHDL-93, functions may be declared as pure or impure. A pure function is the default, and is compatible with VHDL-87. The value returned by an impure function can depend on items other than just its input parameters (e.g.shared variables).

In VHDL-93, the keyword end may be followed by the keyword function for clarity and consistancy.