% BEGIN LICENSE BLOCK
% Version: CMPL 1.1
%
% The contents of this file are subject to the Cisco-style Mozilla Public
% License Version 1.1 (the "License"); you may not use this file except
% in compliance with the License.  You may obtain a copy of the License
% at www.eclipse-clp.org/license.
% 
% Software distributed under the License is distributed on an "AS IS"
% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
% the License for the specific language governing rights and limitations
% under the License. 
% 
% The Original Code is  The ECLiPSe Constraint Logic Programming System. 
% The Initial Developer of the Original Code is  Cisco Systems, Inc. 
% Portions created by the Initial Developer are
% Copyright (C) 1994 - 2006 Cisco Systems, Inc.  All Rights Reserved.
% 
% Contributor(s): 
% 
% END LICENSE BLOCK
%
% @(#)umscompiler.tex	1.9 94/07/15 
%
% \comment{@(\#)text1.mss	20.4 9/19/88}
%
% REL	 DATE		BY		DESCRIPTION	
% 3.0.17 10.10.91	Micha Meier	Created the file
%
%----------------------------------------------------------------------
\chapter{The Compiler}
\label{chapcompiler}
%HEVEA\cutdef[1]{section}
%----------------------------------------------------------------------

{\eclipse} has an efficient incremental compiler which compiles
Prolog source into the instructions of an abstract machine
and they are then executed by an emulator.
The compiler is very fast, it compiles about 1000 lines/sec.
on a Sun-4, and this makes the usual debugging cycle acceptably short.
Unlike other Prolog systems, the {\eclipse} compiler generates
code that can be used for debugging, so that no separate
interpreter is necessary, and also the debugged code runs faster.

The {\eclipse} compiler is interactive and incremental, which means
that Prolog programs are compiled during a {\eclipse} session
directly into the Prolog database.

In addition, object code of {\eclipse} programs can be generated and stored
into a file, which can then be loaded into a different session of
{\eclipse}. See section~\ref{fcompile} for more details.

%----------------------------------------------------------------------
\section{Program Source}
%----------------------------------------------------------------------
When reading the input source, the compiler distinguishes
{\it clauses} and {\it directives}.
Directives are terms with main functor
{\bf :-/1}
or
{\bf ?-/1}.
When the compiler encounters them, it executes immediately
their first argument as a Prolog goal.
If this goal succeeds, the compiler continues to the next
input term without reporting the answer to the user.
If the directive fails, an event is raised.

All other input terms are interpreted as clauses to be compiled.
A sequence of consecutive clauses whose heads have the same
functor is interpreted as one procedure, and so e.g.
if the clauses of one procedure are mixed with directives or
with clauses for another procedure, the compiler
takes them as several different procedures.
To allow the user to write non-consecutive procedures,
the compiler raises an event whenever it
encounters several procedures with the same name and arity
in one file, or when a procedure defined in one file
is being redefined in another file.
Default action for the former is to emit a warning,
for the latter the new procedure just replaces the old one.
The library {\bf scattered} redefines the former handler
\index{scattered (library)}
so that procedures which are scattered in one file are accepted
as normal static procedures.

%----------------------------------------------------------------------
\section{Procedure Types}
%----------------------------------------------------------------------
Procedures can be {\bf static} and {\bf dynamic}
and this feature can be queried with the {\tt stability} flag
of \bipref{get_flag/3}{../bips/kernel/database/get_flag-3.html}.

Static procedures are compiled as one unit, they are thus executed
more efficiently, and they can be modified only by replacing
them by another procedure.
By contrast, dynamic procedures are compiled clause-wise,
they are executed slightly less efficiently, but their source
form can also be retrieved, and they can be modified
by adding or removing single clauses or clause sequences.

By default all procedures are static, dynamic procedures
must be declared by the \bipref{dynamic/1}{../bips/kernel/dynamic/dynamic-1.html} declaration,
except that undefined procedures for which \bipref{assert/1,2}{../bips/kernel/dynamic/assert-1.html}
is called are silently declared as dynamic by the event handler,
and so no declaration is needed.

When compiling static procedures, the compiler remembers
their position in the file, which can be then queried
by \bipref{get_flag/3}{../bips/kernel/database/get_flag-3.html}.
The library {\bf scattered} actually uses this feature
to retrieve predicates whose clauses are not consecutive.

%----------------------------------------------------------------------
\section{Compiler Modes}
%----------------------------------------------------------------------
The compiler has several modes of operation, each mode
generating code with different properties.
The operating mode is controlled by a set of global flags,
which may be modified at any time, even during the compilation
so that a part of the program is compiled in a different mode.
These flags and the associated modes are listed below.

\begin{description}
\item [] \biptxtref{debug_compile}{get_flag/2}{../bips/kernel/env/get_flag-2.html}
When this flag is {\bf on}, the compiler generates code which can
be traced with the debugger.
To generate optimised (untraceable) code, this flag must be switched off.
This can also be achieved by the use of nodebug compiler pragma in the
program:

\begin{quote}
\begin{verbatim}
:- pragma(nodebug).
\end{verbatim}
\end{quote}

\item[] {\bf occur_check}
\index{occur check}
When this flag is {\bf on}, the compiled code will perform
the {\it occur check} if necessary.
This means that every time a variable will be unified
with a compound term that might already contain a reference
to this variable, the compound term will be scanned for this occurrence
and if it is found, the unification fails.
In this way, the creation of infinite (cyclic) terms is impossible
and thus the behaviour of the system is closer
to the first order logic theory.
Unifications with the occur check may sometimes be very slow,
and most Prolog programs do not need it, because
no cyclic terms are created.
Note that this flag must be set both at compile time and at runtime in order
to actually perform the checks. In particular, as {\eclipse} built-ins are
compiled without this flag set, the builtins will not perform the check.

\item [] \biptxtref{variable_names}{get_flag/2}{../bips/kernel/env/get_flag-2.html}
\index{variable names}
{\eclipse} can remember the source variable names of the input variables.
When this flag is {\bf on}, the compiled predicates
will keep the names of the source variables and will display
them whenever the variables are printed.
In this case the usage of the global stack and code space is slightly higher
(to store the name), and the efficiency of the code is marginally lower.
\index{singleton variables}
Setting this flag to \biptxtref{check_singletons}{get_flag/2}{../bips/kernel/env/get_flag-2.html} has the same effect as {\bf on},
but additionally, the compiler will issue warnings about variables which occur
only once in a clause and whose names do not start with an underscore character.

\item [] \biptxtref{all_dynamic}{get_flag/2}{../bips/kernel/env/get_flag-2.html}
When this flag is {\bf on}, all procedures are compiled
as dynamic ones (and there is no equivalent {\bf static/1}
declaration).
It can be used to port programs from older interpreters
which rely heavily on the fact that all predicates
in these interpreters were dynamic.
Another possible use is to switch it on at the beginning of a file
that contains many dynamic predicates and switch it off at its end.

\item [] \biptxtref{macro_expansion}{get_flag/2}{../bips/kernel/env/get_flag-2.html}
This is in fact a parser flag, is enables or disables the macro transformation
(see Chapter \ref{chapmacros}) for the input source.

\item [] \biptxtref{goal_expansion}{get_flag/2}{../bips/kernel/env/get_flag-2.html}
Specifies whether to apply goal-macros or not (see Chapter \ref{chapmacros}).
\end{description}

%----------------------------------------------------------------------
\section{Compiler Input}
%----------------------------------------------------------------------
The compiler normally reads a file up to its end.
The file end can also be simulated with a clause
\begin{verbatim}
end_of_file.
\end{verbatim}
The file is normally read consecutively, however
the compiler uses the normal {\eclipse} I/O streams,
and so if during the compilation the stream pointer is modified
(e.g. by \bipref{seek/2}{../bips/kernel/iostream/seek-2.html} or \bipref{read/2}{../bips/kernel/ioterm/read-2.html}), the compiler continues
at the specified place\footnote{An example of using this feature
\index{ifdef (library)}
is the library {\bf ifdef}.}.

There are several built-in predicates which invoke the compiler:

\begin{description}
\item[] \biptxtref{compile(File)}{compile/1}{../bips/kernel/database/compile-1.html}
\index{compile/1}
This is the standard compiler predicate.
The contents of the file is compiled according to the current
state of the global flags.

\item[] \biptxtref{compile(File, Module)}{compile/2}{../bips/kernel/database/compile-2.html}
\index{compile/2}
This predicate is used to compile the contents of a file into
a specified module, without having to use the module declaration
in the file itself.

\item[] \biptxtref{include(File)}{include/1}{../bips/kernel/directives/include-1.html}
\index{include/1}
This predicate is similar to the {\bf compile} predicate, except that it is
treated as an in place inclusion of {\bf File} by \bipref{fcompile/1}{../bips/lib/fcompile/fcompile-1.html} (see 
section~\ref{fcompile}). Like {\bf compile}, {\bf File} can be a single
file, or a list of files.

\item[] \biptxtref{compile_stream(Stream)}{compile_stream/1}{../bips/kernel/database/compile_stream-1.html}
\index{compile_stream/1}
This predicate compiles a given stream up to its end
or to the {\tt end_of_file} clause.
It can be used when the input file is already open,
e.g. when the beginning of the file does not contain
compiler input, or when the input has to be processed
in a non-consecutive way.

\item[] \biptxtref{compile_term(Clauses)}{compile_term/1}{../bips/kernel/database/compile_term-1.html}
\index{compile_term/1}
This predicate is used to compile a given term,
usually a list of clauses and directives.
Unlike \bipref{assert/1}{../bips/kernel/dynamic/assert-1.html} it compiles a static procedure,
and so it can be used to compile a procedure which is dynamically
created and then used as a static one.
For more information please refer to \cite{sepcustom}.

\item[] \biptxtref{ensure_loaded(File)}{ensure_loaded/1}{../bips/kernel/database/ensure_loaded-1.html}
\index{ensure_loaded/1}
This predicate compiles the specified file if it has not been compiled
yet or if it has been modified since the last compilation.

\item[] \biptxtref{make}{make/0}{../bips/kernel/env/make-0.html}
\index{make/0}
This predicate recompiles all files that have been modified since their
last compilation.

\item[] \biptxtref{lib(File)}{lib/1}{../bips/kernel/database/lib-1.html}
\index{lib/1}
This predicate is used to ensure that a specified library
file is loaded.
If this library is not yet compiled, the system will look
in all directories in the {\tt library_path} flag for
a file with this name.
When the file is found, it is compiled and the system remembers it.

\item[] \biptxtref{current_compiled_file(File, Time, Module)}{current_compiled_file/3}{../bips/kernel/database/current_compiled_file-3.html}
\index{current_compiled_file/3}
This predicate returns on backtracking all files that have been compiled
in this session, together with the module from where the compilation was
done and the modification time stamp of the file at the time it was compiled.

\item[] \biptxtref{compiled_file(File, Line)}{compiled_file/2}{../bips/lib/sepia/index.html}
\index{compiled_file/2}
This predicate allows to access the compiled file during the compilation.
If it is called during the compilation, it returns the name
of the file being compiled and the current line in it\footnote{
This is in fact ambiguous; the system predicate \bipref{compiled_stream/1}{../bips/kernel/database/compiled_stream-1.html}
which is exported from the module {\bf sepia_kernel}
is more precise.}.
If some I/O operations are performed on the compiler stream,
it influences the compiler, e.g. some procedures can be omitted
and some compiled several times.
An example of its use is the library {\bf ifdef}
which implements a C-like conditional compilation.

\item[] \biptxtref{assert(Clause)}{assert/1}{../bips/kernel/dynamic/assert-1.html}
\index{assert/1}
This predicate compiles the given clause of a dynamic predicate.
\end{description}

%----------------------------------------------------------------------
\section{Module Compilation}
%----------------------------------------------------------------------
One source file can contain several modules and one module
may spread over several files\footnote{This style is not recommended.}.
The module structure is controlled by the \bipref{module/1}{../bips/kernel/modules/module-1.html}
directive which tells the compiler that all subsequent input
up to the end of file or another module directive will
be part of the given module.

When it encounters the \bipref{module/1}{../bips/kernel/modules/module-1.html} directive,
the compiler first erases previous contents of this module,
if there was any, before starting to compile predicates
into it.
This means that if the contents of a module has to be
generated incrementally, the module directive cannot be used
because the previous contents of the module would be destroyed.
In this case the predicate {\bf compile(File, Module)}
should be used.

%----------------------------------------------------------------------
\section{Mode Declarations}
%----------------------------------------------------------------------
\index{mode/1}
\index{mode declaration}
Mode declarations are a way for the user to give some additional
information to the compiler, thus enabling it to do a better job.
The {\eclipse} compiler makes use of the mode information mainly to
improve indexing and to reduce code size.

Mode declarations are optional. They specify the argument instantiation
patterns that a predicate will be called with at runtime, for example:
\begin{quote}
\begin{verbatim}
:- mode p(+), q(-), r(++, ?).
\end{verbatim}
\end{quote}
The possible argument modes and their meaning are:
\begin{description}
\item[+] - The argument is instantiated, i.e. it is not a variable.

\item[++] - The argument is ground.

\item[$-$] - The argument is not instantiated, it must be a free variable
without any constraints, especially it must not occur in any other
argument and it cannot be a suspending variable.

\item[?] - The mode is not known or it is neither of the above ones.
\end{description}

Note that, if the actual instantiation of a predicate call violates
its mode declaration, the behaviour is undefined.
Usually, an unexpected failure occurs in this case.

%----------------------------------------------------------------------
\section{Inlining}
%----------------------------------------------------------------------
\index{inline/2}
\index{inlining}
\index{goal expansion}
To improve efficiency, calls to user-defined predicates can be
preprocessed and transformed at compile time.  The directive
\bipref{inline/2}{../bips/kernel/database/inline-2.html}, e.g.
\begin{quote} \begin{verbatim}
:- inline(mypred/1, mytranspred/2).
\end{verbatim} \end{quote}
arranges for mytranspred/2 to be invoked at compile time for each 
call to the predicate mypred/1 before this call is being compiled.

The transformation predicate receives the original call to mypred/1
as its first argument, and is expected to return a replacement goal
in its second argument. This replacement goal replaces the original
call in the compiled code. Usually, the replacement goal would be
semantically equivalent, but more efficient than the original goal.
When the transformation predicate fails, the original goal is not
replaced.

Typically, a predicate would be defined together with the corresponding
inlining transformation predicate, e.g.
\begin{quote} \begin{verbatim}
:- inline(double/2, trans_double/2).

double(X, Y) :-
        Y is 2*X.

trans_double(double(X, Y), Y=Result) :-
        not nonground(X),    % if X already known at compile time:
        Result is 2*X.       % do calculation at compile time!
\end{verbatim} \end{quote}
All compiled calls to double/2 will now be preprocessed by being passed
to trans_double/2.
E.g.\ if we now compile the following predicate involving double/2
\begin{quote} \begin{verbatim}
sample :-
        double(12,Y), ...,  double(Y,Z).
\end{verbatim} \end{quote}
the first call to double will be replaced by \verb+Y=24+ while the
second one will be unaffected. The code that the compiler sees and
compiles is therefore
\begin{quote} \begin{verbatim}
sample :-
        Y=24, ...,  double(Y,Z).
\end{verbatim} \end{quote}
Note that meta-calls (e.g.\ via
\bipref{call/1}{../bips/kernel/control/call-1.html}) are never
preprocessed, they always go directly to the definition of double/2.

Transformation can be disabled for debugging purposes by adding
\begin{quote} \begin{verbatim}
:- pragma(noexpand).
\end{verbatim} \end{quote}
to the compiled file, or by setting the global flag
\begin{quote} \begin{verbatim}
:- set_flag(goal_expansion, off).
\end{verbatim} \end{quote}



%----------------------------------------------------------------------
\section{Compiler Pragmas}
%----------------------------------------------------------------------
\index{pragma}
Compiler pragmas are compiler directives which instruct the compiler
to emit a particular code type.
Their syntax is similar to directives:
\begin{quote}
\begin{verbatim}
:- pragma(Option).
\end{verbatim}
\end{quote}
It is not possible to have several pragmas grouped together and separated
by commas like goals, every pragma must be specified separately.
{\it Option} can be one of the following:
\begin{itemize}
\item {\bf debug} - generate code which can be inspected with the
debugger.
This overrides the global setting of the {\tt debug_compile} flag.

\item {\bf nodebug} - generate optimized code with no debugger support.
This overrides the global setting of the {\tt debug_compile} flag.

\item {\bf silent_debug} - generate code which cannot be inspected
by the debugger, but which allows to debug predicates called
by it.
This is similar to setting the {\tt leash} flag
of all subgoals in the following clauses
to {\tt notrace}.
This option is useful e.g. for library predicates which call other
Prolog predicates: the user wants to see in the debugger the
call to the library predicate and to the invoked predicate,
but no internal calls in the library predicates.

\item {\bf expand} - do in-line expansion of some subgoals,
like {$=$/2}, \bipref{is/2}{../bips/kernel/arithmetic/is-2.html} and others.
This code can still be inspected with the debugger but the expanded
subgoals look differently than in the normal debugged code,
or their arguments cannot be seen.
This pragma overrides the global setting of the {\tt goal_expansion} flag.

\item {\bf noexpand} - inhibit the in-line goal expansion.
This pragma overrides the global setting of the {\tt goal_expansion} flag.

\item {\bf skip} - set the {\tt skip} flag of all following
predicates to {\tt on}.

\item {\bf noskip} - set the {\tt skip} flag of all following
predicates to {\tt off}.

\item {\bf system} - set the {\tt type} flag of all following
predicates to {\tt built_in}.
Moreover, all following predicates will have unspecified
{\tt source_file} and {\tt source_line} flags.
\end{itemize}
By default, the compiler works as if the pragmas {\bf debug}, {\bf expand}
and {\bf noskip} were specified.

The pragma is active from its specification in the file
until the file end or until it is disabled by another pragma.
Recursive compilations or calls to other compiling predicates
are not affected by the pragma.
Pragmas which have the same effect as global flags override
the global flags if they specify more optimized code.
For instance, the pragma {\bf debug} has no effect if the
global flag {\tt debug_compile} is {\tt off},
but the pragma {\bf nodebug} overrides the global
flag {\tt debug_compile} being {\tt on}.

The pragmas are  useful mainly for libraries and other programs
that should be always compiled in a particular mode
independently of the global flags setting.

%----------------------------------------------------------------------
\section{Writing Efficient Code}
\label{secefficientcode}
%----------------------------------------------------------------------
The {\eclipse} compiler tries its best, however there are some
constructs which can be compiled more efficiently than others.
On the other hand, many Prolog programmers overemphasize
the importance of efficient code and write completely unreadable
programs which can be only hardly maintained and which are only
marginally faster than simple, straightforward and readable
programs.
The advice is therefore {\bf Try the simple and straightforward
solution first!}
The second rule is to keep this original program even if you try
to optimise it. You may find out that the optimisation
was not worth the effort.

To achieve the maximum speed of your programs, you must
produce the optimised code with the flag {\tt debug_compile}
being off, e.g. 
by calling {\bf set_flag(debug_compile, off)},
or using the pragma {\bf nodebug}.
Setting the flag {\tt variable_names} can also cause slight
performance degradations and it is thus better to have
it off, unless variable names have to be kept.
Unlike in the previous releases, the flag {\tt coroutine}
has now no influence on the execution speed.
Some programs spend a lot of time in the garbage collection,
collecting the stacks and/or the dictionary.
If the space is known to be deallocated anyway, e.g. on failure,
the programs can be often speeded up considerably
by switching the garbage collector off or by increasing
the {\tt gc_interval} flag.
As the global stack expands automatically, this does not cause
any stack overflow, but it may of course exhaust the machine memory.

When the program is running and its speed is still
not satisfactory, use the profiling tools.
The profiler can tell you which predicates
are the most expensive ones, and the statistics tool
tells you why.
A program may spend its time in a predicate because the predicate
itself is very time consuming, or because it was frequently executed.
The statistics tool gives you this information.
It can also tell whether the predicate was slow because it
has created a choice point or because there was too much
backtracking due to bad indexing.

One of the very important points is the selection
of the clause that matches the current call.
If there is only one clause that can potentially match,
the compiler is expected to recognise this and generate code
that will directly execute the right clause
instead of trying several subsequent clauses until the
matching one is found.
Unlike most of the current Prolog compilers, the {\eclipse}
compiler tries to base this selection ({\it indexing}) on the most suitable
argument of the predicate\footnote{The standard approach
is to index only on the first argument}.
It is therefore not necessary to reorder the predicate
arguments so that the first one is the crucial argument
for indexing.
However, the decision is still based only on one argument.
If it is necessary to look at two arguments
in order to select the matching clause, e.g. in
\begin{quote}
\begin{verbatim}
p(a, a) :- a.
p(b, a) :- b.
p(a, b) :- c.
p(d, b) :- d.
p(b, c) :- e.
\end{verbatim}
\end{quote}
and if it is crucial that this procedure is executed
as fast as possible, it is necessary to define
an auxiliary procedure which can be indexed on the other argument:
\begin{quote}
\begin{verbatim}
p(X, a) :- pa(X).
p(X, b) :- pb(X).
p(b, c) :- e.

pa(a) :- a. pa(b) :- b.

pb(a) :- c. pb(d) :- d.
\end{verbatim}
\end{quote}

The compiler also tries to use for indexing all type-testing information
that appears at the beginning of the clause body:
\begin{itemize}

\item Type testing predicates \bipref{free/1}{../bips/kernel/typetest/free-1.html}, \bipref{var/1}{../bips/kernel/typetest/var-1.html}, \bipref{meta/1}{../bips/kernel/typetest/meta-1.html},
\bipref{atom/1}{../bips/kernel/typetest/atom-1.html}, \bipref{integer/1}{../bips/kernel/typetest/integer-1.html},
\bipref{rational/1}{../bips/kernel/typetest/rational-1.html},
\bipref{float/1}{../bips/kernel/typetest/float-1.html},
\bipref{breal/1}{../bips/kernel/typetest/breal-1.html},
\bipref{real/1}{../bips/kernel/typetest/real-1.html},
\bipref{number/1}{../bips/kernel/typetest/number-1.html},
\bipref{string/1}{../bips/kernel/typetest/string-1.html}, \bipref{atomic/1}{../bips/kernel/typetest/atomic-1.html}, \bipref{compound/1}{../bips/kernel/typetest/compound-1.html}, \bipref{nonvar/1}{../bips/kernel/typetest/nonvar-1.html} and
\bipref{nonground/1}{../bips/kernel/typetest/nonground-1.html}.

\item Explicit unification and value testing
\txtbipref{=/2}{(=)/2}{../bips/kernel/termcomp/E-2.html}, \txtbipref{==/2}{(==)/2}{../bips/kernel/termcomp/EE-2.html}, 
\biprefnoidx{$\backslash$==/2}{../bips/kernel/termcomp/REE-2.html}\index{$\backslash==$/2} and \biprefnoidx{$\backslash$=/2}{../bips/kernel/termcomp/RE-2.html}\index{$\backslash$=/2}.

\item Combinations of tests with \txtbipref{,/2}{','/2}{../bips/kernel/control/C-2.html}, \bipref{;/2}{../bips/kernel/control/O-2.html},
\bipref{not/1}{../bips/kernel/control/not-1.html}, \txtbipref{$->$/2}{(->)/2}{../bips/kernel/control/-G-2.html}.

\item Arithmetic testing predicates
\txtbipref{$<$/2}{(<)/2}{../bips/kernel/arithmetic/L-2.html},
\txtbipref{=$<$/2}{(=<)/2}{../bips/kernel/arithmetic/EL-2.html},
\txtbipref{$>$/2}{(>)/2}{../bips/kernel/arithmetic/G-2.html},
\txtbipref{$>=$/2}{(>=)/2}{../bips/kernel/arithmetic/GE-2.html} if one argument is an integer constant and the
other one known to be of the integer type.

\item A cut after the type tests.
\end{itemize}

If the compiler can decide about the clause selection at compile time,
the type tests are never executed and thus they incur no overhead.
When the clauses are not disjoint because of the type tests, either a cut
after the test or more tests into the other clauses can be added.
For example, the following procedure will be recognised as deterministic
and all tests are optimised away:

\begin{verbatim}
    % a procedure without cuts
    p(X) :- var(X), ...
    p(X) :- (atom(X); integer(X)), X \= [], ...
    p(X) :- nonvar(X), X = [_|_], ...
    p(X) :- nonvar(X), X = [], ...
\end{verbatim}

Another example:
\begin{verbatim}
    % A procedure with cuts
    p(X{_}) ?- !, ...
    p(X) :- var(X), !, ...
    p(X) :- integer(X), ...
    p(X) :- real(X), ...
    p([H|T]) :- ...
    p([]) :- ...
\end{verbatim}

Integers less than or greater than a constant can also be
recognised by the compiler:
\begin{verbatim}
    p(X) :- integer(X), X < 5, ...
    p(7) :- ...
    p(9) :- ...
    p(X) :- integer(X), X >= 15, ...
\end{verbatim}

If the clause contains tests of several head arguments, only the
first one is taken into account for indexing.

Here are some more hints for efficient coding with {\eclipse}:
\begin{itemize}

\item Arguments which are repeated in the clause head and in the first
regular goal in the body do not require any data moving and thus
they do not cost anything. For example,
\begin{quote}
\begin{verbatim}
p(X, Y, Z, T, U) :- q(X, Y, Z, T, U).
\end{verbatim}
\end{quote}
is as expensive as
\begin{quote}
\begin{verbatim}
p :- q.
\end{verbatim}
\end{quote}
On the other hand, switching arguments requires data moves and so
\begin{quote}
\begin{verbatim}
p(A, B, C) :- q(B, C, A).
\end{verbatim}
\end{quote}
is significantly more expensive.

\item When accessing an argument of a
structure whose functor is known, unification
is better than \bipref{arg/3}{../bips/kernel/termmanip/arg-3.html}.
Note, however, that for better maintainability the {\bf structure
notation} (see section~\ref{chapstruct})
should be used to define the structures.
\index{structures}

\item Tests are generally rather slow unless they can be compiled away
(see {\it indexing}).
\item When processing all arguments of a structure, using \txtbipref{=../2}{(=..)/2}{../bips/kernel/termmanip/EDD-2.html}
and list predicates is always faster, more readable
and easier analyzable by automated tools than using \bipref{functor/3}{../bips/kernel/termmanip/functor-3.html}
and \bipref{arg/3}{../bips/kernel/termmanip/arg-3.html} loops.

\item Similarly, when adding one new element to a structure, using {\bf =../2}
and \bipref{append/3}{../bips/lib/lists/append-3.html} is faster than functor/arg.

\item Waking is less expensive than metacalling and more expensive
than direct calling.
Metacalls, although generally slow, are still a lot faster than
in some other Prolog systems.

\item Sorting using \bipref{sort/2}{../bips/kernel/termcomp/sort-2.html} is very efficient and it does not use
much space.
Using \bipref{setof/3}{../bips/kernel/allsols/setof-3.html}, \bipref{findall/3}{../bips/kernel/allsols/findall-3.html} etc. is also efficient enough
to be used every time a list of all solutions is needed.

\item using {\bf not not Goal} is optimised in the compiler
to use only one choice point.

\item \txtbipref{=/2}{(=)/2}{../bips/kernel/termcomp/E-2.html}, when expanded by the compiler, is faster than \txtbipref{==/2}{(==)/2}{../bips/kernel/termcomp/EE-2.html}
or \txtbipref{=:=/2}{(=:=)/2}{../bips/kernel/arithmetic/ENE-2.html}.

\item \txtbipref{:/2}{: /2}{../bips/kernel/control/N-2.html} is optimised away by the compiler
if both argument are known.

\item Using several clauses is much more efficient than using
a disjunction if the clause heads contain nonvariables
which can be used for indexing.
If no indexing can be made anyway, using a disjunction
is slightly faster.

\item Conditionals with {\bf $-> ;$} are compiled more efficiently
if the condition is a simple built-in test.
However, using several clauses can be faster if the compiler
optimises the test away.

\end{itemize}

%----------------------------------------------------------------------
\section{Compiling and loading object code}
%----------------------------------------------------------------------
\index{object code}
\index{fcompile/1}
\label{fcompile}

Traditionally when an {\eclipse} file is compiled, it is loaded immediately
into the system. Sometime it is useful to generate `object code' which can
then be loaded later, perhaps even in a different session of \eclipse,
maybe on a different platform. This functionality is provided by the
fcompile library.

In order to use this facility, the fcompile library should be loaded first:

\begin{verbatim}
:- lib(fcompile).
\end{verbatim}

\noindent
\biptxtref{fcompile(+File)}{fcompile:fcompile/1}{../bips/lib/fcompile/fcompile-1.html} can then be used to generate an object file from an
{\eclipse} source file. The object file has the same base name as the source
file {\bf File}, but with the suffix {\bf .eco} attached. 

{\bf fcompile} generates an object file by compiling an {\eclipse} source
file normally, and then disassembling the compiled code into an object
form, which is written to the object file. This object form is platform
independent and can be loaded into {\eclipse} running on a different
platform from the one that generated it (see section~\ref{objectport} for 
restrictions). 

The object file is generated in the current working directory.

Options can be specified for fcompile by using \bipref{fcompile/2}{../bips/lib/fcompile/fcompile-2.html}. 


{\bf fcompile} is designed mainly for generating an object file for a whole
module. 
The \biptxtref{include}{include/1}{../bips/kernel/directives/include-1.html} directive allows multiple source files to be compiled
into one object file. When {\bf fcompile} encounters an include directive
in the source file:

\begin{verbatim}
:- include(File).
\end{verbatim}

\noindent
it will generate the object code for the file(s) in {\bf File} in place of
the directive. The effect is as if the actual source code for file(s) was
written at the point of the {\bf include} directive. Note that this can
have a different semantics from recursively compiling files using the {\bf
compile} directive, because any new module in a recursively compiled file
ends with the end of that file. With {\bf include}, any new modules defined
in that file will not end with the file. Thus, a {\bf compile}
directive should not be changed to an {\bf include} directive if the
target file contains definitions for a separate module.

The object code file (with {\bf .eco} suffix) will be loaded in preference
to the Prolog source file by \bipref{use_module/1}{../bips/kernel/modules/use_module-1.html} and \bipref{lib/1,2}{../bips/kernel/database/lib-1.html} if both
files are present. On the other hand, the compile predicates expect a
source file and will normally not load an object code file. 

The compiler generates different object code depending on the settings of
various pragmas. It is the settings of the pragmas at the time the object
code is generated that determines what codes are generated, rather than at
load time. The load time pragma settings have no effect on the object code
that is loaded in, so for example, if the code was generated while the
debug pragma is on, but loaded while the nodebug pragma is on, the loaded
code is still the debuggable, non-optimised code.
 
Note that in addition to generating the object code for predicates found in
the source file, {\bf fcompile} also generates the object code of any 
auxiliary predicates that are called in the source file.
These are the
predicates that are generated by the compiler (such as the \bipref{do/2}{../bips/kernel/control/do-2.html}
iterator). A warning is 
generated if a file contains more than one module. These warnings often
indicates that files have been incorrectly omitted or included in the
include directive. 



fcompile/1,2 can be used to
generate non-source versions of programs for delivery. 

\subsection{Restrictions}

Currently, the compiler generates the auxiliary predicates for the do
iterator using a global counter to name the predicates. Unfortunately this
means that if an object file with auxiliary predicates is loaded into a
module that already has existing code that contains auxiliary predicates, 
naming conflict can occur and the old auxiliaries may be replaced. It is
thus strongly recommended that object files should not be loaded into an
existing module. This will only be a problem if the file does not contain
any module declarations that redefines the module (i.e. \bipref{module/1}{../bips/kernel/modules/module-1.html}),
as these redefinition will erase the old copy of
the module.

The predicate generates the object code by first compiling the program and
then outputting the object code. Directives, which are executed in a normal
compilation process, will not be executed during the output of the object
code (but the directives themselves will be added to the object code so
that they will be executed when the code is loaded). This can lead to
differences between loading the object code and compiling the program if
the directive affects the compiled code during the compilation
(e.g. determining which files to load by a conditional in a
directive). 

If macro transformation is defined (via \bipref{macro/3}{../bips/kernel/syntax/macro-3.html}
declarations) in the module that is fcompiled, then
the ``protecting functor'' {\tt no_macro_expansion}
\index{no_macro_expansion/1} \index{macro!no_macro_expansion} (see
section~\ref{usingmacros}) should be used to prevent the macro definition
itself from being transformed when the definition is generated by
fcompile. For example:

\begin{quote}\begin{verbatim}
:- local macro(no_marco_transformation(foo/1), trans_foo/2, []).
\end{verbatim}\end{quote}

\noindent
the {\tt no_macro_transformation/1} wrapper prevents this instance of {\tt
foo/1} from being transformed when the directive is generated by fcompile.
Note that this is only needed if all terms are transformed, and not for
goals or clause transformation.

\subsubsection{Object file portability}
\label{objectport}

One restriction does apply between platforms of different
word sizes: integers which fit in the word size of one platform
but not the other are represented differently internally in {\eclipse}. 
Specifically, integers which takes between 32 and 64
bits to represent are treated as normal integers on a 64 bit machine,
but as bignums (see section~\ref{intrep}) on 32 bit machines. This
difference is normally invisible, but if
such numbers occur as constants in the program code (i.e. their values appear
textually), they can lead to different low-level compiled abstract code on
the different platforms. Avoid using such constants if you want
the object code to be portable across different word sizes (they can always
be computed at run-time, e.g. writing \verb'2^34' instead of {\tt 17179869184}).



%----------------------------------------------------------------------
\section{Abstract Code Listing}
%----------------------------------------------------------------------
The built-in predicate \bipref{als/1}{../bips/kernel/database/als-1.html} lists the abstract code
of the given predicate and it can thus be used by experts
to check if the predicate was compiled as expected.


%HEVEA\cutend





