Procedures as arguments and procedure pointers

A procedure name is a value in Fortran, but a value of its own kind: it can be passed to another procedure, stored in a pointer and called later. That is how a library writes one solver, one integrator or one sort and lets the caller supply the function. This lesson passes a function as an argument, gives the argument a shape with an abstract interface, holds a function in a procedure pointer, and builds a table of functions to call in a loop.

A dummy procedure

The dummy argument is declared with procedure(fun1) :: f, where fun1 is an interface. Inside apply the name f is called like any function; which function it is was decided by the caller. The same module also holds a procedure(fun1), pointer in the program below, so one build shows both mechanisms.

The file proc.f90:

module funs implicit none abstract interface function fun1(x) result(y) real, intent(in) :: x real :: y end function fun1 end interface contains pure function square(x) result(y) real, intent(in) :: x real :: y y = x * x end function square pure function cube(x) result(y) real, intent(in) :: x real :: y y = x * x * x end function cube function apply(f, x) result(y) procedure(fun1) :: f real, intent(in) :: x real :: y y = f(x) end function apply end module funs program procdemo use funs implicit none procedure(fun1), pointer :: p => null() print '(a,f8.2)', 'apply(square) = ', apply(square, 3.0) print '(a,f8.2)', 'apply(cube) = ', apply(cube, 2.0) p => square print '(a,f8.2)', 'p(5.0) via square = ', p(5.0) p => cube print '(a,f8.2)', 'p(5.0) via cube = ', p(5.0) end program procdemo

gfortran -Wall -Wextra -std=f2018 proc.f90 -o proc
./proc

apply(square) = 9.00
apply(cube) = 8.00
p(5.0) via square = 25.00
p(5.0) via cube = 125.00

Four lines and no dispatch written by hand: apply is compiled once and works for any function that matches fun1, and the pointer holds one of the module procedures and can be changed at run time. A procedure dummy is the static form of the same idea; a procedure pointer is the form that can be reseated.

The abstract interface

abstract interface ... end interface declares a shape of a procedure and nothing else: there is no body anywhere, and the name fun1 can only be used where a procedure is declared. An ordinary interface block would also do, but it exists to name procedures that are written somewhere else, and then every reader looks for a body that does not exist.

The shape is what makes the call work. f(x) inside apply is checked at compile time against fun1: one real argument in, a real result out. Without the interface the compiler would have to guess, and the guess is the old assumption that a name starting with F is a real function of unknown arguments.

PROCEDURE pointers

procedure(fun1), pointer :: p => null() declares a pointer whose target is a procedure. p => square is a pointer assignment, not a call, and it may happen as often as the program likes; p(5.0) calls whatever is in it. The => null() initialisation is worth writing: an uninitialised pointer is undefined, and associated(p) on a null pointer answers .false. instead of reading garbage.

A procedure pointer may only be a scalar. An array of them is not allowed by the standard; a table of functions is an array of a derived type with a pointer component, which is the next section.

A table of functions

The type op holds a name and a pointer to a function with the shape fun1. An array of op is a dispatch table: the loop does not know which function it calls, and a caller can add a row without touching the loop. nopass says the function is a plain one and takes no object of the type as its first argument, which is what keeps ops(i)%f(3.0) a call with one argument.

The file dtable.f90:

module funs implicit none abstract interface function fun1(x) result(y) real, intent(in) :: x real :: y end function fun1 end interface type :: op character(len=8) :: name procedure(fun1), pointer, nopass :: f => null() end type op contains pure function square(x) result(y) real, intent(in) :: x real :: y y = x * x end function square pure function cube(x) result(y) real, intent(in) :: x real :: y y = x * x * x end function cube end module funs program dtable_demo use funs implicit none type(op) :: ops(3) integer :: i ops(1)%name = 'square' ops(1)%f => square ops(2)%name = 'cube' ops(2)%f => cube ops(3)%name = 'square' ops(3)%f => square do i = 1, size(ops) print '(a,f8.2)', trim(ops(i)%name) // '(3.0) =', ops(i)%f(3.0) end do end program dtable_demo

gfortran -Wall -Wextra -std=f2018 dtable.f90 -o dtable
./dtable

square(3.0) = 9.00
cube(3.0) = 27.00
square(3.0) = 9.00

A table like this is what a command dispatcher, a set of numerical methods or a list of output formats looks like without a long select case. The row is a value: it can be built from a configuration file, filtered before the loop, or passed to another procedure whole.

An internal procedure as an argument

Any procedure with the right shape can be passed, including one contained in the program. gfortran builds that call through a small generated stub, and warns about what the stub costs:

The file inner.f90:

module funs implicit none abstract interface function fun1(x) result(y) real, intent(in) :: x real :: y end function fun1 end interface contains function apply(f, x) result(y) procedure(fun1) :: f real, intent(in) :: x real :: y y = f(x) end function apply end module funs program inner_demo use funs implicit none print '(a,f8.2)', 'half(9.0) = ', apply(half, 9.0) contains function half(x) result(y) real, intent(in) :: x real :: y y = x / 2.0 end function half end program inner_demo

