we always have liblpp now, remove WITH_ILP flag
[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 #include "bitset.h"
50 #include "raw_bitset.h"
51 #include "pdeq.h"
52
53 #include "irtools.h"
54 #include "irgwalk.h"
55 #include "becopyilp_t.h"
56 #include "beifg.h"
57 #include "besched.h"
58 #include "bemodule.h"
59
60 #define DEBUG_LVL 1
61
62 typedef struct local_env_t {
63         double time_limit;
64         int first_x_var, last_x_var;
65         int n_colors;
66         bitset_t *normal_colors;
67         pmap *nr_2_irn;
68         DEBUG_ONLY(firm_dbg_module_t *dbg;)
69 } local_env_t;
70
71 static void build_coloring_cstr(ilp_env_t *ienv)
72 {
73         be_ifg_t *ifg     = ienv->co->cenv->ifg;
74         nodes_iter_t iter;
75         bitset_t *colors;
76         ir_node *irn;
77         char buf[16];
78
79         colors = bitset_alloca(arch_register_class_n_regs(ienv->co->cls));
80
81         be_ifg_foreach_node(ifg, &iter, irn)
82                 if (!sr_is_removed(ienv->sr, irn)) {
83                         size_t col;
84                         int cst_idx;
85                         const arch_register_req_t *req;
86                         int curr_node_color = get_irn_col(irn);
87                         int node_nr = (int)get_irn_idx(irn);
88                         local_env_t *lenv = ienv->env;
89
90                         pmap_insert(lenv->nr_2_irn, INT_TO_PTR(node_nr), irn);
91
92                         req = arch_get_register_req_out(irn);
93
94                         bitset_clear_all(colors);
95
96                         /* get assignable colors */
97                         if (arch_register_req_is(req, limited)) {
98                                 rbitset_copy_to_bitset(req->limited, colors);
99                         } else {
100                                 bitset_copy(colors, lenv->normal_colors);
101                         }
102
103                         /* add the coloring constraint */
104                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
105
106                         bitset_foreach(colors, col) {
107                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
108                                 lpp_set_start_value(ienv->lp, var_idx, (col == (unsigned) curr_node_color) ? 1.0 : 0.0);
109                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
110
111                                 lenv->last_x_var = var_idx;
112                                 if (lenv->first_x_var == -1)
113                                         lenv->first_x_var = var_idx;
114                         }
115
116                         /* add register constraint constraints */
117                         bitset_foreach_clear(colors, col) {
118                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
119                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
120                                 lpp_set_start_value(ienv->lp, var_idx, 0.0);
121                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
122
123                                 lenv->last_x_var = var_idx;
124                         }
125                 }
126 }
127
128 static void build_interference_cstr(ilp_env_t *ienv)
129 {
130         lpp_t       *lpp      = ienv->lp;
131         local_env_t *lenv     = ienv->env;
132         be_ifg_t    *ifg      = ienv->co->cenv->ifg;
133         int          n_colors = lenv->n_colors;
134         cliques_iter_t iter;
135         ir_node    **clique   = ALLOCAN(ir_node*, n_colors);
136         int          size;
137         int          col;
138         int          i;
139
140         char buf[16];
141
142         /* for each maximal clique */
143         be_ifg_foreach_clique(ifg, &iter, clique, &size) {
144                 int realsize = 0;
145
146                 for (i=0; i<size; ++i)
147                         if (!sr_is_removed(ienv->sr, clique[i]))
148                                 ++realsize;
149
150                 if (realsize < 2)
151                         continue;
152
153                 /* for all colors */
154                 for (col=0; col<n_colors; ++col) {
155                         int cst_idx = lpp_add_cst(lpp, NULL, lpp_less, 1.0);
156
157                         /* for each member of this clique */
158                         for (i=0; i<size; ++i) {
159                                 ir_node *irn = clique[i];
160
161                                 if (!sr_is_removed(ienv->sr, irn)) {
162                                         int var_idx = lpp_get_var_idx(lpp, name_cdd(buf, 'x', (int)get_irn_idx(irn), col));
163                                         lpp_set_factor_fast(lpp, cst_idx, var_idx, 1);
164                                 }
165                         }
166                 }
167         }
168 }
169
170
171 /**
172  * TODO: Remove the dependency of the opt-units data structure
173  *       by walking over all affinity edges. Graph structure
174  *       does not provide this walker, yet.
175  */
176 static void build_affinity_cstr(ilp_env_t *ienv)
177 {
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 {
225         const edge_t *e1 = k1;
226         const edge_t *e2 = k2;
227         (void) size;
228
229         return ! (e1->n1 == e2->n1   &&   e1->n2 == e2->n2);
230 }
231
232 #define HASH_EDGE(e) (hash_irn((e)->n1) ^ hash_irn((e)->n2))
233
234 static inline edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, int *counter)
235 {
236         edge_t new_edge;
237
238         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
239                 new_edge.n1 = n1;
240                 new_edge.n2 = n2;
241         } else {
242                 new_edge.n1 = n2;
243                 new_edge.n2 = n1;
244         }
245         (*counter)++;
246         return set_insert(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
247 }
248
249 static inline edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2)
250 {
251         edge_t new_edge;
252
253         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
254                 new_edge.n1 = n1;
255                 new_edge.n2 = n2;
256         } else {
257                 new_edge.n1 = n2;
258                 new_edge.n2 = n1;
259         }
260         return set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
261 }
262
263 static inline void remove_edge(set *edges, ir_node *n1, ir_node *n2, int *counter)
264 {
265         edge_t new_edge, *e;
266
267         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
268                 new_edge.n1 = n1;
269                 new_edge.n2 = n2;
270         } else {
271                 new_edge.n1 = n2;
272                 new_edge.n2 = n1;
273         }
274         e = set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
275         if (e) {
276                 e->n1 = NULL;
277                 e->n2 = NULL;
278                 (*counter)--;
279         }
280 }
281
282 #define pset_foreach(pset, irn)  for (irn=pset_first(pset); irn; irn=pset_next(pset))
283
284 /**
285  * Search for an interference clique and an external node
286  * with affinity edges to all nodes of the clique.
287  * At most 1 node of the clique can be colored equally with the external node.
288  */
289 static void build_clique_star_cstr(ilp_env_t *ienv)
290 {
291         affinity_node_t *aff;
292
293         /* for each node with affinity edges */
294         co_gs_foreach_aff_node(ienv->co, aff) {
295                 struct obstack ob;
296                 neighb_t *nbr;
297                 const ir_node *center = aff->irn;
298                 ir_node **nodes;
299                 set *edges;
300                 int i, o, n_nodes, n_edges;
301
302                 if (arch_irn_is_ignore(aff->irn))
303                         continue;
304
305                 obstack_init(&ob);
306                 edges = new_set(compare_edge_t, 8);
307
308                 /* get all affinity neighbours */
309                 n_nodes = 0;
310                 co_gs_foreach_neighb(aff, nbr) {
311                         if (!arch_irn_is_ignore(nbr->irn)) {
312                                 obstack_ptr_grow(&ob, nbr->irn);
313                                 ++n_nodes;
314                         }
315                 }
316                 nodes = obstack_finish(&ob);
317
318                 /* get all interference edges between these */
319                 n_edges = 0;
320                 for (i=0; i<n_nodes; ++i)
321                         for (o=0; o<i; ++o)
322                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
323                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
324
325                 /* cover all these interference edges with maximal cliques */
326                 while (n_edges) {
327                         edge_t *e;
328                         pset *clique = pset_new_ptr(8);
329                         int growed;
330
331                         /* get 2 starting nodes to form a clique */
332                         for (e=set_first(edges); !e->n1; e=set_next(edges))
333                                 /*nothing*/ ;
334
335                         /* we could be stepped out of the loop before the set iterated to the end */
336                         set_break(edges);
337
338                         pset_insert_ptr(clique, e->n1);
339                         pset_insert_ptr(clique, e->n2);
340                         remove_edge(edges, e->n1, e->n2, &n_edges);
341
342                         /* while the clique is growing */
343                         do {
344                                 growed = 0;
345
346                                 /* search for a candidate to extend the clique */
347                                 for (i=0; i<n_nodes; ++i) {
348                                         ir_node *member, *cand = nodes[i];
349                                         int is_cand;
350
351                                         /* if its already in the clique try the next */
352                                         if (pset_find_ptr(clique, cand))
353                                                 continue;
354
355                                         /* are there all necessary interferences? */
356                                         is_cand = 1;
357                                         pset_foreach(clique, member) {
358                                                 if (!find_edge(edges, cand, member)) {
359                                                         is_cand = 0;
360                                                         pset_break(clique);
361                                                         break;
362                                                 }
363                                         }
364
365                                         /* now we know if we have a clique extender */
366                                         if (is_cand) {
367                                                 /* first remove all covered edges */
368                                                 pset_foreach(clique, member)
369                                                         remove_edge(edges, cand, member, &n_edges);
370
371                                                 /* insert into clique */
372                                                 pset_insert_ptr(clique, cand);
373                                                 growed = 1;
374                                                 break;
375                                         }
376                                 }
377                         } while (growed);
378
379                         /* now the clique is maximal. Finally add the constraint */
380                         {
381                                 ir_node *member;
382                                 int var_idx, cst_idx, center_nr, member_nr;
383                                 char buf[16];
384
385                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, pset_count(clique)-1);
386                                 center_nr = get_irn_idx(center);
387
388                                 pset_foreach(clique, member) {
389                                         member_nr = get_irn_idx(member);
390                                         var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', center_nr, member_nr));
391                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
392                                 }
393                         }
394
395                         del_pset(clique);
396                 }
397
398                 del_set(edges);
399                 obstack_free(&ob, NULL);
400         }
401 }
402
403
404 static void extend_path(ilp_env_t *ienv, pdeq *path, const ir_node *irn)
405 {
406         be_ifg_t *ifg = ienv->co->cenv->ifg;
407         int i, len;
408         ir_node **curr_path;
409         affinity_node_t *aff;
410         neighb_t *nbr;
411
412         /* do not walk backwards or in circles */
413         if (pdeq_contains(path, irn))
414                 return;
415
416         if (arch_irn_is_ignore(irn))
417                 return;
418
419         /* insert the new irn */
420         pdeq_putr(path, irn);
421
422
423
424         /* check for forbidden interferences */
425         len       = pdeq_len(path);
426         curr_path = ALLOCAN(ir_node*, len);
427         pdeq_copyl(path, (const void **)curr_path);
428
429         for (i=1; i<len; ++i)
430                 if (be_ifg_connected(ifg, irn, curr_path[i]))
431                         goto end;
432
433
434
435         /* check for terminating interference */
436         if (be_ifg_connected(ifg, irn, curr_path[0])) {
437
438                 /* One node is not a path. */
439                 /* And a path of length 2 is covered by a clique star constraint. */
440                 if (len > 2) {
441                         /* finally build the constraint */
442                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, 1.0);
443                         for (i=1; i<len; ++i) {
444                                 char buf[16];
445                                 int nr_1    = get_irn_idx(curr_path[i-1]);
446                                 int nr_2    = get_irn_idx(curr_path[i]);
447                                 int var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', nr_1, nr_2));
448                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
449                         }
450                 }
451
452                 /* this path cannot be extended anymore */
453                 goto end;
454         }
455
456
457
458         /* recursively extend the path */
459         aff = get_affinity_info(ienv->co, irn);
460         co_gs_foreach_neighb(aff, nbr)
461                 extend_path(ienv, path, nbr->irn);
462
463
464 end:
465         /* remove the irn */
466         pdeq_getr(path);
467
468 }
469
470 /**
471  *  Search a path of affinity edges, whose ends are connected
472  *  by an interference edge and there are no other interference
473  *  edges in between.
474  *  Then at least one of these affinity edges must break.
475  */
476 static void build_path_cstr(ilp_env_t *ienv)
477 {
478         affinity_node_t *aff_info;
479
480         /* for each node with affinity edges */
481         co_gs_foreach_aff_node(ienv->co, aff_info) {
482                 pdeq *path = new_pdeq();
483
484                 extend_path(ienv, path, aff_info->irn);
485
486                 del_pdeq(path);
487         }
488 }
489
490 static void ilp2_build(ilp_env_t *ienv)
491 {
492         local_env_t *lenv = ienv->env;
493         int lower_bound;
494
495         ienv->lp = new_lpp(ienv->co->name, lpp_minimize);
496         build_coloring_cstr(ienv);
497         build_interference_cstr(ienv);
498         build_affinity_cstr(ienv);
499         build_clique_star_cstr(ienv);
500         build_path_cstr(ienv);
501
502         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
503         lpp_set_bound(ienv->lp, lower_bound);
504         lpp_set_time_limit(ienv->lp, lenv->time_limit);
505 }
506
507 static void ilp2_apply(ilp_env_t *ienv)
508 {
509         local_env_t *lenv = ienv->env;
510         int i;
511
512         /* first check if there was sth. to optimize */
513         if (lenv->first_x_var >= 0) {
514                 int              count = lenv->last_x_var - lenv->first_x_var + 1;
515                 double          *sol   = XMALLOCN(double, count);
516                 lpp_sol_state_t  state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
517
518                 if (state != lpp_optimal) {
519                         printf("WARNING %s: Solution state is not 'optimal': %d\n", ienv->co->name, state);
520                         assert(state >= lpp_feasible && "The solution should at least be feasible!");
521                 }
522
523                 for (i=0; i<count; ++i) {
524                         int nodenr, color;
525                         char var_name[16];
526
527                         if (sol[i] > 1-EPSILON) { /* split variable name into components */
528                                 lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
529
530                                 if (sscanf(var_name, "x_%d_%d", &nodenr, &color) == 2) {
531                                         ir_node *irn = pmap_get(lenv->nr_2_irn, INT_TO_PTR(nodenr));
532                                         assert(irn && "This node number must be present in the map");
533
534                                         set_irn_col(ienv->co, irn, color);
535                                 } else
536                                         assert(0 && "This should be a x-var");
537                         }
538                 }
539
540                 xfree(sol);
541         }
542
543 #ifdef COPYOPT_STAT
544         /* TODO adapt to multiple possible ILPs */
545         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
546         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
547         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
548         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
549 #endif
550 }
551
552 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyilp2);
553 void be_init_copyilp2(void)
554 {
555         static co_algo_info copyheur = {
556                 co_solve_ilp2, 1
557         };
558
559         be_register_copyopt("ilp", &copyheur);
560 }
561
562 int co_solve_ilp2(copy_opt_t *co)
563 {
564         lpp_sol_state_t sol_state;
565         ilp_env_t *ienv;
566         local_env_t my;
567
568         ASSERT_OU_AVAIL(co); //See build_clique_st
569         ASSERT_GS_AVAIL(co);
570
571         my.time_limit  = 0;
572         my.first_x_var = -1;
573         my.last_x_var  = -1;
574         my.nr_2_irn    = pmap_create();
575         FIRM_DBG_REGISTER(my.dbg, "firm.be.coilp2");
576
577         my.normal_colors = bitset_alloca(arch_register_class_n_regs(co->cls));
578         bitset_clear_all(my.normal_colors);
579         be_put_allocatable_regs(co->irg, co->cls, my.normal_colors);
580         my.n_colors = bitset_popcount(my.normal_colors);
581
582         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
583
584         sol_state = ilp_go(ienv);
585
586         pmap_destroy(my.nr_2_irn);
587         free_ilp_env(ienv);
588
589         return sol_state == lpp_optimal;
590 }