[comp.lang.misc] Calling functions by address

pardo@june.cs.washington.edu (David Keppel) (08/31/88)

First, a "leading question" for those who don't want to read the
rest of this article: Can somebody describe for me "knotted code",
as compared to "threaded code"?

In article <679@mssx.UUCP> src@mssx.UUCP (Pleschutznig Andreas) writes:
>[ Emulation for another processor ]
>[ "switch(opcode){ case AAA: [...]" isn't fast enough ]

You can dereference a pointer to a function by the following:

    typedef void (*fptr_t)();
    fptr_t instruction[ OPCODES ] = { opc_aaa, ... };

	(*(instruction[opcode]))();

This still involves a function call/return overhead.  In high-
performance virtual machine interpreters such as Smalltalk, "threaded"
interpreters are often used.  To the best of my knowledge, threaded
code cannot be generated portably from C.  It may be possible to
generate by writing a special set of #defines and "fake functions",
having the compiler generate assembly, and then walking over the
assembly to generate the threading tables and the transfer sequences.

Original:

    main:
	jsb	foo
	jsb	bar
	<...>

    foo:
	<...>
	rsb

    bar:
	<...>
	rsb


Threaded:

    codeptrs:
	.long	foo
	.long	bar

    main:
	movl	&codeptrs,r4
	jmp	(r4)
	<...>
    
    foo:
	<...>
	jmp	*(r4)+

    bar:
	<...>
	jmp	*(r4)+
    
    

Citations Follow:
%A James R. Bell
%T Threaded Code
%J CACM
%V 16
%N 6
%D JUN 1973
%P 370-372

%A Robert B. K. Dewar
%T Indirect Threaded Code
%J CACM
%V 18
%N 6
%D JUN 1975
%P 330-331

	;-D on  ( To be conflagnulated )  Pardo
-- 
		    pardo@cs.washington.edu
    {rutgers,cornell,ucsd,ubc-cs,tektronix}!uw-beaver!june!pardo

jax@well.UUCP (Jack J. Woehr) (09/01/88)

In article <5595@june.cs.washington.edu> pardo@cs.washington.edu (David Keppel) writes:
>(much deleted) To the best of my knowledge, threaded
>code cannot be generated portably from C.  It may be possible to
>generate by writing a special set of #defines and "fake functions",
>having the compiler generate assembly, and then walking over the
>assembly to generate the threading tables and the transfer sequences.

	Got the obvious answer, son ... learn Forth!

**********
jax@well	: INSIGHT ( ---) FORTH-PROGAMMER IF DONE-WORK-EARLY
jax@chariot	   ELSE C-PROGRAMMER IF STAY-LATE THEN THEN ." :-)" ;
JAX on GEnie