Use module mechanism to register copy minimization algorithms.
[libfirm] / ir / be / becopyilp2.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       ILP based copy minimization.
23  * @author      Daniel Grund
24  * @date        28.02.2006
25  * @version     $Id$
26  *
27  * ILP formalization using G=(V, E, Q):
28  *  - 2 class of variables: coloring vars x_ic   and   equal color vars y_ij
29  *  - Path constraints
30  *  - Clique-star constraints
31  *
32  *
33  *      \min \sum_{ (i,j) \in Q }  w_ij y_ij
34  *
35  *              \sum_c x_nc                     =  1                    n \in N, c \in C
36  *
37  *              x_nc                            =  0                    n \in N, c \not\in C(n)
38  *
39  *              \sum x_nc                       <= 1                    x_nc \in Clique \in AllCliques,  c \in C
40  *
41  *              \sum_{e \in p} y_e      >= 1                    p \in P         path constraints
42  *
43  *              \sum_{e \in cs} y_e     >= |cs| - 1             cs \in CP       clique-star constraints
44  *
45  *              x_nc, y_ij \in N,   w_ij \in R^+
46  */
47 #include "config.h"
48
49 #ifdef WITH_ILP
50
51 #include "bitset.h"
52 #include "raw_bitset.h"
53 #include "pdeq.h"
54
55 #include "irtools.h"
56 #include "irgwalk.h"
57 #include "becopyilp_t.h"
58 #include "beifg_t.h"
59 #include "besched.h"
60 #include "bemodule.h"
61
62 #define DEBUG_LVL 1
63
64 typedef struct _local_env_t {
65         double time_limit;
66         int first_x_var, last_x_var;
67         int n_colors;
68         bitset_t *normal_colors;
69         pmap *nr_2_irn;
70         DEBUG_ONLY(firm_dbg_module_t *dbg;)
71 } local_env_t;
72
73 static void build_coloring_cstr(ilp_env_t *ienv) {
74         be_ifg_t *ifg     = ienv->co->cenv->ifg;
75         void *iter        = be_ifg_nodes_iter_alloca(ifg);
76         bitset_t *colors;
77         ir_node *irn;
78         char buf[16];
79
80         colors = bitset_alloca(arch_register_class_n_regs(ienv->co->cls));
81
82         be_ifg_foreach_node(ifg, iter, irn)
83                 if (!sr_is_removed(ienv->sr, irn)) {
84                         bitset_pos_t col;
85                         int cst_idx;
86                         const arch_register_req_t *req;
87                         int curr_node_color = get_irn_col(irn);
88                         int node_nr = (int)get_irn_idx(irn);
89                         local_env_t *lenv = ienv->env;
90
91                         pmap_insert(lenv->nr_2_irn, INT_TO_PTR(node_nr), irn);
92
93                         req = arch_get_register_req_out(irn);
94
95                         bitset_clear_all(colors);
96
97                         /* get assignable colors */
98                         if (arch_register_req_is(req, limited)) {
99                                 rbitset_copy_to_bitset(req->limited, colors);
100                         } else {
101                                 bitset_copy(colors, lenv->normal_colors);
102                         }
103
104                         /* add the coloring constraint */
105                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
106
107                         bitset_foreach(colors, col) {
108                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
109                                 lpp_set_start_value(ienv->lp, var_idx, (col == (unsigned) curr_node_color) ? 1.0 : 0.0);
110                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
111
112                                 lenv->last_x_var = var_idx;
113                                 if (lenv->first_x_var == -1)
114                                         lenv->first_x_var = var_idx;
115                         }
116
117                         /* add register constraint constraints */
118                         bitset_foreach_clear(colors, col) {
119                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
120                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
121                                 lpp_set_start_value(ienv->lp, var_idx, 0.0);
122                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
123
124                                 lenv->last_x_var = var_idx;
125                         }
126                 }
127 }
128
129 static void build_interference_cstr(ilp_env_t *ienv)
130 {
131         lpp_t       *lpp      = ienv->lp;
132         local_env_t *lenv     = ienv->env;
133         be_ifg_t    *ifg      = ienv->co->cenv->ifg;
134         int          n_colors = lenv->n_colors;
135         void        *iter     = be_ifg_cliques_iter_alloca(ifg);
136         ir_node    **clique   = ALLOCAN(ir_node*, n_colors);
137         int          size;
138         int          col;
139         int          i;
140
141         char buf[16];
142
143         /* for each maximal clique */
144         be_ifg_foreach_clique(ifg, iter, clique, &size) {
145                 int realsize = 0;
146
147                 for (i=0; i<size; ++i)
148                         if (!sr_is_removed(ienv->sr, clique[i]))
149                                 ++realsize;
150
151                 if (realsize < 2)
152                         continue;
153
154                 /* for all colors */
155                 for (col=0; col<n_colors; ++col) {
156                         int cst_idx = lpp_add_cst(lpp, NULL, lpp_less, 1.0);
157
158                         /* for each member of this clique */
159                         for (i=0; i<size; ++i) {
160                                 ir_node *irn = clique[i];
161
162                                 if (!sr_is_removed(ienv->sr, irn)) {
163                                         int var_idx = lpp_get_var_idx(lpp, name_cdd(buf, 'x', (int)get_irn_idx(irn), col));
164                                         lpp_set_factor_fast(lpp, cst_idx, var_idx, 1);
165                                 }
166                         }
167                 }
168         }
169 }
170
171
172 /**
173  * TODO: Remove the dependency of the opt-units data structure
174  *       by walking over all affinity edges. Graph structure
175  *       does not provide this walker, yet.
176  */
177 static void build_affinity_cstr(ilp_env_t *ienv) {
178         local_env_t *lenv = ienv->env;
179         int n_colors      = lenv->n_colors;
180         unit_t *curr;
181
182         /* for all optimization units */
183         list_for_each_entry(unit_t, curr, &ienv->co->units, units) {
184                 ir_node *root, *arg;
185                 int root_nr, arg_nr, i, col, y_idx, root_idx, arg_idx;
186                 char buf[16];
187                 int root_col, arg_col;
188
189                 root = curr->nodes[0];
190                 root_nr = (int) get_irn_idx(root);
191                 root_col = get_irn_col(root);
192
193                 for (i = 1; i < curr->node_count; ++i) {
194                         arg = curr->nodes[i];
195                         arg_nr = (int) get_irn_idx(arg);
196                         arg_col = get_irn_col(arg);
197
198                         /* add a new affinity variable */
199                         y_idx = lpp_add_var(ienv->lp, name_cdd_sorted(buf, 'y', root_nr, arg_nr), lpp_binary, curr->costs[i]);
200                         lpp_set_start_value(ienv->lp, y_idx, (root_col==arg_col) ? 0.0 : 1.0);
201
202                         /* add constraints relating the affinity var to the color vars */
203                         for (col=0; col<n_colors; ++col) {
204                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_less, 0.0);
205                                 root_idx = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', root_nr, col));
206                                 arg_idx  = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', arg_nr,  col));
207
208                                 lpp_set_factor_fast(ienv->lp, cst_idx, root_idx,  1.0);
209                                 lpp_set_factor_fast(ienv->lp, cst_idx, arg_idx,  -1.0);
210                                 lpp_set_factor_fast(ienv->lp, cst_idx, y_idx, -1.0);
211                         }
212                 }
213         }
214 }
215
216 /**
217  * Helping stuff for build_clique_star_cstr
218  */
219 typedef struct _edge_t {
220         ir_node *n1, *n2;
221 } edge_t;
222
223 static int compare_edge_t(const void *k1, const void *k2, size_t size) {
224         const edge_t *e1 = k1;
225         const edge_t *e2 = k2;
226         (void) size;
227
228         return ! (e1->n1 == e2->n1   &&   e1->n2 == e2->n2);
229 }
230
231 #define HASH_EDGE(e) (hash_irn((e)->n1) ^ hash_irn((e)->n2))
232
233 static inline edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
234         edge_t new_edge;
235
236         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
237                 new_edge.n1 = n1;
238                 new_edge.n2 = n2;
239         } else {
240                 new_edge.n1 = n2;
241                 new_edge.n2 = n1;
242         }
243         (*counter)++;
244         return set_insert(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
245 }
246
247 static inline edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2) {
248         edge_t new_edge;
249
250         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
251                 new_edge.n1 = n1;
252                 new_edge.n2 = n2;
253         } else {
254                 new_edge.n1 = n2;
255                 new_edge.n2 = n1;
256         }
257         return set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
258 }
259
260 static inline void remove_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
261         edge_t new_edge, *e;
262
263         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
264                 new_edge.n1 = n1;
265                 new_edge.n2 = n2;
266         } else {
267                 new_edge.n1 = n2;
268                 new_edge.n2 = n1;
269         }
270         e = set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
271         if (e) {
272                 e->n1 = NULL;
273                 e->n2 = NULL;
274                 (*counter)--;
275         }
276 }
277
278 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
279
280 /**
281  * Search for an interference clique and an external node
282  * with affinity edges to all nodes of the clique.
283  * At most 1 node of the clique can be colored equally with the external node.
284  */
285 static void build_clique_star_cstr(ilp_env_t *ienv) {
286         affinity_node_t *aff;
287
288         /* for each node with affinity edges */
289         co_gs_foreach_aff_node(ienv->co, aff) {
290                 struct obstack ob;
291                 neighb_t *nbr;
292                 const ir_node *center = aff->irn;
293                 ir_node **nodes;
294                 set *edges;
295                 int i, o, n_nodes, n_edges;
296
297                 if (arch_irn_is_ignore(aff->irn))
298                         continue;
299
300                 obstack_init(&ob);
301                 edges = new_set(compare_edge_t, 8);
302
303                 /* get all affinity neighbours */
304                 n_nodes = 0;
305                 co_gs_foreach_neighb(aff, nbr) {
306                         if (!arch_irn_is_ignore(nbr->irn)) {
307                                 obstack_ptr_grow(&ob, nbr->irn);
308                                 ++n_nodes;
309                         }
310                 }
311                 nodes = obstack_finish(&ob);
312
313                 /* get all interference edges between these */
314                 n_edges = 0;
315                 for (i=0; i<n_nodes; ++i)
316                         for (o=0; o<i; ++o)
317                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
318                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
319
320                 /* cover all these interference edges with maximal cliques */
321                 while (n_edges) {
322                         edge_t *e;
323                         pset *clique = pset_new_ptr(8);
324                         int growed;
325
326                         /* get 2 starting nodes to form a clique */
327                         for (e=set_first(edges); !e->n1; e=set_next(edges))
328                                 /*nothing*/ ;
329
330                         /* we could be stepped out of the loop before the set iterated to the end */
331                         set_break(edges);
332
333                         pset_insert_ptr(clique, e->n1);
334                         pset_insert_ptr(clique, e->n2);
335                         remove_edge(edges, e->n1, e->n2, &n_edges);
336
337                         /* while the clique is growing */
338                         do {
339                                 growed = 0;
340
341                                 /* search for a candidate to extend the clique */
342                                 for (i=0; i<n_nodes; ++i) {
343                                         ir_node *member, *cand = nodes[i];
344                                         int is_cand;
345
346                                         /* if its already in the clique try the next */
347                                         if (pset_find_ptr(clique, cand))
348                                                 continue;
349
350                                         /* are there all necessary interferences? */
351                                         is_cand = 1;
352                                         pset_foreach(clique, member) {
353                                                 if (!find_edge(edges, cand, member)) {
354                                                         is_cand = 0;
355                                                         pset_break(clique);
356                                                         break;
357                                                 }
358                                         }
359
360                                         /* now we know if we have a clique extender */
361                                         if (is_cand) {
362                                                 /* first remove all covered edges */
363                                                 pset_foreach(clique, member)
364                                                         remove_edge(edges, cand, member, &n_edges);
365
366                                                 /* insert into clique */
367                                                 pset_insert_ptr(clique, cand);
368                                                 growed = 1;
369                                                 break;
370                                         }
371                                 }
372                         } while (growed);
373
374                         /* now the clique is maximal. Finally add the constraint */
375                         {
376                                 ir_node *member;
377                                 int var_idx, cst_idx, center_nr, member_nr;
378                                 char buf[16];
379
380                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, pset_count(clique)-1);
381                                 center_nr = get_irn_idx(center);
382
383                                 pset_foreach(clique, member) {
384                                         member_nr = get_irn_idx(member);
385                                         var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', center_nr, member_nr));
386                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
387                                 }
388                         }
389
390                         del_pset(clique);
391                 }
392
393                 del_set(edges);
394                 obstack_free(&ob, NULL);
395         }
396 }
397
398
399 static void extend_path(ilp_env_t *ienv, pdeq *path, const ir_node *irn) {
400         be_ifg_t *ifg = ienv->co->cenv->ifg;
401         int i, len;
402         ir_node **curr_path;
403         affinity_node_t *aff;
404         neighb_t *nbr;
405
406         /* do not walk backwards or in circles */
407         if (pdeq_contains(path, irn))
408                 return;
409
410         if (arch_irn_is_ignore(irn))
411                 return;
412
413         /* insert the new irn */
414         pdeq_putr(path, irn);
415
416
417
418         /* check for forbidden interferences */
419         len       = pdeq_len(path);
420         curr_path = ALLOCAN(ir_node*, len);
421         pdeq_copyl(path, (const void **)curr_path);
422
423         for (i=1; i<len; ++i)
424                 if (be_ifg_connected(ifg, irn, curr_path[i]))
425                         goto end;
426
427
428
429         /* check for terminating interference */
430         if (be_ifg_connected(ifg, irn, curr_path[0])) {
431
432                 /* One node is not a path. */
433                 /* And a path of length 2 is covered by a clique star constraint. */
434                 if (len > 2) {
435                         /* finally build the constraint */
436                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, 1.0);
437                         for (i=1; i<len; ++i) {
438                                 char buf[16];
439                                 int nr_1    = get_irn_idx(curr_path[i-1]);
440                                 int nr_2    = get_irn_idx(curr_path[i]);
441                                 int var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', nr_1, nr_2));
442                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
443                         }
444                 }
445
446                 /* this path cannot be extended anymore */
447                 goto end;
448         }
449
450
451
452         /* recursively extend the path */
453         aff = get_affinity_info(ienv->co, irn);
454         co_gs_foreach_neighb(aff, nbr)
455                 extend_path(ienv, path, nbr->irn);
456
457
458 end:
459         /* remove the irn */
460         pdeq_getr(path);
461
462 }
463
464 /**
465  *  Search a path of affinity edges, whose ends are connected
466  *  by an interference edge and there are no other interference
467  *  edges in between.
468  *  Then at least one of these affinity edges must break.
469  */
470 static void build_path_cstr(ilp_env_t *ienv) {
471         affinity_node_t *aff_info;
472
473         /* for each node with affinity edges */
474         co_gs_foreach_aff_node(ienv->co, aff_info) {
475                 pdeq *path = new_pdeq();
476
477                 extend_path(ienv, path, aff_info->irn);
478
479                 del_pdeq(path);
480         }
481 }
482
483 static void ilp2_build(ilp_env_t *ienv) {
484         local_env_t *lenv = ienv->env;
485         int lower_bound;
486
487         ienv->lp = new_lpp(ienv->co->name, lpp_minimize);
488         build_coloring_cstr(ienv);
489         build_interference_cstr(ienv);
490         build_affinity_cstr(ienv);
491         build_clique_star_cstr(ienv);
492         build_path_cstr(ienv);
493
494         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
495         lpp_set_bound(ienv->lp, lower_bound);
496         lpp_set_time_limit(ienv->lp, lenv->time_limit);
497 }
498
499 static void ilp2_apply(ilp_env_t *ienv) {
500         local_env_t *lenv = ienv->env;
501         int i;
502
503         /* first check if there was sth. to optimize */
504         if (lenv->first_x_var >= 0) {
505                 int              count = lenv->last_x_var - lenv->first_x_var + 1;
506                 double          *sol   = XMALLOCN(double, count);
507                 lpp_sol_state_t  state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
508
509                 if (state != lpp_optimal) {
510                         printf("WARNING %s: Solution state is not 'optimal': %d\n", ienv->co->name, state);
511                         assert(state >= lpp_feasible && "The solution should at least be feasible!");
512                 }
513
514                 for (i=0; i<count; ++i) {
515                         int nodenr, color;
516                         char var_name[16];
517
518                         if (sol[i] > 1-EPSILON) { /* split variable name into components */
519                                 lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
520
521                                 if (sscanf(var_name, "x_%d_%d", &nodenr, &color) == 2) {
522                                         ir_node *irn = pmap_get(lenv->nr_2_irn, INT_TO_PTR(nodenr));
523                                         assert(irn && "This node number must be present in the map");
524
525                                         set_irn_col(ienv->co, irn, color);
526                                 } else
527                                         assert(0 && "This should be a x-var");
528                         }
529                 }
530
531                 xfree(sol);
532         }
533
534 #ifdef COPYOPT_STAT
535         /* TODO adapt to multiple possible ILPs */
536         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
537         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
538         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
539         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
540 #endif
541 }
542
543 void be_init_copyilp2(void)
544 {
545         static co_algo_info copyheur = {
546                 co_solve_ilp2, 1
547         };
548
549         be_register_copyopt("ilp", &copyheur);
550 }
551
552 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyilp2);
553
554 int co_solve_ilp2(copy_opt_t *co) {
555         lpp_sol_state_t sol_state;
556         ilp_env_t *ienv;
557         local_env_t my;
558
559         ASSERT_OU_AVAIL(co); //See build_clique_st
560         ASSERT_GS_AVAIL(co);
561
562         my.time_limit  = 0;
563         my.first_x_var = -1;
564         my.last_x_var  = -1;
565         my.nr_2_irn    = pmap_create();
566         FIRM_DBG_REGISTER(my.dbg, "firm.be.coilp2");
567
568         my.normal_colors = bitset_alloca(arch_register_class_n_regs(co->cls));
569         bitset_clear_all(my.normal_colors);
570         arch_put_non_ignore_regs(co->cls, my.normal_colors);
571         my.n_colors = bitset_popcnt(my.normal_colors);
572
573         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
574
575         sol_state = ilp_go(ienv);
576
577         pmap_destroy(my.nr_2_irn);
578         free_ilp_env(ienv);
579
580         return sol_state == lpp_optimal;
581 }
582
583 #else /* WITH_ILP */
584
585 static inline void only_that_you_can_compile_without_WITH_ILP_defined(void) {
586 }
587
588 #endif /* WITH_ILP */