View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2026, SWI-Prolog Solutions b.v.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(prolog_auto_table,
   36          [ auto_table/0,
   37            auto_table/1,               % +Options
   38            auto_table_analysis/3,      % +Spec, -Analysis, +Options
   39            auto_table_learn/2,         % :Goals, +Options
   40            auto_table_learn/3          % :Goals, -Result, +Options
   41          ]).   42:- use_module(library(prolog_wrap), [wrap_predicate/4]).   43
   44:- if(exists_source(library(time))).   45:- use_module(library(time), [call_with_time_limit/2]).   46:- endif.   47:- use_module(library(prolog_call_cycles),
   48              [call_graph/2, call_graph_sccs/3, left_recursion/3]).   49:- use_module(library(apply), [maplist/2, maplist/3, foldl/4, include/3,
   50                               exclude/3, partition/4]).   51:- use_module(library(assoc), [list_to_assoc/2, get_assoc/3]).   52:- use_module(library(lists), [member/2, append/3, append/2, sum_list/2,
   53                               last/2, subtract/3, reverse/2, min_member/2,
   54                               selectchk/3]).   55:- use_module(library(prolog_code), [comma_list/2]).   56:- use_module(library(wfs), [call_delays/2]).   57:- use_module(library(pairs), [pairs_keys_values/3, pairs_keys/2,
   58                               pairs_values/2, group_pairs_by_key/2]).   59:- use_module(library(aggregate), [aggregate_all/3]).   60:- autoload(library(prolog_xref),
   61            [xref_source/2, xref_mode/3, xref_current_source/1,
   62             xref_clean/1]).   63:- use_module(library(dcg/high_order), [sequence//2, sequence//3]).   64:- use_module(library(option), [option/2, option/3]).   65:- use_module(library(ugraphs), [vertices_edges_to_ugraph/3]).   66:- use_module(library(error), [must_be/2, permission_error/3]).

Automatic tabling

This library provides the XSB compatible directive auto_table/0, which tables enough predicates of the file in which it appears to make sure that every cycle in the static call graph of the file contains a tabled predicate. It uses library(prolog_call_cycles) to find the recursion in the static call graph of the file. In addition, auto_table_learn/3 learns which predicates to table and in which mode by running goals.

For each strongly connected component of the call graph, the analysis selects a set of predicates to table such that removing these predicates breaks all cycles (a feedback vertex set). Among the possible sets it chooses the one with the lowest estimated number of tabled variants. This estimate is based on how the predicates are called inside the component: calls with fresh variables or ground arguments create few variants, while calls with arguments that are built from data, notably accumulators, create many. Left recursion (recursion where no call to a non-built-in predicate precedes the recursive call) is always reported, as it is guaranteed to loop under Prolog's SLD resolution.

Like XSB, a predicate is also tabled if it is called through tnot/1.

A tabled goal that waits for an incomplete table suspends by capturing its continuation using shift/1. It cannot do so through findall/3 and the other predicates that collect all solutions, aggregate_all/3 or a predicate defined in C (see the barrier key of call_graph_sccs/2). Recursion through such a predicate is therefore not tabled: if its call passes a proper subterm or a computed value of the head it is assumed to terminate, otherwise nothing in the strongly connected component is tabled and auto_table/0 prints a warning.

The analysis is static. Calls through meta-calls that cannot be resolved at compile time are not seen. Tabling guarantees termination only if the number of call variants and answers is finite.

  105:- dynamic
  106    auto_tabled/2.                      % File, PI
 auto_table is det
 auto_table(+Options) is det
Directive that tables predicates of the current file such that each loop in the static call graph of the file contains at least one tabled predicate. The analysis is performed after the file has been loaded completely. Options:
cycles(+Which)
One of all (default) or left. If left, only left recursive cycles are broken.
structural(+Bool)
If true (default false), assume that directly recursive calls on a proper subterm of an argument of the head terminate. This is true if the argument is sufficiently instantiated when the predicate is called. Without this option, this is only assumed if a mode declaration says the argument is input (+ or ++). Mode declarations are given using mode/1 or using PlDoc structured comments, e.g. `%! len(+List, -Len)`.
verbose(+Bool)
If true (default), print a message for each predicate that is tabled.

When the file is reloaded, the predicates tabled by the previous analysis are untabled before the new analysis is performed.

Compatibility
- XSB. XSB only provides auto_table/0. As with XSB, :- mode declarations avoid tabling directly recursive predicates whose recursion decreases an input argument. The XSB dialect maps XSB :- mode declarations to mode/1.
  139auto_table :-
  140    auto_table([]).
  141
  142auto_table(Options) :-
  143    must_be(list, Options),
  144    (   prolog_load_context(source, File),
  145        prolog_load_context(module, Module)
  146    ->  untable_previous(File),
  147        initialization(auto_table_file(File, Module, Options))
  148    ;   permission_error(execute, directive, auto_table/0)
  149    ).
  150
  151untable_previous(File) :-
  152    forall(retract(auto_tabled(File, PI)),
  153           untable(PI)).
 auto_table_file(+File, +Module, +Options) is det
Analyse File and table the predicates selected by the analysis.
  159auto_table_file(File, _Module, Options) :-
  160    catch(auto_table_analysis(file(File), Analysis, Options), E,
  161          ( print_message(warning, E),
  162            fail
  163          )),
  164    !,
  165    option(verbose(Verbose), Options, true),
  166    (   Verbose == true
  167    ->  Level = informational
  168    ;   Level = silent
  169    ),
  170    print_message(Level, auto_table(analysis(Analysis))),
  171    forall(member(PI-_, Analysis.selected),
  172           ( table(PI),
  173             assertz(auto_tabled(File, PI))
  174           )),
  175    forall(( member(SCC, Analysis.sccs),
  176             member(Edge, SCC.cuts)
  177           ),
  178           print_message(warning, auto_table(illegal_cut(Edge)))),
  179    forall(( member(SCC, Analysis.sccs),
  180             SCC.barriers \== []
  181           ),
  182           print_message(warning, auto_table(barrier(SCC)))).
  183auto_table_file(_, _, _).
  184
  185
  186		 /*******************************
  187		 *           ANALYSIS           *
  188		 *******************************/
  189
  190:- meta_predicate
  191    auto_table_analysis(:, -, +).
 auto_table_analysis(:Spec, -Analysis:dict, +Options) is det
Determine the predicates to table for Spec, which is one of file(File), module(Module) or goal(Goal). The latter analyses the predicates reachable from Goal. The options files(FileOrFiles) and module(ModuleOrModules) restrict these to the predicates defined in the given files or modules (see call_graph/2). Analysis is a dict with the keys below. Options are those of auto_table/1 plus the options of call_graph/2.
selected
List of PI-Reason for each predicate that must be tabled, where Reason is one of tnot or cycle.
sccs
List of dicts describing each strongly connected component, holding the keys members, tabled (predicates in the SCC that were already tabled), selected (predicates selected for tabling), cost (estimated cost of the selection), left_recursion (list of left recursion dicts, see left_recursion/3), terminating (directly recursive predicates that are not tabled because their recursion is known to terminate), barriers (edges through a barrier for suspending a tabled goal that are not known to terminate; if this is not empty, nothing is selected) and cuts (if the SCC contains tabled predicates, the edges of the SCC whose call can be pruned by a cut, which raises an error if the call is to an incomplete table; see the pruned key of call_graph_sccs/2).
  222auto_table_analysis(M:Spec, Analysis, Options) :-
  223    graph_options(Spec, M, GraphOptions, Options),
  224    call_graph(Graph, [external(true)|GraphOptions]),
  225    call_graph_sccs(Graph, SCCs, GraphOptions),
  226    tnot_called(Graph, TNot),
  227    option(structural(Structural), Options, false),
  228    mode_db(Structural, SCCs, ModeDB),
  229    maplist(analyse_scc(Options, TNot, ModeDB), SCCs, SCCResults),
  230    findall(PI-tnot, member(PI, TNot), TNotTable),
  231    findall(PI-cycle,
  232            ( member(R, SCCResults),
  233              member(PI, R.selected)
  234            ), CycleTable),
  235    append(TNotTable, CycleTable, Table),
  236    Analysis = auto_table{selected:Table, sccs:SCCResults}.
  237
  238graph_options(file(File), _, [files(File)|Options], Options) :- !.
  239graph_options(module(M), _, [module(M)|Options], Options) :- !.
  240graph_options(goal(G), M, [goal(M:G)|Options], Options) :- !.
  241graph_options(File, _, [files(File)|Options], Options).
 tnot_called(+Graph, -PIs) is det
PIs is the set of predicates in scope that are called through tnot/1 and are not yet tabled.
  248tnot_called(Graph, PIs) :-
  249    list_to_assoc_set(Graph.vertices, VSet),
  250    findall(PI,
  251            ( member(E, Graph.external),
  252              E.to = _:tnot/1,
  253              E.goal = M:tnot(G),
  254              callable(G),
  255              strip_module(M:G, GM, Plain),
  256              resolve_pi(GM:Plain, PI),
  257              get_assoc(PI, VSet, _),
  258              \+ tabled(PI)
  259            ), PIs0),
  260    sort(PIs0, PIs).
  261
  262resolve_pi(M:Goal, IM:Name/Arity) :-
  263    (   predicate_property(M:Goal, imported_from(IM))
  264    ->  true
  265    ;   IM = M
  266    ),
  267    functor(Goal, Name, Arity).
  268
  269tabled(M:Name/Arity) :-
  270    functor(Head, Name, Arity),
  271    predicate_property(M:Head, tabled).
  272
  273list_to_assoc_set(List, Assoc) :-
  274    findall(K-true, member(K, List), Pairs),
  275    list_to_assoc(Pairs, Assoc).
 analyse_scc(+Options, +TNot, +ModeDB, +SCC, -Result) is det
  279analyse_scc(Options, TNot, ModeDB, SCC, Result) :-
  280    option(cycles(Cycles), Options, all),
  281    must_be(oneof([all,left]), Cycles),
  282    partition(tabled, SCC.members, Tabled, Untabled0),
  283    subtract(Untabled0, TNot, Untabled),
  284    findall(L, left_recursion([SCC], L, []), LeftRecs),
  285    partition(barrier_edge, SCC.edges, BarrierEdges, PlainEdges),
  286    partition(progress_edge, BarrierEdges, TermBarriers, Barriers),
  287    include(relevant_edge(Cycles, Untabled), PlainEdges, Edges0),
  288    option(structural(Structural), Options, false),
  289    partition(terminating_edge(Structural, ModeDB), Edges0, TermEdges, Edges1),
  290    (   Barriers == []
  291    ->  Edges = Edges1
  292    ;   Edges = []                      % tabling would raise an error
  293    ),
  294    append(TermEdges, TermBarriers, TermAll),
  295    findall(PI, (member(E, TermAll), PI = E.from), Term0),
  296    sort(Term0, Terminating),
  297    node_costs(Untabled, Edges, Costs),
  298    feedback_vertex_set(Untabled, Edges, Costs, FVS, Cost),
  299    illegal_cuts(SCC, Tabled, TNot, FVS, Cuts),
  300    Result = scc{members:SCC.members, tabled:Tabled, selected:FVS,
  301                 cost:Cost, left_recursion:LeftRecs,
  302                 terminating:Terminating, barriers:Barriers, cuts:Cuts}.
 barrier_edge(+Edge) is semidet
True if the call of Edge is made through a barrier for suspending a tabled goal, e.g., findall/3. A cycle through it cannot be broken by tabling: a tabled goal in it that waits for an incomplete table raises an error.
  311barrier_edge(Edge) :-
  312    Edge.barrier \== none.
 progress_edge(+Edge) is semidet
True if the call of Edge passes a proper subterm or a computed value of the head, so the recursion through it is assumed to terminate.
  320progress_edge(Edge) :-
  321    (   Edge.decreasing == true
  322    ->  true
  323    ;   Args = Edge.args,
  324        is_list(Args),
  325        (   memberchk(subterm, Args)
  326        ->  true
  327        ;   memberchk(computed, Args)
  328        )
  329    ).
 illegal_cuts(+SCC, +Tabled, +TNot, +Selected, -Cuts) is det
If the SCC contains tabled predicates, Cuts is the list of edges in the SCC whose call can be pruned by a cut. Each tabled predicate is reachable from every call in the SCC, so such a cut may prune a call to an incomplete table, which raises a permission error.
  339illegal_cuts(SCC, Tabled, TNot, Selected, Cuts) :-
  340    (   (   Tabled \== []
  341        ;   Selected \== []
  342        ;   member(PI, TNot),
  343            memberchk(PI, SCC.members)
  344        )
  345    ->  include(pruned_edge, SCC.edges, Cuts)
  346    ;   Cuts = []
  347    ).
  348
  349pruned_edge(Edge) :-
  350    Edge.pruned == true.
  351
  352relevant_edge(Cycles, Untabled, Edge) :-
  353    memberchk(Edge.from, Untabled),
  354    memberchk(Edge.to, Untabled),
  355    (   Cycles == left
  356    ->  Edge.left == true
  357    ;   true
  358    ).
 terminating_edge(+Structural, +ModeDB, +Edge) is semidet
True if Edge is a directly recursive call that decreases an argument that is declared as input (+ or ++) by a mode declaration (see mode_db/3). If Structural is true, any directly recursive call that decreases an argument is considered terminating.
  368terminating_edge(Structural, ModeDB, Edge) :-
  369    Edge.from == Edge.to,
  370    Edge.decreasing == true,
  371    (   Structural == true
  372    ->  true
  373    ;   mode_terminating(ModeDB, Edge)
  374    ).
 mode_terminating(+ModeDB, +Edge) is semidet
True if the predicate has mode declarations and, for each of them, Edge passes a proper subterm of the head at an input argument.
  382mode_terminating(ModeDB, Edge) :-
  383    get_assoc(Edge.to, ModeDB, Modes),
  384    Edge.args = Args,
  385    is_list(Args),
  386    forall(member(Mode, Modes),
  387           nth_decreasing_input(Args, Mode)).
  388
  389nth_decreasing_input(Args, Modes) :-
  390    Modes =.. [_|ModeList],
  391    nth_input_subterm(Args, ModeList).
  392
  393nth_input_subterm([subterm|_], [Ind|_]) :-
  394    input_mode(Ind),
  395    !.
  396nth_input_subterm([_|As], [_|Ms]) :-
  397    nth_input_subterm(As, Ms).
  398
  399input_mode(+).
  400input_mode(++).
 mode_db(+Structural, +SCCs, -ModeDB) is det
ModeDB is an assoc mapping the directly recursive predicates of SCCs that recurse on a proper subterm to their mode declarations, a non-empty list of terms Name(Ind, ...), where Ind is a mode indicator such as +, - or ?. Mode declarations are taken from the first of these sources that provides them:
  1. A mode/1 declaration, as reported by the predicate property mode(Head). This also covers XSB :- mode declarations (see library(dialect/xsb)).
  2. PlDoc structured comments. If PlDoc was active while loading, these are available as '$mode'/2 facts. Otherwise the source file is cross-referenced using xref_source/2.
  417mode_db(true, _, ModeDB) :-
  418    !,
  419    list_to_assoc([], ModeDB).
  420mode_db(_, SCCs, ModeDB) :-
  421    findall(PI,
  422            ( member(SCC, SCCs),
  423              member(E, SCC.edges),
  424              E.from == E.to,
  425              E.decreasing == true,
  426              PI = E.to
  427            ), PIs0),
  428    sort(PIs0, PIs),
  429    foldl(declared_modes, PIs, Nested, [], Missing),
  430    append(Nested, Pairs),
  431    xref_modes(Missing, XrefPairs),
  432    append(Pairs, XrefPairs, AllPairs),
  433    list_to_assoc(AllPairs, ModeDB).
  434
  435declared_modes(PI, Pairs, Missing0, Missing) :-
  436    PI = M:Name/Arity,
  437    functor(Head, Name, Arity),
  438    (   predicate_property(M:Head, mode(Mode))
  439    ->  Pairs = [PI-[Mode]],
  440        Missing = Missing0
  441    ;   findall(Mode, pldoc_mode(M:Head, Mode), Modes),
  442        Modes \== []
  443    ->  Pairs = [PI-Modes],
  444        Missing = Missing0
  445    ;   Pairs = [],
  446        Missing = [PI|Missing0]
  447    ).
  448
  449pldoc_mode(M:Head, Mode) :-
  450    current_predicate(M:'$mode'/2),
  451    \+ predicate_property(M:'$mode'(_,_), imported_from(_)),
  452    M:'$mode'(Mode0, _),
  453    strip_module(Mode0, _, Plain),
  454    Plain \= //(_),
  455    functor(Plain, Name, Arity),
  456    functor(Head, Name, Arity),
  457    pldoc_mode_indicators(Plain, Mode).
  458
  459pldoc_mode_indicators(PlDocMode, Mode) :-
  460    PlDocMode =.. [Name|Args0],
  461    maplist(mode_indicator, Args0, Args),
  462    Mode =.. [Name|Args].
  463
  464mode_indicator(Arg, Ind) :-
  465    compound(Arg),
  466    compound_name_arity(Arg, Ind, 1),
  467    !.
  468mode_indicator(_, ?).
 xref_modes(+PIs, -Pairs) is det
Find PlDoc mode declarations for PIs by cross-referencing the files that define them. Files that were not cross-referenced before are cleaned afterwards.
  476xref_modes([], []) :- !.
  477xref_modes(PIs, Pairs) :-
  478    findall(File-PI,
  479            ( member(PI, PIs),
  480              PI = M:Name/Arity,
  481              functor(Head, Name, Arity),
  482              predicate_property(M:Head, file(File))
  483            ), FilePIs0),
  484    keysort(FilePIs0, FilePIs),
  485    group_pairs_by_key(FilePIs, Grouped),
  486    foldl(file_modes, Grouped, Pairs, []).
  487
  488file_modes(File-PIs, Pairs, Tail) :-
  489    (   xref_current_source(File)
  490    ->  file_modes_(File, PIs, Pairs, Tail)
  491    ;   setup_call_cleanup(
  492            catch(xref_source(File, [comments(store), silent(true)]), _, fail),
  493            file_modes_(File, PIs, Pairs, Tail),
  494            xref_clean(File))
  495    ->  true
  496    ;   Pairs = Tail
  497    ).
  498
  499file_modes_(File, PIs, Pairs, Tail) :-
  500    foldl(xref_pi_modes(File), PIs, Pairs, Tail).
  501
  502xref_pi_modes(File, PI, Pairs, Tail) :-
  503    PI = _:Name/Arity,
  504    findall(Mode,
  505            ( xref_mode(File, Mode0, _),
  506              strip_module(Mode0, _, Plain),
  507              functor(Plain, Name, Arity),
  508              pldoc_mode_indicators(Plain, Mode)
  509            ), Modes),
  510    (   Modes == []
  511    ->  Pairs = Tail
  512    ;   Pairs = [PI-Modes|Tail]
  513    ).
  514
  515
  516		 /*******************************
  517		 *             COST             *
  518		 *******************************/
 node_costs(+Nodes, +Edges, -Costs) is det
Costs is an assoc mapping each node to a cost term c(Variants, NotExported, Arity). Variants estimates the number of tabled variants if this node is tabled, based on the argument abstraction of the calls to the node. The other two fields implement XSB's tie breaking: prefer exported predicates and predicates with a low arity.
  529node_costs(Nodes, Edges, Costs) :-
  530    maplist(node_cost(Edges), Nodes, Pairs),
  531    list_to_assoc(Pairs, Costs).
  532
  533node_cost(Edges, PI, PI-c(Variants, NotExported, Arity)) :-
  534    findall(C, ( member(E, Edges),
  535                 E.to == PI,
  536                 call_cost(E.args, C)
  537               ), Cs),
  538    sum_list(Cs, Variants0),
  539    Variants is Variants0+1,
  540    PI = M:Name/Arity,
  541    functor(Head, Name, Arity),
  542    (   predicate_property(M:Head, exported)
  543    ->  NotExported = 0
  544    ;   NotExported = 1
  545    ).
  546
  547call_cost(unknown, 3) :- !.
  548call_cost(Args, Cost) :-
  549    foldl(arg_cost, Args, 0, Cost).
  550
  551arg_cost(Class, C0, C) :-
  552    arg_class_cost(Class, AC),
  553    C is C0+AC.
  554
  555arg_class_cost(fresh,         0).
  556arg_class_cost(ground,        0).
  557arg_class_cost(pass,          1).
  558arg_class_cost(subterm,       2).
  559arg_class_cost(bound_earlier, 3).
  560arg_class_cost(computed,      3).
  561arg_class_cost(distinct,      3).
  562arg_class_cost(constructed,  10).
  563
  564add_cost(c(V1,E1,A1), c(V2,E2,A2), c(V,E,A)) :-
  565    V is V1+V2,
  566    E is E1+E2,
  567    A is A1+A2.
  568
  569
  570		 /*******************************
  571		 *     FEEDBACK VERTEX SET      *
  572		 *******************************/
 feedback_vertex_set(+Nodes, +Edges, +Costs, -FVS, -Cost) is det
Find a set of nodes FVS with minimal total Cost such that the graph Nodes/Edges without FVS has no cycles. We use branch and bound: find a shortest cycle in the remaining graph; one of its nodes must be in the FVS. If the search exceeds its budget we use the best solution found so far, starting with a greedy one.
  582feedback_vertex_set(Nodes, Edges, Costs, FVS, Cost) :-
  583    findall(F-T, (member(E, Edges), F = E.from, T = E.to), Pairs0),
  584    sort(Pairs0, Pairs),
  585    vertices_edges_to_ugraph(Nodes, Pairs, Graph),
  586    greedy_fvs(Graph, Costs, Greedy),
  587    set_cost(Greedy, Costs, GreedyCost),
  588    State = best(Greedy, GreedyCost, 10000),
  589    catch(bb_fvs(Graph, Costs, [], c(0,0,0), State),
  590          fvs_budget_exceeded, true),
  591    arg(1, State, FVS0),
  592    arg(2, State, Cost),
  593    sort(FVS0, FVS).
  594
  595set_cost(Set, Costs, Cost) :-
  596    foldl(node_set_cost(Costs), Set, c(0,0,0), Cost).
  597
  598node_set_cost(Costs, Node, C0, C) :-
  599    get_assoc(Node, Costs, NC),
  600    add_cost(C0, NC, C).
  601
  602bb_fvs(Graph, Costs, Set, Cost, State) :-
  603    arg(3, State, Budget),
  604    (   Budget =< 0
  605    ->  throw(fvs_budget_exceeded)
  606    ;   Budget1 is Budget-1,
  607        nb_setarg(3, State, Budget1)
  608    ),
  609    arg(2, State, Best),
  610    (   Cost @>= Best
  611    ->  true
  612    ;   find_cycle(Graph, Cycle)
  613    ->  forall(member(Node, Cycle),
  614               ( get_assoc(Node, Costs, NC),
  615                 add_cost(Cost, NC, Cost1),
  616                 del_vertex(Graph, Node, Graph1),
  617                 bb_fvs(Graph1, Costs, [Node|Set], Cost1, State)
  618               ))
  619    ;   nb_setarg(1, State, Set),
  620        nb_setarg(2, State, Cost)
  621    ).
 greedy_fvs(+Graph, +Costs, -FVS) is det
Greedy approximation: repeatedly remove the node of a cycle that has the best ratio between the number of edges it is involved in and its cost, then remove redundant nodes.
  629greedy_fvs(Graph, Costs, FVS) :-
  630    greedy_fvs_(Graph, Costs, [], FVS0),
  631    prune_fvs(FVS0, FVS0, Graph, FVS).
  632
  633greedy_fvs_(Graph0, Costs, FVS0, FVS) :-
  634    reduce_graph(Graph0, Graph),
  635    (   Graph == []
  636    ->  FVS = FVS0
  637    ;   member(V-Ns, Graph), memberchk(V, Ns)
  638    ->  del_vertex(Graph, V, Graph1),
  639        greedy_fvs_(Graph1, Costs, [V|FVS0], FVS)
  640    ;   findall(Score-V,
  641                ( member(V-Out, Graph),
  642                  length(Out, NOut),
  643                  aggregate_all(count, (member(_-Ns, Graph), memberchk(V, Ns)),
  644                                NIn),
  645                  get_assoc(V, Costs, c(Vars,_,_)),
  646                  Score is -(NIn*NOut)/(Vars+1)
  647                ), Scored),
  648        keysort(Scored, [_-V|_]),
  649        del_vertex(Graph, V, Graph1),
  650        greedy_fvs_(Graph1, Costs, [V|FVS0], FVS)
  651    ).
  652
  653prune_fvs([], FVS, _, FVS).
  654prune_fvs([V|Vs], FVS0, Graph, FVS) :-
  655    subtract(FVS0, [V], FVS1),
  656    (   foldl(del_vertex_, FVS1, Graph, G1),
  657        \+ find_cycle(G1, _)
  658    ->  prune_fvs(Vs, FVS1, Graph, FVS)
  659    ;   prune_fvs(Vs, FVS0, Graph, FVS)
  660    ).
  661
  662del_vertex_(V, G0, G) :-
  663    del_vertex(G0, V, G).
 reduce_graph(+Graph0, -Graph) is det
Remove vertices without incoming or outgoing edges, as they cannot be part of a cycle.
  670reduce_graph(Graph0, Graph) :-
  671    findall(V, ( member(V-Out, Graph0),
  672                 (   Out == []
  673                 ;   \+ (member(_-Ns, Graph0), memberchk(V, Ns))
  674                 )
  675               ), Dead),
  676    (   Dead == []
  677    ->  Graph = Graph0
  678    ;   foldl(del_vertex_, Dead, Graph0, Graph1),
  679        reduce_graph(Graph1, Graph)
  680    ).
  681
  682del_vertex(Graph0, V, Graph) :-
  683    foldl(del_vertex_edge(V), Graph0, [], RevGraph),
  684    reverse(RevGraph, Graph).
  685
  686del_vertex_edge(V, W-Ns0, G0, G) :-
  687    (   W == V
  688    ->  G = G0
  689    ;   subtract(Ns0, [V], Ns),
  690        G = [W-Ns|G0]
  691    ).
 find_cycle(+Graph, -Cycle) is semidet
Find a shortest cycle in Graph. Cycle is a list of vertices.
  697find_cycle(Graph0, Cycle) :-
  698    reduce_graph(Graph0, Graph),
  699    Graph \== [],
  700    (   member(V-Ns, Graph), memberchk(V, Ns)
  701    ->  Cycle = [V]
  702    ;   findall(Len-C,
  703                ( member(V-_, Graph),
  704                  bfs_cycle(Graph, V, C),
  705                  length(C, Len)
  706                ), Cycles),
  707        keysort(Cycles, [_-Cycle|_])
  708    ).
  709
  710bfs_cycle(Graph, Start, Cycle) :-
  711    bfs([Start-[Start]], Graph, Start, [Start], Path),
  712    reverse(Path, Cycle).
  713
  714bfs([V-Path|Queue], Graph, Start, Visited, Cycle) :-
  715    memberchk(V-Ns, Graph),
  716    (   memberchk(Start, Ns)
  717    ->  Cycle = Path
  718    ;   foldl(bfs_next(Path), Ns, Queue-Visited, Queue1-Visited1),
  719        bfs(Queue1, Graph, Start, Visited1, Cycle)
  720    ).
  721
  722bfs_next(Path, W, Q0-V0, Q-V) :-
  723    (   memberchk(W, V0)
  724    ->  Q = Q0, V = V0
  725    ;   V = [W|V0],
  726        append(Q0, [W-[W|Path]], Q)
  727    ).
  728
  729
  730		 /*******************************
  731		 *           LEARNING           *
  732		 *******************************/
 auto_table_learn(:Goals, +Options) is det
 auto_table_learn(:Goals, -Result:dict, +Options) is det
Run Goals (a goal or list of goals) to learn which predicates must be tabled. The first phase runs Goals without (additional) tabling while observing the recursion: a call that is a variant of one of its ancestors is a loop. Such a call is recorded and fails, so the run continues. This also finds recursion that is not visible to the static analysis, such as recursion through meta-calls or recursion in the data interpreted by a meta-interpreter. The observed loops are combined into a graph for which we compute a feedback vertex set using the observed number of call variants as cost.

auto_table_learn/2 prints the result. Options:

modules(+Modules)
Observe the predicates of the given modules. Default are all modules of class user.
predicates(+PIs)
Observe the given predicates.
time_limit(+Seconds)
Time limit for each run of a goal. Default 60. This option is ignored if library(time) is not available, which is the case in single threaded versions and WASM.
inference_limit(+Count)
Inference limit for each run of a goal. Default infinite.
max_depth(+Depth)
Treat recursion deeper than Depth as a loop. Default 10,000.
ancestor_depth(+Depth)
Only check the nearest Depth ancestors for variants. Default 1,000.
hot(+Count)
Report statistics for the Count predicates with the most call variants. Default 10.
search(+Bool)
If true (default), run the second phase (see below).
objective(+Objective)
What to optimise in the second phase. One of time (CPU time), memory (table space) or balanced (default, the sum of both relative to the initial configuration).
max_runs(+Count)
Maximum number of configurations to try. Default 50.
modes(+Modes)
Tabling modes to try. Default [variant,subsumptive].
apply(+Bool)
If true, leave the program tabled according to the best configuration. Default false, restoring the original tabling.
output(+File)
Write the table directives for the best configuration to File.

The second phase searches for the best configuration, a mapping from predicates to variant, subsumptive or not tabled. It starts with the predicates that were already tabled plus the selected predicates of the first phase. Each configuration is evaluated by running Goals with fresh tables, measuring CPU time and table space. A configuration is rejected if a goal does not complete or produces different answers than the initial configuration. If the initial configuration fails, e.g., because a cut prunes a call to an incomplete table, the search starts from the original tabling. If that fails too, the best configuration is the original tabling. The search moves are: untable all tabled predicates that are not involved in any observed loop (if this fails, try halves), untable a single predicate, switch between variant and subsumptive tabling, and table a predicate that is often called with the same arguments.

Result is a dict with the keys below.

selected
List of predicates that must be tabled to break all observed loops.
loops
List of observed loops. Each loop is a list of predicate indicators.
barrier_loops
List of Loop-Barrier for the observed loops that pass a barrier for suspending a tabled goal, such as findall/3 or a predicate defined in C (see shift/1). Tabling cannot break these loops, so their predicates are not selected.
predicates
List of dicts with statistics for each predicate that is involved in a loop. Keys are pi, calls, variants, args (number of distinct values per argument), tabled (whether the predicate was already tabled) and loops (number of loop detections).
goals
List of Goal-Status, where Status is the result of running the goal: true, false, time_limit_exceeded, inference_limit_exceeded or an error.
hot
Statistics for the predicates with the most call variants.
config
The best configuration found by the second phase, a list of PI-Mode, where Mode is variant or subsumptive.
runs
List of dicts describing each configuration that was tried.
directives
List of table directives for the best configuration.
  835:- meta_predicate
  836    auto_table_learn(:, +),
  837    auto_table_learn(:, -, +).  838
  839auto_table_learn(Goals, Options) :-
  840    auto_table_learn(Goals, Result, Options),
  841    print_message(informational, auto_table(learned(Result))).
  842
  843auto_table_learn(M:Goals0, Result, Options) :-
  844    goal_list(Goals0, M, Goals),
  845    candidate_predicates(Options, Candidates),
  846    original_tabling(Candidates, Original, Fixed),
  847    discover(Goals, Candidates, Discovery, Options),
  848    learned_selection(Discovery, Selected),
  849    Result0 = Discovery.put(selected, Selected),
  850    (   option(search(true), Options, true)
  851    ->  search(Goals, Result0, Original, Fixed, Result, Options)
  852    ;   Result = Result0
  853    ).
  854
  855goal_list(Var, _, _) :-
  856    var(Var),
  857    !,
  858    instantiation_error(Var).
  859goal_list(List, M, Goals) :-
  860    is_list(List),
  861    !,
  862    maplist(qualify_goal(M), List, Goals).
  863goal_list(Goal, M, [QGoal]) :-
  864    qualify_goal(M, Goal, QGoal).
  865
  866qualify_goal(M, Goal, QGoal) :-
  867    strip_module(M:Goal, GM, Plain),
  868    QGoal = GM:Plain.
  869
  870instantiation_error(Var) :-
  871    must_be(callable, Var).
 candidate_predicates(+Options, -PIs) is det
Find the predicates we observe while learning.
  877candidate_predicates(Options, PIs) :-
  878    option(predicates(PIs0), Options),
  879    !,
  880    must_be(list, PIs0),
  881    include(observable, PIs0, PIs).
  882candidate_predicates(Options, PIs) :-
  883    (   option(modules(Modules), Options)
  884    ->  must_be(list(atom), Modules)
  885    ;   findall(M, module_property(M, class(user)), Modules)
  886    ),
  887    findall(M:Name/Arity,
  888            ( member(M, Modules),
  889              current_predicate(M:Name/Arity),
  890              observable(M:Name/Arity)
  891            ), PIs0),
  892    sort(PIs0, PIs).
  893
  894observable(M:Name/Arity) :-
  895    functor(Head, Name, Arity),
  896    \+ predicate_property(M:Head, imported_from(_)),
  897    \+ predicate_property(M:Head, foreign),
  898    predicate_property(M:Head, number_of_rules(N)),
  899    N > 0,
  900    \+ internal_predicate(Name/Arity).
  901
  902internal_predicate('$tabled'/2).
  903internal_predicate('$table_mode'/3).
  904internal_predicate('$table_update'/4).
  905
  906
  907		 /*******************************
  908		 *          DISCOVERY           *
  909		 *******************************/
 discover(+Goals, +Candidates, -Discovery, +Options) is det
Run Goals with all Candidates wrapped to observe the recursion.
  915discover(Goals, Candidates, Discovery, Options) :-
  916    limits(Options, Limits),
  917    option(max_depth(MaxDepth), Options, 10 000),
  918    option(ancestor_depth(AncDepth), Options, 1 000),
  919    length(Candidates, Count),
  920    length(Slots, Count),
  921    maplist(new_slot, Candidates, Slots),
  922    State =.. [slots|Slots],
  923    trie_new(Loops),
  924    trie_new(BarrierLoops),
  925    setup_call_cleanup(
  926        ( nb_setval(auto_table_learn,
  927                    ctx(State, Loops, BarrierLoops, MaxDepth, AncDepth)),
  928          wrap_candidates(Candidates, 1)
  929        ),
  930        ( maplist(run_goal(Limits), Goals, Statuses),
  931          nb_getval(auto_table_learn, ctx(FinalState, _, _, _, _))
  932        ),
  933        ( unwrap_candidates(Candidates),
  934          nb_delete(auto_table_learn)
  935        )),
  936    findall(Loop, trie_gen(Loops, Loop), LoopList0),
  937    findall(Loop-Barrier, trie_gen(BarrierLoops, Loop-Barrier), BarrierList),
  938    pairs_keys(BarrierList, BarrierLoopList),
  939    append(LoopList0, BarrierLoopList, AllLoops),
  940    sort(AllLoops, LoopList),
  941    loop_predicates(LoopList, Candidates, FinalState, Preds),
  942    option(hot(NHot), Options, 10),
  943    hot_predicates(FinalState, NHot, Hot),
  944    pairs_keys_values(GoalStatus, Goals, Statuses),
  945    Discovery = learned{loops:LoopList, barrier_loops:BarrierList,
  946                        predicates:Preds, hot:Hot, goals:GoalStatus}.
  947
  948new_slot(PI, slot(PI, 0, 0, Trie, ArgTries)) :-
  949    PI = _:_/Arity,
  950    trie_new(Trie),
  951    length(ArgTries0, Arity),
  952    maplist(trie_new, ArgTries0),
  953    ArgTries =.. [args|ArgTries0].
  954
  955wrap_candidates([], _).
  956wrap_candidates([PI|PIs], I) :-
  957    PI = M:Name/Arity,
  958    functor(Head, Name, Arity),
  959    wrap_predicate(M:Head, auto_table_learn, Wrapped,
  960                   prolog_auto_table:observe_call(I, Head, Wrapped)),
  961    I2 is I+1,
  962    wrap_candidates(PIs, I2).
  963
  964unwrap_candidates(PIs) :-
  965    forall(member(PI, PIs),
  966           ignore(unwrap_predicate(PI, auto_table_learn))).
  967
  968:- public observe_call/3.  969:- meta_predicate observe_call(+, +, 0).
 observe_call(+Index, +Head, :Wrapped)
Wrapper body. The ancestor stack is kept in the backtrackable global variable auto_table_stack as a term s(Depth, Index, HeadCopy, Parent, Frame) or [], where Frame is the frame that runs the ancestor. The learning state is in the global variable auto_table_learn. We must access it using nb_getval/2 such that we can update it destructively.

A loop that passes a barrier for suspending a tabled goal, such as findall/3, cannot be broken by tabling. It is recorded separately (see shift_barrier/2).

  984observe_call(I, Head, Wrapped) :-
  985    nb_getval(auto_table_learn,
  986              ctx(State, Loops, BarrierLoops, MaxDepth, AncDepth)),
  987    arg(I, State, Slot),
  988    count_call(Slot, Head),
  989    (   nb_current(auto_table_stack, Stack)
  990    ->  true
  991    ;   Stack = []
  992    ),
  993    (   Stack = s(Depth, _, _, _, _)
  994    ->  true
  995    ;   Depth = 0
  996    ),
  997    (   ancestor_variant(Stack, I, Head, AncDepth, Path, AncFrame)
  998    ->  prolog_current_frame(Frame),
  999        (   frame_barrier(Frame, AncFrame, Barrier)
 1000        ->  record_loop(Path, I, State, BarrierLoops, Barrier)
 1001        ;   record_loop(Path, I, State, Loops)
 1002        ),
 1003        (   arg(1, Slot, PI),
 1004            tabled(PI)
 1005        ->  call_observed(Depth, I, Head, Stack, Wrapped)
 1006        ;   fail
 1007        )
 1008    ;   Depth >= MaxDepth
 1009    ->  deep_loop(Stack, I, State, Loops),
 1010        fail
 1011    ;   call_observed(Depth, I, Head, Stack, Wrapped)
 1012    ).
 1013
 1014call_observed(Depth, I, Head, Stack, Wrapped) :-
 1015    Depth1 is Depth+1,
 1016    copy_term(Head, Copy),
 1017    prolog_current_frame(Frame),
 1018    b_setval(auto_table_stack, s(Depth1, I, Copy, Stack, Frame)),
 1019    call(Wrapped),
 1020    b_setval(auto_table_stack, Stack).
 1021
 1022count_call(Slot, Head) :-
 1023    arg(2, Slot, C0),
 1024    C is C0+1,
 1025    nb_setarg(2, Slot, C),
 1026    arg(4, Slot, Trie),
 1027    insert_variant(Trie, Head),
 1028    arg(5, Slot, ArgTries),
 1029    forall(( compound(ArgTries),
 1030             arg(AI, ArgTries, ArgTrie)
 1031           ),
 1032           ( arg(AI, Head, A),
 1033             insert_variant(ArgTrie, A)
 1034           )).
 1035
 1036insert_variant(Trie, Term) :-
 1037    (   catch(trie_insert(Trie, Term), _, true)
 1038    ->  true
 1039    ;   true
 1040    ).
 ancestor_variant(+Stack, +I, +Head, +MaxCheck, -Path, -Frame) is semidet
True if Stack contains a call to predicate I that is a variant of Head. Path is the list of predicate indexes from that ancestor to the current call and Frame is the frame that runs the ancestor.
 1049ancestor_variant(Stack, I, Head, MaxCheck, Path, Frame) :-
 1050    ancestor_variant_(Stack, I, Head, MaxCheck, [], Path, Frame).
 1051
 1052ancestor_variant_(s(_, J, Copy, Parent, Frame0), I, Head, Max, Path0,
 1053                  Path, Frame) :-
 1054    Max > 0,
 1055    (   J == I,
 1056        Copy =@= Head
 1057    ->  Path = [J|Path0],
 1058        Frame = Frame0
 1059    ;   Max1 is Max-1,
 1060        ancestor_variant_(Parent, I, Head, Max1, [J|Path0], Path, Frame)
 1061    ).
 frame_barrier(+Frame, +AncFrame, -Barrier) is semidet
True if a frame between Frame and its ancestor AncFrame runs a barrier for suspending a tabled goal (see shift/1): a predicate with the attribute shift_barrier, such as findall/3, or a predicate defined in C that called Prolog. Barrier is its predicate indicator.
 1071frame_barrier(Frame, AncFrame, Barrier) :-
 1072    prolog_frame_attribute(Frame, parent, Parent),
 1073    Parent \== AncFrame,
 1074    (   prolog_frame_attribute(Parent, predicate_indicator, PI0),
 1075        barrier_frame_pi(PI0, Barrier)
 1076    ->  true
 1077    ;   frame_barrier(Parent, AncFrame, Barrier)
 1078    ).
 1079
 1080barrier_frame_pi(PI0, Barrier) :-
 1081    (   PI0 = M:Name/Arity
 1082    ->  true
 1083    ;   PI0 = Name/Arity,
 1084        M = user
 1085    ),
 1086    functor(Head, Name, Arity),
 1087    (   predicate_property(M:Head, shift_barrier)
 1088    ->  true
 1089    ;   predicate_property(M:Head, foreign)
 1090    ),
 1091    (   bags_loop(M:Name/Arity, Public)
 1092    ->  Barrier = Public
 1093    ;   M == '$bags'
 1094    ->  Barrier = Name/Arity
 1095    ;   M == system
 1096    ->  Barrier = Name/Arity
 1097    ;   Barrier = M:Name/Arity
 1098    ).
 1099
 1100bags_loop('$bags':findall_loop/4, findall/3).
 1101bags_loop('$bags':findnsols_loop/5, findnsols/4).
 1102
 1103record_loop(Path, I, State, Loops) :-
 1104    loop_cycle(Path, I, State, Cycle),
 1105    insert_variant(Loops, Cycle).
 1106
 1107record_loop(Path, I, State, Loops, Barrier) :-
 1108    loop_cycle(Path, I, State, Cycle),
 1109    insert_variant(Loops, Cycle-Barrier).
 1110
 1111loop_cycle(Path, I, State, Cycle) :-
 1112    arg(I, State, Slot),
 1113    arg(3, Slot, L0),
 1114    L is L0+1,
 1115    nb_setarg(3, Slot, L),
 1116    maplist(slot_pi(State), Path, PIs),
 1117    canonical_cycle(PIs, Cycle).
 1118
 1119slot_pi(State, I, PI) :-
 1120    arg(I, State, Slot),
 1121    arg(1, Slot, PI).
 deep_loop(+Stack, +I, +State, +Loops)
The recursion exceeded max_depth. Record the shortest repeating sequence of predicates on top of the stack as a loop.
 1128deep_loop(Stack, I, State, Loops) :-
 1129    stack_indexes(Stack, 100, Top),
 1130    (   append(Cycle0, [I|_], Top),
 1131        \+ memberchk(I, Cycle0)
 1132    ->  record_loop([I|Cycle0], I, State, Loops)
 1133    ;   true
 1134    ).
 1135
 1136stack_indexes(s(_, J, _, Parent, _), Max, [J|T]) :-
 1137    Max > 0,
 1138    !,
 1139    Max1 is Max-1,
 1140    stack_indexes(Parent, Max1, T).
 1141stack_indexes(_, _, []).
 canonical_cycle(+PIs, -Cycle) is det
Rotate a cycle such that it starts with its smallest element and remove the duplicate end.
 1148canonical_cycle([PI], [PI]) :- !.
 1149canonical_cycle([First|Rest], Cycle) :-
 1150    (   last(Rest, First)
 1151    ->  append(Ring, [First], Rest),
 1152        Ring1 = [First|Ring]
 1153    ;   Ring1 = [First|Rest]
 1154    ),
 1155    min_member(Min, Ring1),
 1156    append(Before, [Min|After], Ring1),
 1157    !,
 1158    append([Min|After], Before, Cycle).
 run_goal(+Limits, :Goal, -Status) is det
 1162run_goal(Limits, Goal, Status) :-
 1163    abolish_all_tables,
 1164    b_setval(auto_table_stack, []),
 1165    catch(call_with_limits(Limits,
 1166                           (   forall(Goal, true)
 1167                           ->  Status = true
 1168                           ;   Status = false
 1169                           )),
 1170          E, Status = E),
 1171    nb_delete(auto_table_stack).
 limits(+Options, -Limits) is det
Limits is a term limits(Time, Inferences) holding the limits for a single run of a goal. Each is a number or infinite.
 1178limits(Options, limits(Time, Inferences)) :-
 1179    option(inference_limit(Inferences), Options, infinite),
 1180    (   Inferences == infinite
 1181    ->  true
 1182    ;   must_be(positive_integer, Inferences)
 1183    ),
 1184    (   has_time_limit
 1185    ->  option(time_limit(Time), Options, 60),
 1186        must_be(number, Time)
 1187    ;   Time = infinite
 1188    ).
 call_with_limits(+Limits, :Goal)
Run Goal as once/1 subject to Limits (see limits/2). Raises the exception time_limit_exceeded or inference_limit_exceeded if a limit is exceeded.
 1196call_with_limits(limits(Time, Inferences), Goal) :-
 1197    call_with_time_limit_opt(Time, inference_limited(Inferences, Goal)).
 1198
 1199inference_limited(infinite, Goal) :-
 1200    !,
 1201    once(Goal).
 1202inference_limited(Inferences, Goal) :-
 1203    call_with_inference_limit(Goal, Inferences, Result),
 1204    (   Result == inference_limit_exceeded
 1205    ->  throw(inference_limit_exceeded)
 1206    ;   true
 1207    ).
 1208
 1209:- if(current_predicate(call_with_time_limit/2)). 1210has_time_limit.
 1211
 1212call_with_time_limit_opt(infinite, Goal) :-
 1213    !,
 1214    call(Goal).
 1215call_with_time_limit_opt(Time, Goal) :-
 1216    call_with_time_limit(Time, Goal).
 1217:- else. 1218has_time_limit :-
 1219    fail.
 1220
 1221call_with_time_limit_opt(infinite, Goal) :-
 1222    call(Goal).
 1223:- endif.
 scale_limits(+Limits0, +Run, -Limits) is det
Limit a run of a new configuration to three times the time and inferences used by Run, the best configuration so far.
 1230scale_limits(limits(Time0, Inf0), Run, limits(Time, Inf)) :-
 1231    (   Time0 == infinite
 1232    ->  Time = infinite
 1233    ;   Time is min(Time0, max(1, 3*Run.time))
 1234    ),
 1235    MaxInf is max(1 000 000, 3*Run.inferences),
 1236    (   Inf0 == infinite
 1237    ->  Inf = MaxInf
 1238    ;   Inf is min(Inf0, MaxInf)
 1239    ).
 loop_predicates(+Loops, +Candidates, +State, -Preds) is det
 1243loop_predicates(Loops, _Candidates, State, Preds) :-
 1244    append(Loops, PIs0),
 1245    sort(PIs0, PIs),
 1246    maplist(pred_stats(State), PIs, Preds).
 hot_predicates(+State, +N, -Hot) is det
Hot is a list of statistics dicts for the N predicates with the most call variants.
 1253hot_predicates(State, N, Hot) :-
 1254    State =.. [_|Slots],
 1255    findall(V-Slot,
 1256            ( member(Slot, Slots),
 1257              arg(4, Slot, Trie),
 1258              trie_count(Trie, V),
 1259              V > 0
 1260            ), Pairs),
 1261    keysort(Pairs, Sorted),
 1262    reverse(Sorted, Desc),
 1263    length(Desc, Len),
 1264    Take is min(N, Len),
 1265    length(Top, Take),
 1266    append(Top, _, Desc),
 1267    pairs_values(Top, TopSlots),
 1268    maplist(slot_stats, TopSlots, Hot).
 1269
 1270pred_stats(State, PI, Stats) :-
 1271    State =.. [_|Slots],
 1272    member(Slot, Slots),
 1273    arg(1, Slot, PI),
 1274    !,
 1275    slot_stats(Slot, Stats).
 1276
 1277slot_stats(Slot, Stats) :-
 1278    Slot = slot(PI, Calls, LoopCount, Trie, ArgTries),
 1279    trie_count(Trie, Variants),
 1280    (   compound(ArgTries)
 1281    ->  ArgTries =.. [_|ArgTrieList]
 1282    ;   ArgTrieList = []
 1283    ),
 1284    maplist(trie_count, ArgTrieList, ArgCounts),
 1285    (   tabled(PI) -> Tabled = true ; Tabled = false ),
 1286    Stats = pred{pi:PI, calls:Calls, variants:Variants, args:ArgCounts,
 1287                 tabled:Tabled, loops:LoopCount}.
 1288
 1289trie_count(Trie, Count) :-
 1290    (   trie_property(Trie, value_count(Count))
 1291    ->  true
 1292    ;   Count = 0
 1293    ).
 learned_selection(+Discovery, -Selected) is det
Compute the predicates to table from the observed loops. Loops through predicates that are already tabled are considered broken. The predicates of a loop through a barrier for suspending a tabled goal (see frame_barrier/3) are not tabled, so the loops through them are not broken.
 1303learned_selection(Discovery, Selected) :-
 1304    Preds = Discovery.predicates,
 1305    pairs_keys(Discovery.barrier_loops, BarrierLoops),
 1306    append(BarrierLoops, Blocked0),
 1307    sort(Blocked0, Blocked),
 1308    exclude(tabled_stats, Preds, Untabled0),
 1309    exclude(blocked_stats(Blocked), Untabled0, Untabled),
 1310    maplist(get_dict(pi), Untabled, Nodes),
 1311    findall(edge{from:F, to:T},
 1312            ( member(Loop, Discovery.loops),
 1313              \+ ( member(PI, Loop), member(P, Preds),
 1314                   P.pi == PI, P.tabled == true ),
 1315              \+ ( member(PI, Loop), memberchk(PI, Blocked) ),
 1316              loop_edge(Loop, F, T)
 1317            ), Edges),
 1318    maplist(stats_cost, Untabled, CostPairs),
 1319    list_to_assoc(CostPairs, Costs),
 1320    feedback_vertex_set(Nodes, Edges, Costs, Selected, _Cost).
 1321
 1322blocked_stats(Blocked, Stats) :-
 1323    memberchk(Stats.pi, Blocked).
 1324
 1325tabled_stats(Stats) :-
 1326    Stats.tabled == true.
 1327
 1328loop_edge([PI], PI, PI) :- !.
 1329loop_edge(Loop, F, T) :-
 1330    Loop = [First|_],
 1331    append(Loop, [First], Closed),
 1332    append(_, [F,T|_], Closed).
 1333
 1334stats_cost(Stats, PI-c(Variants, NotExported, Arity)) :-
 1335    PI = Stats.pi,
 1336    Variants = Stats.variants,
 1337    PI = M:Name/Arity,
 1338    functor(Head, Name, Arity),
 1339    (   predicate_property(M:Head, exported)
 1340    ->  NotExported = 0
 1341    ;   NotExported = 1
 1342    ).
 1343
 1344
 1345		 /*******************************
 1346		 *            SEARCH            *
 1347		 *******************************/
 original_tabling(+Candidates, -Original, -Fixed) is det
Original is a list of PI-t(Mode, Extra) for the tabled candidates we may change, where Mode is variant or subsumptive and Extra is a list of additional table options (incremental, shared, ...). Fixed is a list of tabled candidates we do not change: predicates with mode-directed tabling.
 1357original_tabling(Candidates, Original, Fixed) :-
 1358    include(tabled, Candidates, Tabled),
 1359    partition(moded_tabled, Tabled, Fixed, Tunable),
 1360    maplist(table_state, Tunable, Original).
 1361
 1362moded_tabled(M:Name/Arity) :-
 1363    functor(Head, Name, Arity),
 1364    '$tbl_implementation'(M:Head, IM:IHead),
 1365    catch(IM:'$table_mode'(IHead, Variant, _), _, fail),
 1366    IHead \=@= Variant.
 1367
 1368table_state(PI, PI-t(Mode, Extra)) :-
 1369    PI = M:Name/Arity,
 1370    functor(Head, Name, Arity),
 1371    (   predicate_property(M:Head, tabled(subsumptive))
 1372    ->  Mode = subsumptive
 1373    ;   Mode = variant
 1374    ),
 1375    findall(X, ( extra_table_flag(X),
 1376                 predicate_property(M:Head, tabled(X))
 1377               ), Extra).
 1378
 1379extra_table_flag(incremental).
 1380extra_table_flag(shared).
 1381extra_table_flag(monotonic).
 search(+Goals, +Result0, +Original, +Fixed, -Result, +Options)
 1385search(Goals, Result0, Original, Fixed, Result, Options) :-
 1386    option(apply(Apply), Options, false),
 1387    pairs_keys_values(Original, OrigPIs, OrigStates),
 1388    maplist(state_mode, OrigStates, OrigModes),
 1389    pairs_keys_values(Config00, OrigPIs, OrigModes),
 1390    findall(PI-variant,
 1391            ( member(PI, Result0.selected),
 1392              \+ memberchk(PI-_, Config00)
 1393            ), Added),
 1394    append(Config00, Added, Config0),
 1395    sort(Config0, Initial),
 1396    State = search(Original, [], Options),
 1397    (   Apply == true
 1398    ->  run_search(Goals, Initial, Result0, Fixed, State, Search),
 1399        apply_config(Search.config, State)
 1400    ;   setup_call_cleanup(
 1401            true,
 1402            run_search(Goals, Initial, Result0, Fixed, State, Search),
 1403            restore_tabling(Original, State))
 1404    ),
 1405    directives(Search.config, Directives),
 1406    (   option(output(File), Options)
 1407    ->  write_directives(File, Directives)
 1408    ;   true
 1409    ),
 1410    Result = Result0.put(Search).put(directives, Directives).
 1411
 1412state_mode(t(Mode, _), Mode).
 1413
 1414restore_tabling(Original, State) :-
 1415    pairs_keys_values(Original, PIs, States),
 1416    maplist(state_mode, States, Modes),
 1417    pairs_keys_values(Config, PIs, Modes),
 1418    apply_config(Config, State),
 1419    abolish_all_tables.
 run_search(+Goals, +Initial, +Result0, +Fixed, +State, -Search)
Hill climbing from the Initial configuration.
 1425run_search(Goals, Initial, Result0, Fixed, State, Search) :-
 1426    arg(3, State, Options),
 1427    limits(Options, Limits),
 1428    option(max_runs(MaxRuns), Options, 50),
 1429    option(objective(Objective), Options, balanced),
 1430    must_be(oneof([time,memory,balanced]), Objective),
 1431    evaluate(Goals, Initial, initial, Limits, [], State, Run00),
 1432    (   Run00.status == ok
 1433    ->  Start = Initial,
 1434        Run0 = Run00,
 1435        Runs0 = [Run00]
 1436    ;   print_message(warning, auto_table(initial_failed(Run00.status))),
 1437        original_config(State, Original),
 1438        Original \== Initial,
 1439        evaluate(Goals, Original, original, Limits, [], State, Run01),
 1440        Run01.status == ok
 1441    ->  Start = Original,
 1442        Run0 = Run01,
 1443        Runs0 = [Run01, Run00]
 1444    ;   true
 1445    ),
 1446    (   nonvar(Start)
 1447    ->  Ref = Run0.answers,
 1448        Ctx = ctx(Goals, Ref, Run0, Objective, Fixed, Result0, State),
 1449        length(Runs0, Used),
 1450        Budget is MaxRuns-Used,
 1451        moves(Start, Ctx, Moves),
 1452        climb(Moves, Start, Run0, Ctx, Budget, Runs0, Best, Runs)
 1453    ;   original_config(State, Best),    % no configuration works
 1454        Runs = [Run00]
 1455    ),
 1456    reverse(Runs, RunsInOrder),
 1457    maplist(public_run, RunsInOrder, PublicRuns),
 1458    Search = #{config:Best, runs:PublicRuns}.
 original_config(+State, -Config) is det
Config is the configuration with the original tabling of the candidates.
 1465original_config(State, Config) :-
 1466    arg(1, State, Original),
 1467    pairs_keys_values(Original, PIs, States),
 1468    maplist(state_mode, States, Modes),
 1469    pairs_keys_values(Config0, PIs, Modes),
 1470    sort(Config0, Config).
 1471
 1472public_run(Run, Public) :-
 1473    del_dict(answers, Run, _, Public).
 climb(+Moves, +Config, +Run, +Ctx, +Budget, +Runs0, -Best, -Runs)
First improvement hill climbing. After an improving move, the moves are recomputed for the new configuration. Moves that did not improve are not tried again.
 1481climb(_, Config, _, _, Budget, Runs, Config, Runs) :-
 1482    Budget =< 0,
 1483    !.
 1484climb([], Config, _, _, _, Runs, Config, Runs).
 1485climb([Move|Moves], Config, Run, Ctx, Budget, Runs0, Best, Runs) :-
 1486    apply_move(Move, Config, Config1),
 1487    (   Config1 == Config
 1488    ->  climb(Moves, Config, Run, Ctx, Budget, Runs0, Best, Runs)
 1489    ;   Ctx = ctx(Goals, Ref, Run0, Objective, _Fixed, _Result0, State),
 1490        arg(3, State, Options),
 1491        limits(Options, Limits0),
 1492        scale_limits(Limits0, Run, Limits),
 1493        evaluate(Goals, Config1, Move, Limits, Ref, State, Run1),
 1494        Budget1 is Budget-1,
 1495        Runs1 = [Run1|Runs0],
 1496        (   Run1.status == ok,
 1497            accept(Objective, Run1, Run, Run0)
 1498        ->  moves(Config1, Ctx, NewMoves0),
 1499            tried_moves(Runs1, Tried0),
 1500            inverse_moves(Move, Config, Inverse),
 1501            append(Inverse, Tried0, Tried),
 1502            exclude(tried(Tried), NewMoves0, NewMoves),
 1503            climb(NewMoves, Config1, Run1, Ctx, Budget1, Runs1, Best, Runs)
 1504        ;   Run1.status \== ok,
 1505            Move = untable_all(PIs),
 1506            PIs = [_,_|_]
 1507        ->  length(PIs, Len),
 1508            Half is Len // 2,
 1509            length(First, Half),
 1510            append(First, Second, PIs),
 1511            climb([untable_all(First), untable_all(Second)|Moves],
 1512                  Config, Run, Ctx, Budget1, Runs1, Best, Runs)
 1513        ;   climb(Moves, Config, Run, Ctx, Budget1, Runs1, Best, Runs)
 1514        )
 1515    ).
 1516
 1517tried_moves(Runs, Moves) :-
 1518    findall(M, (member(R, Runs), M = R.move), Moves).
 1519
 1520tried(Tried, Move) :-
 1521    memberchk(Move, Tried).
 inverse_moves(+Move, +OldConfig, -Inverse) is det
Moves that undo Move. We do not try these after accepting Move.
 1527inverse_moves(mode(PI, _), Config, [mode(PI, Old)]) :-
 1528    memberchk(PI-Old, Config),
 1529    !.
 1530inverse_moves(untable(PI), Config, [table(PI, Old)]) :-
 1531    memberchk(PI-Old, Config),
 1532    !.
 1533inverse_moves(untable_all(PIs), Config, Inverse) :-
 1534    !,
 1535    findall(table(PI, Old), (member(PI, PIs), memberchk(PI-Old, Config)),
 1536            Inverse).
 1537inverse_moves(table(PI, _), _, [untable(PI)]) :-
 1538    !.
 1539inverse_moves(_, _, []).
 accept(+Objective, +New, +Current, +Initial) is semidet
True if we accept New over Current. This is the case if New is better or New is about as good and tables fewer predicates.
 1546accept(Objective, New, Cur, Init) :-
 1547    (   better(Objective, New, Cur, Init)
 1548    ->  true
 1549    ;   length(New.config, NN),
 1550        length(Cur.config, NC),
 1551        NN < NC,
 1552        \+ worse(Objective, New, Cur, Init)
 1553    ).
 1554
 1555worse(time, New, Cur, _) :-
 1556    New.time > Cur.time*1.05.
 1557worse(memory, New, Cur, _) :-
 1558    New.space > Cur.space*1.05.
 1559worse(balanced, New, Cur, Init) :-
 1560    score(New, Init, SN),
 1561    score(Cur, Init, SC),
 1562    SN > SC*1.05.
 better(+Objective, +New, +Current, +Initial) is semidet
True if New is better than Current. Time measurements need to improve by at least 5% to compensate for noise.
 1569better(time, New, Cur, _) :-
 1570    New.time < Cur.time*0.95.
 1571better(memory, New, Cur, _) :-
 1572    (   New.space < Cur.space
 1573    ->  true
 1574    ;   New.space =:= Cur.space,
 1575        New.time < Cur.time*0.95
 1576    ).
 1577better(balanced, New, Cur, Init) :-
 1578    score(New, Init, SN),
 1579    score(Cur, Init, SC),
 1580    SN < SC*0.95.
 1581
 1582score(Run, Init, Score) :-
 1583    Score is (Run.time+0.001)/(Init.time+0.001) +
 1584             (Run.space+1000)/(Init.space+1000).
 moves(+Config, +Ctx, -Moves) is det
Generate the moves for Config, in the order we try them.
 1590moves(Config, Ctx, Moves) :-
 1591    Ctx = ctx(_Goals, _Ref, _Run0, _Objective, _Fixed, Result0, State),
 1592    arg(3, State, Options),
 1593    option(modes(Modes), Options, [variant,subsumptive]),
 1594    pairs_keys(Config, Tabled),
 1595    loop_preds(Result0, InLoop),
 1596    exclude(in_set(InLoop), Tabled, NotInLoop),
 1597    (   NotInLoop = [_,_|_]
 1598    ->  Bulk = [untable_all(NotInLoop)]
 1599    ;   Bulk = []
 1600    ),
 1601    variant_order(Tabled, Result0, Ordered),
 1602    findall(untable(PI), member(PI, Ordered), Untable),
 1603    reverse(Ordered, ByVariants),
 1604    findall(mode(PI, Mode),
 1605            ( member(PI, ByVariants),
 1606              memberchk(PI-Current, Config),
 1607              member(Mode, Modes),
 1608              Mode \== Current
 1609            ), ModeMoves),
 1610    findall(table(PI, variant),
 1611            ( member(P, Result0.hot),
 1612              PI = P.pi,
 1613              \+ memberchk(PI-_, Config),
 1614              P.tabled == false,
 1615              P.calls >= 2*P.variants
 1616            ), Add),
 1617    append([Bulk, Untable, ModeMoves, Add], Moves).
 1618
 1619in_set(Set, X) :-
 1620    memberchk(X, Set).
 1621
 1622loop_preds(Result, PIs) :-
 1623    append(Result.loops, PIs0),
 1624    sort(PIs0, PIs).
 variant_order(+PIs, +Result, -Ordered) is det
Order PIs by increasing number of observed call variants. Small tables are the cheapest to try removing.
 1631variant_order(PIs, Result, Ordered) :-
 1632    append(Result.predicates, Result.hot, Stats),
 1633    maplist(variant_key(Stats), PIs, Keyed),
 1634    keysort(Keyed, Sorted),
 1635    pairs_values(Sorted, Ordered).
 1636
 1637variant_key(Stats, PI, V-PI) :-
 1638    (   member(S, Stats), S.pi == PI
 1639    ->  V = S.variants
 1640    ;   V = 0
 1641    ).
 1642
 1643apply_move(untable_all(PIs), Config0, Config) :-
 1644    exclude(pi_in(PIs), Config0, Config).
 1645apply_move(untable(PI), Config0, Config) :-
 1646    exclude(pi_in([PI]), Config0, Config).
 1647apply_move(mode(PI, Mode), Config0, Config) :-
 1648    (   selectchk(PI-_, Config0, Config1)
 1649    ->  sort([PI-Mode|Config1], Config)
 1650    ;   Config = Config0
 1651    ).
 1652apply_move(table(PI, Mode), Config0, Config) :-
 1653    sort([PI-Mode|Config0], Config).
 1654
 1655pi_in(PIs, PI-_) :-
 1656    memberchk(PI, PIs).
 evaluate(+Goals, +Config, +Move, +Limits, +RefAnswers, +State, -Run) is det
Apply Config and run Goals. Run is a dict with the keys move, config, status (ok, different_answers or the error), time (CPU seconds), inferences, space (memory used by the tables in bytes), tables and answers.
 1666evaluate(Goals, Config, Move, Limits, Ref, State, Run) :-
 1667    catch(apply_config(Config, State), E, true),
 1668    (   var(E)
 1669    ->  abolish_all_tables,
 1670        garbage_collect,
 1671        statistics(cputime, T0),
 1672        statistics(inferences, I0),
 1673        maplist(goal_answers(Limits), Goals, Answers),
 1674        statistics(cputime, T1),
 1675        statistics(inferences, I1),
 1676        table_space(Tables, Space),
 1677        abolish_all_tables,
 1678        Time is T1-T0,
 1679        Inferences is I1-I0,
 1680        (   member(error(Status0), Answers)
 1681        ->  Status = Status0
 1682        ;   Ref \== [],
 1683            Ref \== Answers
 1684        ->  Status = different_answers
 1685        ;   Status = ok
 1686        )
 1687    ;   Status = E,
 1688        Time = 0, Inferences = 0, Space = 0, Tables = 0, Answers = []
 1689    ),
 1690    Run = run{move:Move, config:Config, status:Status, time:Time,
 1691              inferences:Inferences, space:Space, tables:Tables,
 1692              answers:Answers},
 1693    print_message(silent, auto_table(run(Run))).
 table_space(-Count, -Bytes) is det
Count the tables and the memory they use. We sum the sizes of the tables rather than using the table_space_used statistics because the space of abolished tables is not always reclaimed immediately. The size of a table includes its compiled answer representation.
 1702table_space(Count, Bytes) :-
 1703    aggregate_all(count-sum(Size),
 1704                  ( current_table(_:_, Trie),
 1705                    trie_space(Trie, Size)
 1706                  ),
 1707                  Count-Bytes).
 1708
 1709trie_space(Trie, Size) :-
 1710    (   trie_property(Trie, size(Size0)) -> true ; Size0 = 0 ),
 1711    (   trie_property(Trie, compiled_size(Size1)) -> true ; Size1 = 0 ),
 1712    Size is Size0+Size1.
 1713
 1714goal_answers(Limits, Goal, Answers) :-
 1715    catch(call_with_limits(
 1716              Limits,
 1717              findall(Goal-Delays, call_delays(Goal, Delays), List)),
 1718          E, true),
 1719    (   var(E)
 1720    ->  answer_set(List, Answers)
 1721    ;   Answers = error(E)
 1722    ).
 1723
 1724answer_set(List, Set) :-
 1725    maplist(answer_hash, List, Hashes),
 1726    sort(Hashes, Set).
 1727
 1728answer_hash(Answer, Hash) :-
 1729    (   catch(variant_sha1(Answer, Hash), _, fail)
 1730    ->  true
 1731    ;   copy_term(Answer, Hash),
 1732        numbervars(Hash, 0, _, [singletons(true)])
 1733    ).
 apply_config(+Config, +State) is det
Make the tabling of the predicates we manage agree with Config. The managed predicates are those in Config, those that were tabled originally and those of previously applied configurations.
 1741apply_config(Config, State) :-
 1742    State = search(Original, Managed0, _Options),
 1743    pairs_keys(Config, CPIs),
 1744    pairs_keys(Original, OPIs),
 1745    append([CPIs, OPIs, Managed0], All0),
 1746    sort(All0, All),
 1747    nb_setarg(2, State, All),
 1748    maplist(apply_pi_config(Config, Original), All).
 1749
 1750apply_pi_config(Config, Original, PI) :-
 1751    PI = M:Name/Arity,
 1752    functor(Head, Name, Arity),
 1753    (   memberchk(PI-Mode, Config)
 1754    ->  (   memberchk(PI-t(_, Extra), Original)
 1755        ->  true
 1756        ;   Extra = []
 1757        ),
 1758        (   predicate_property(M:Head, tabled(Mode)),
 1759            forall(member(X, Extra), predicate_property(M:Head, tabled(X)))
 1760        ->  true
 1761        ;   (   predicate_property(M:Head, tabled)
 1762            ->  untable(PI)
 1763            ;   true
 1764            ),
 1765            comma_list(Opts, [Mode|Extra]),
 1766            table(PI as Opts)
 1767        )
 1768    ;   predicate_property(M:Head, tabled)
 1769    ->  untable(PI)
 1770    ;   true
 1771    ).
 directives(+Config, -Directives) is det
 1775directives(Config, Directives) :-
 1776    maplist(directive, Config, Directives).
 1777
 1778directive(PI-variant, (:- table(PI))) :- !.
 1779directive(PI-Mode, (:- table(PI as Mode))).
 1780
 1781write_directives(File, Directives) :-
 1782    setup_call_cleanup(
 1783        open(File, write, Out),
 1784        forall(member(D, Directives),
 1785               portray_clause(Out, D)),
 1786        close(Out)).
 1787
 1788
 1789		 /*******************************
 1790		 *           MESSAGES           *
 1791		 *******************************/
 1792
 1793:- multifile
 1794    prolog:message//1. 1795
 1796prolog:message(auto_table(Msg)) -->
 1797    message(Msg).
 1798
 1799message(learned(R)) -->
 1800    { pairs_keys(R.get(barrier_loops, []), BarrierLoops),
 1801      subtract(R.loops, BarrierLoops, Loops)
 1802    },
 1803    learned_goals(R.goals),
 1804    learned_loops(Loops),
 1805    learned_barrier_loops(R.get(barrier_loops, [])),
 1806    learned_preds(R.predicates),
 1807    learned_hot(R.hot),
 1808    learned_selected(R.selected),
 1809    learned_runs(R.get(runs, [])),
 1810    learned_directives(R.get(directives, -)).
 1811message(initial_failed(Status)) -->
 1812    [ 'auto_table_learn/3: initial configuration failed: ~p'-[Status] ].
 1813message(run(Run)) -->
 1814    run(Run).
 1815
 1816message(analysis(Analysis)) -->
 1817    { Analysis.selected == [] },
 1818    !,
 1819    [ 'auto_table: no predicates need to be tabled' ].
 1820message(analysis(Analysis)) -->
 1821    { Table = Analysis.selected },
 1822    sequence(table_reason(Analysis), [nl], Table).
 1823
 1824message(illegal_cut(Edge)) -->
 1825    [ 'auto_table: the call to ~q from ~q'-[Edge.to, Edge.from] ],
 1826    location(Edge.location),
 1827    [ ' can be pruned by a cut.', nl,
 1828      'This raises an error if the call is to an incomplete table.' ].
 1829
 1830message(barrier(SCC)) -->
 1831    sequence(barrier_edge_message, [nl], SCC.barriers),
 1832    [ nl, 'A tabled goal cannot wait for an incomplete table through \c
 1833           these calls.  Not tabling ' ],
 1834    sequence(pi, [', '], SCC.members).
 1835
 1836barrier_edge_message(Edge) -->
 1837    [ 'auto_table: ~q calls ~q through ~q'-[Edge.from, Edge.to, Edge.barrier] ],
 1838    location(Edge.location).
 1839
 1840table_reason(_, PI-tnot) -->
 1841    [ 'auto_table: tabling ~q (called through tnot/1)'-[PI] ].
 1842table_reason(Analysis, PI-cycle) -->
 1843    { member(SCC, Analysis.sccs),
 1844      memberchk(PI, SCC.selected),
 1845      !
 1846    },
 1847    [ 'auto_table: tabling ~q'-[PI] ],
 1848    left_recursion_reason(PI, SCC.left_recursion).
 1849
 1850left_recursion_reason(PI, LeftRecs) -->
 1851    { member(L, LeftRecs),
 1852      memberchk(PI, L.members),
 1853      !
 1854    },
 1855    [ ' (breaks left recursion ' ],
 1856    cycle(L.cycle),
 1857    [ ')' ].
 1858left_recursion_reason(_, _) -->
 1859    [ ' (breaks recursion)' ].
 1860
 1861cycle(Edges) -->
 1862    { Edges = [E0|_],
 1863      last(Edges, Last)
 1864    },
 1865    [ '~q'-[E0.from] ],
 1866    sequence(cycle_edge, Edges),
 1867    location(Last.location).
 1868
 1869cycle_edge(E) -->
 1870    [ ' -> ~q'-[E.to] ].
 1871
 1872learned_goals(Goals) -->
 1873    sequence(learned_goal, Goals).
 1874
 1875learned_goal(Goal-Status) -->
 1876    [ 'Goal ~p: ~p'-[Goal, Status], nl ].
 1877
 1878learned_loops([]) -->
 1879    !,
 1880    [ 'No loops observed', nl ].
 1881learned_loops(Loops) -->
 1882    { length(Loops, Count) },
 1883    [ 'Observed ~D loops:'-[Count], nl ],
 1884    sequence(learned_loop, Loops).
 1885
 1886learned_barrier_loops([]) -->
 1887    !.
 1888learned_barrier_loops(Loops) -->
 1889    [ 'Loops through a barrier for suspending a tabled goal \c
 1890       (not tabled):', nl ],
 1891    sequence(learned_barrier_loop, Loops).
 1892
 1893learned_barrier_loop(Loop-Barrier) -->
 1894    { Loop = [First|_] },
 1895    [ '  ' ],
 1896    sequence(pi, [' -> '], Loop),
 1897    [ ' -> ~q (through ~q)'-[First, Barrier], nl ].
 1898
 1899learned_loop(Loop) -->
 1900    { Loop = [First|_] },
 1901    [ '  ' ],
 1902    sequence(pi, [' -> '], Loop),
 1903    [ ' -> ~q'-[First], nl ].
 1904
 1905pi(PI) -->
 1906    [ '~q'-[PI] ].
 1907
 1908learned_preds([]) -->
 1909    !.
 1910learned_preds(Preds) -->
 1911    [ 'Predicates in loops:', nl ],
 1912    sequence(learned_pred, Preds).
 1913
 1914learned_pred(P) -->
 1915    { (P.tabled == true -> Tabled = ' (tabled)' ; Tabled = '') },
 1916    [ '  ~q~w: ~D calls, ~D variants, args ~w'-
 1917      [P.pi, Tabled, P.calls, P.variants, P.args], nl ].
 1918
 1919learned_hot([]) -->
 1920    !.
 1921learned_hot(Preds) -->
 1922    [ 'Predicates with the most call variants:', nl ],
 1923    sequence(learned_pred, Preds).
 1924
 1925learned_runs([]) -->
 1926    !.
 1927learned_runs(Runs) -->
 1928    [ nl, 'Configurations tried (CPU time, table space, tables):', nl ],
 1929    sequence(run_line, Runs).
 1930
 1931run_line(Run) -->
 1932    [ '  ' ], run(Run), [ nl ].
 1933
 1934run(Run) -->
 1935    { Run.status == ok },
 1936    !,
 1937    [ '~p: ~3f sec, ~D bytes, ~D tables'-
 1938      [Run.move, Run.time, Run.space, Run.tables] ].
 1939run(Run) -->
 1940    { (   Run.status = error(Formal, _)
 1941      ->  Status = Formal
 1942      ;   Status = Run.status
 1943      )
 1944    },
 1945    [ '~p: ~p'-[Run.move, Status] ].
 1946
 1947learned_directives(-) -->
 1948    !.
 1949learned_directives([]) -->
 1950    !,
 1951    [ 'Best configuration: no tabling' ].
 1952learned_directives(Directives) -->
 1953    [ 'Best configuration:', nl ],
 1954    sequence(directive_line, [nl], Directives).
 1955
 1956directive_line(Directive) -->
 1957    { format(string(S), '~q.', [Directive]) },
 1958    [ '  ~s'-[S] ].
 1959
 1960learned_selected([]) -->
 1961    !,
 1962    [ 'No (additional) predicates need to be tabled' ].
 1963learned_selected(PIs) -->
 1964    [ 'Table: ' ],
 1965    sequence(pi, [', '], PIs).
 1966
 1967location(Loc) -->
 1968    { get_dict(file, Loc, File),
 1969      get_dict(line_count, Loc, Line)
 1970    },
 1971    !,
 1972    [ ' at ', url(File:Line) ].
 1973location(_) -->
 1974    []