gfortran -Wall -Wextra -std=f2018 -c inner.f90
gfortran inner.o -o inner
./inner

inner.f90:25:2:

25 | function half(x) result(y)
| ^
Warning: trampoline generated for nested function 'half' [-Wtrampolines]
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld: warning: inner.o: requires executable stack (because the .note.GNU-stack section is executable)
half(9.0) = 4.50

A trampoline is a few bytes of code on the stack that carries the environment of the host procedure, and the stack has to be executable for it to work. That is a real cost: the program runs, and every security policy that forbids an executable stack will refuse it. Moving half into a module makes the warning and the requirement disappear, which is one more reason module procedures are the default in this course.

A mismatching interface

The pointer is checked against the shape it was declared with, and a function of another type does not fit:

module funs implicit none abstract interface function fun1(x) result(y) real, intent(in) :: x real :: y end function fun1 end interface contains function intfun(n) result(r) integer, intent(in) :: n integer :: r r = n * 2 end function intfun end module funs program mismatch use funs implicit none procedure(fun1), pointer :: p => null() p => intfun print '(a,f8.2)', 'p(3.0) = ', p(3.0) end program mismatch

gfortran -Wall -Wextra -std=f2018 miss.f90 -o miss

miss.f90:22:7:

22 | p => intfun
| 1
Error: Interface mismatch in procedure pointer assignment at (1): Type mismatch in function result (REAL(4)/INTEGER(4))

The compiler compares the whole shape: the types and kinds of the arguments, the type of the result and whether the procedure is a function or a subroutine. The same check runs for a dummy procedure, where the message is about the argument of the call. This is the part of Fortran that old code could not have: before Fortran 90 the compiler saw a name and a type and nothing else.

Which of the three

A plain module call is the default: the compiler knows everything and the call is as fast as it gets. A procedure dummy is the right tool when the choice is made once, by the caller, at the moment of the call: an integrator takes the function it integrates, a sort takes the comparison. A procedure pointer is the right tool when the choice changes during the run or is stored with data: a table, a plug-in, a callback in a library that has to switch.

A pointer call is an indirect call and cannot be inlined. For a function called once per row that does not matter; for one called a million times inside a loop it can be most of the run time. When the loop is the bottleneck, put the pointer assignment outside the loop and pass the result to a procedure that takes a dummy procedure argument instead, which gives the compiler a direct call it can still not inline but can at least keep out of the dependency chain.

Exercises

  1. Add a function negate to proc.f90 and print apply(negate, 3.0). What has to change in the module?
  2. Declare p without => null() and add if (associated(p)) before the first call. What does the program do without the initialisation?
  3. Add a fourth row to the table in dtable.f90 whose function is intfun from the last section. Read the error.
  4. Move half from the program into the module and build inner.f90 again. Which warnings disappear?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does procedure(fun1) :: f declare?

    Answer

    A dummy argument that is a procedure with the shape of fun1

    The dummy is a procedure, and fun1 gives its interface.

  2. What is an abstract interface for?

    Answer

    It declares the shape of a procedure and has no body

    The name is only usable where a procedure is declared.

  3. What does p => square do to a procedure pointer?

    Answer

    Points it at the procedure; it is not a call

    The arrow is a pointer assignment.

  4. Why write => null() on a procedure pointer?

    Answer

    So associated(p) is false and a call is a clear error, not garbage

    An uninitialised pointer has an undefined association status.

  5. What does this program print? module m implicit none abstract interface function f1(x) result(y) integer, intent(in) :: x integer :: y end function f1 end interface contains function dbl(x) result(y) integer, intent(in) :: x integer :: y y = 2 * x end function dbl end module m program p use m implicit none procedure(f1), pointer :: q => null() q => dbl print *, q(4) end program p

    Answer

    8

    dbl doubles its argument, and the pointer calls it.

  6. Why is an array of procedure pointers not allowed?

    Answer

    The standard requires a procedure pointer to be scalar

    A table of functions is an array of a type with a pointer component.

  7. What does nopass on a procedure pointer component mean?

    Answer

    The procedure does not take the object as its first argument

    Without nopass a binding passes the object in front.

  8. What does gfortran warn about when an internal procedure is passed as an argument?

    Answer

    A trampoline is generated and the stack must be executable

    The generated stub carries the host environment on the stack.

  9. What does gfortran report when a pointer is pointed at a function of another type?

    Answer

    Interface mismatch in procedure pointer assignment

    The whole shape of the target is compared with the declaration.

  10. When is a procedure pointer better than a dummy procedure argument?

    Answer

    When the choice is made or changed during the run, or stored with data

    A dummy procedure fixes the choice at the call.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev