no environment anymore for emitters
[libfirm] / ir / be / becopyilp2.c
1 /*
2  * Copyright (C) 1995-2007 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 #ifdef HAVE_CONFIG_H
48 #include "config.h"
49 #endif /* HAVE_CONFIG_H */
50
51 #include "firm_config.h"
52
53 #ifdef WITH_ILP
54
55 #include "bitset.h"
56 #include "raw_bitset.h"
57 #include "pdeq.h"
58
59 #include "irtools.h"
60 #include "irgwalk.h"
61 #include "becopyilp_t.h"
62 #include "beifg_t.h"
63 #include "besched_t.h"
64 #include "benodesets.h"
65
66 #define DEBUG_LVL 1
67
68 typedef struct _local_env_t {
69         double time_limit;
70         int first_x_var, last_x_var;
71         pmap *nr_2_irn;
72         DEBUG_ONLY(firm_dbg_module_t *dbg;)
73 } local_env_t;
74
75 static void build_coloring_cstr(ilp_env_t *ienv) {
76         be_ifg_t *ifg = ienv->co->cenv->ifg;
77         void *iter = be_ifg_nodes_iter_alloca(ifg);
78         bitset_t *colors;
79         ir_node *irn;
80         char buf[16];
81
82         colors = bitset_alloca(arch_register_class_n_regs(ienv->co->cls));
83
84         be_ifg_foreach_node(ifg, iter, irn)
85                 if (!sr_is_removed(ienv->sr, irn)) {
86                         bitset_pos_t col;
87                         int cst_idx;
88                         const arch_register_req_t *req;
89                         int curr_node_color = get_irn_col(ienv->co, irn);
90                         int node_nr = (int)get_irn_node_nr(irn);
91                         local_env_t *lenv = ienv->env;
92
93                         pmap_insert(lenv->nr_2_irn, INT_TO_PTR(node_nr), irn);
94
95                         req = arch_get_register_req(ienv->co->aenv, irn, -1);
96
97                         /* get assignable colors */
98                         if (arch_register_req_is(req, limited)) {
99                                 rbitset_copy_to_bitset(req->limited, colors);
100                         } else {
101                                 arch_register_class_put(req->cls, colors);
102                                 // bitset_andnot(colors, ienv->co->cenv->ignore_colors);
103                         }
104
105                         /* add the coloring constraint */
106                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
107
108                         bitset_foreach(colors, col) {
109                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
110                                 lpp_set_start_value(ienv->lp, var_idx, (col == (unsigned) curr_node_color) ? 1.0 : 0.0);
111                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
112
113                                 lenv->last_x_var = var_idx;
114                                 if (lenv->first_x_var == -1)
115                                         lenv->first_x_var = var_idx;
116                         }
117
118                         /* add register constraint constraints */
119                         bitset_foreach_clear(colors, col) {
120                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
121                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
122                                 lpp_set_start_value(ienv->lp, var_idx, 0.0);
123                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
124
125                                 lenv->last_x_var = var_idx;
126                         }
127                 }
128 }
129
130 static void build_interference_cstr(ilp_env_t *ienv) {
131         lpp_t *lpp = ienv->lp;
132         be_ifg_t *ifg = ienv->co->cenv->ifg;
133         int n_colors = arch_register_class_n_regs(ienv->co->cls);
134         int i, col;
135
136         void *iter = be_ifg_cliques_iter_alloca(ifg);
137         ir_node **clique = alloca(sizeof(*clique) * n_colors);
138         int size;
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_node_nr(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         unit_t *curr;
178         int n_colors = arch_register_class_n_regs(ienv->co->cls);
179
180         /* for all optimization units */
181         list_for_each_entry(unit_t, curr, &ienv->co->units, units) {
182                 ir_node *root, *arg;
183                 int root_nr, arg_nr, i, col, y_idx, root_idx, arg_idx;
184                 char buf[16];
185                 int root_col, arg_col;
186
187                 root = curr->nodes[0];
188                 root_nr = (int) get_irn_node_nr(root);
189                 root_col = get_irn_col(ienv->co, root);
190
191                 for (i = 1; i < curr->node_count; ++i) {
192                         arg = curr->nodes[i];
193                         arg_nr = (int) get_irn_node_nr(arg);
194                         arg_col = get_irn_col(ienv->co, arg);
195
196                         /* add a new affinity variable */
197                         y_idx = lpp_add_var(ienv->lp, name_cdd_sorted(buf, 'y', root_nr, arg_nr), lpp_binary, curr->costs[i]);
198                         lpp_set_start_value(ienv->lp, y_idx, (root_col==arg_col) ? 0.0 : 1.0);
199
200                         /* add constraints relating the affinity var to the color vars */
201                         for (col=0; col<n_colors; ++col) {
202                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_less, 0.0);
203                                 root_idx = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', root_nr, col));
204                                 arg_idx  = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', arg_nr,  col));
205
206                                 lpp_set_factor_fast(ienv->lp, cst_idx, root_idx,  1.0);
207                                 lpp_set_factor_fast(ienv->lp, cst_idx, arg_idx,  -1.0);
208                                 lpp_set_factor_fast(ienv->lp, cst_idx, y_idx, -1.0);
209                         }
210                 }
211         }
212 }
213
214 /**
215  * Helping stuff for build_clique_star_cstr
216  */
217 typedef struct _edge_t {
218         ir_node *n1, *n2;
219 } edge_t;
220
221 static int compare_edge_t(const void *k1, const void *k2, size_t size) {
222         const edge_t *e1 = k1;
223         const edge_t *e2 = k2;
224         (void) size;
225
226         return ! (e1->n1 == e2->n1   &&   e1->n2 == e2->n2);
227 }
228
229 #define HASH_EDGE(e) (nodeset_hash((e)->n1) ^ nodeset_hash((e)->n2))
230
231 static INLINE edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
232         edge_t new_edge;
233
234         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
235                 new_edge.n1 = n1;
236                 new_edge.n2 = n2;
237         } else {
238                 new_edge.n1 = n2;
239                 new_edge.n2 = n1;
240         }
241         (*counter)++;
242         return set_insert(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
243 }
244
245 static INLINE edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2) {
246         edge_t new_edge;
247
248         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
249                 new_edge.n1 = n1;
250                 new_edge.n2 = n2;
251         } else {
252                 new_edge.n1 = n2;
253                 new_edge.n2 = n1;
254         }
255         return set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
256 }
257
258 static INLINE void remove_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
259         edge_t new_edge, *e;
260
261         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
262                 new_edge.n1 = n1;
263                 new_edge.n2 = n2;
264         } else {
265                 new_edge.n1 = n2;
266                 new_edge.n2 = n1;
267         }
268         e = set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
269         if (e) {
270                 e->n1 = NULL;
271                 e->n2 = NULL;
272                 (*counter)--;
273         }
274 }
275
276 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
277
278 /**
279  * Search for an interference clique and an external node
280  * with affinity edges to all nodes of the clique.
281  * At most 1 node of the clique can be colored equally with the external node.
282  */
283 static void build_clique_star_cstr(ilp_env_t *ienv) {
284         affinity_node_t *aff;
285
286         /* for each node with affinity edges */
287         co_gs_foreach_aff_node(ienv->co, aff) {
288                 struct obstack ob;
289                 neighb_t *nbr;
290                 ir_node *center = aff->irn;
291                 ir_node **nodes;
292                 set *edges;
293                 int i, o, n_nodes, n_edges;
294
295                 obstack_init(&ob);
296                 edges = new_set(compare_edge_t, 8);
297
298                 /* get all affinity neighbours */
299                 n_nodes = 0;
300                 co_gs_foreach_neighb(aff, nbr) {
301                         obstack_ptr_grow(&ob, nbr->irn);
302                         ++n_nodes;
303                 }
304                 nodes = obstack_finish(&ob);
305
306                 /* get all interference edges between these */
307                 n_edges = 0;
308                 for (i=0; i<n_nodes; ++i)
309                         for (o=0; o<i; ++o)
310                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
311                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
312
313                 /* cover all these interference edges with maximal cliques */
314                 while (n_edges) {
315                         edge_t *e;
316                         pset *clique = pset_new_ptr(8);
317                         int growed;
318
319                         /* get 2 starting nodes to form a clique */
320                         for (e=set_first(edges); !e->n1; e=set_next(edges))
321                                 /*nothing*/ ;
322
323                         /* we could be stepped out of the loop before the set iterated to the end */
324                         set_break(edges);
325
326                         pset_insert_ptr(clique, e->n1);
327                         pset_insert_ptr(clique, e->n2);
328                         remove_edge(edges, e->n1, e->n2, &n_edges);
329
330                         /* while the clique is growing */
331                         do {
332                                 growed = 0;
333
334                                 /* search for a candidate to extend the clique */
335                                 for (i=0; i<n_nodes; ++i) {
336                                         ir_node *member, *cand = nodes[i];
337                                         int is_cand;
338
339                                         /* if its already in the clique try the next */
340                                         if (pset_find_ptr(clique, cand))
341                                                 continue;
342
343                                         /* are there all necessary interferences? */
344                                         is_cand = 1;
345                                         pset_foreach(clique, member) {
346                                                 if (!find_edge(edges, cand, member)) {
347                                                         is_cand = 0;
348                                                         pset_break(clique);
349                                                         break;
350                                                 }
351                                         }
352
353                                         /* now we know if we have a clique extender */
354                                         if (is_cand) {
355                                                 /* first remove all covered edges */
356                                                 pset_foreach(clique, member)
357                                                         remove_edge(edges, cand, member, &n_edges);
358
359                                                 /* insert into clique */
360                                                 pset_insert_ptr(clique, cand);
361                                                 growed = 1;
362                                                 break;
363                                         }
364                                 }
365                         } while (growed);
366
367                         /* now the clique is maximal. Finally add the constraint */
368                         {
369                                 ir_node *member;
370                                 int var_idx, cst_idx, center_nr, member_nr;
371                                 char buf[16];
372
373                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, pset_count(clique)-1);
374                                 center_nr = get_irn_node_nr(center);
375
376                                 pset_foreach(clique, member) {
377                                         member_nr = get_irn_node_nr(member);
378                                         var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', center_nr, member_nr));
379                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
380                                 }
381                         }
382
383                         del_pset(clique);
384                 }
385
386                 del_set(edges);
387                 obstack_free(&ob, NULL);
388         }
389 }
390
391
392 static void extend_path(ilp_env_t *ienv, pdeq *path, ir_node *irn) {
393         be_ifg_t *ifg = ienv->co->cenv->ifg;
394         int i, len;
395         ir_node **curr_path;
396         affinity_node_t *aff;
397         neighb_t *nbr;
398
399         /* do not walk backwards or in circles */
400         if (pdeq_contains(path, irn))
401                 return;
402
403         /* insert the new irn */
404         pdeq_putr(path, irn);
405
406
407
408         /* check for forbidden interferences */
409         len = pdeq_len(path);
410         curr_path = alloca(len * sizeof(*curr_path));
411         pdeq_copyl(path, (const void **)curr_path);
412
413         for (i=1; i<len; ++i)
414                 if (be_ifg_connected(ifg, irn, curr_path[i]))
415                         goto end;
416
417
418
419         /* check for terminating interference */
420         if (be_ifg_connected(ifg, irn, curr_path[0])) {
421
422                 /* One node is not a path. */
423                 /* And a path of length 2 is covered by a clique star constraint. */
424                 if (len > 2) {
425                         /* finally build the constraint */
426                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, 1.0);
427                         for (i=1; i<len; ++i) {
428                                 char buf[16];
429                                 int nr_1    = get_irn_node_nr(curr_path[i-1]);
430                                 int nr_2    = get_irn_node_nr(curr_path[i]);
431                                 int var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', nr_1, nr_2));
432                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
433                         }
434                 }
435
436                 /* this path cannot be extended anymore */
437                 goto end;
438         }
439
440
441
442         /* recursively extend the path */
443         aff = get_affinity_info(ienv->co, irn);
444         co_gs_foreach_neighb(aff, nbr)
445                 extend_path(ienv, path, nbr->irn);
446
447
448 end:
449         /* remove the irn */
450         pdeq_getr(path);
451
452 }
453
454 /**
455  *  Search a path of affinity edges, whose ends are connected
456  *  by an interference edge and there are no other interference
457  *  edges in between.
458  *  Then at least one of these affinity edges must break.
459  */
460 static void build_path_cstr(ilp_env_t *ienv) {
461         affinity_node_t *aff_info;
462
463         /* for each node with affinity edges */
464         co_gs_foreach_aff_node(ienv->co, aff_info) {
465                 pdeq *path = new_pdeq();
466
467                 extend_path(ienv, path, aff_info->irn);
468
469                 del_pdeq(path);
470         }
471 }
472
473 static void ilp2_build(ilp_env_t *ienv) {
474         local_env_t *lenv = ienv->env;
475         int lower_bound;
476
477         ienv->lp = new_lpp(ienv->co->name, lpp_minimize);
478         build_coloring_cstr(ienv);
479         build_interference_cstr(ienv);
480         build_affinity_cstr(ienv);
481         build_clique_star_cstr(ienv);
482         build_path_cstr(ienv);
483
484         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
485         lpp_set_bound(ienv->lp, lower_bound);
486         lpp_set_time_limit(ienv->lp, lenv->time_limit);
487 }
488
489 static void ilp2_apply(ilp_env_t *ienv) {
490         local_env_t *lenv = ienv->env;
491         double *sol;
492         lpp_sol_state_t state;
493         int i, count;
494
495         /* first check if there was sth. to optimize */
496         if (lenv->first_x_var >= 0) {
497
498                 count = lenv->last_x_var - lenv->first_x_var + 1;
499                 sol = xmalloc(count * sizeof(sol[0]));
500                 state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
501                 if (state != lpp_optimal) {
502                         printf("WARNING %s: Solution state is not 'optimal': %d\n", ienv->co->name, state);
503                         assert(state >= lpp_feasible && "The solution should at least be feasible!");
504                 }
505
506                 for (i=0; i<count; ++i) {
507                         int nodenr, color;
508                         char var_name[16];
509
510                         if (sol[i] > 1-EPSILON) { /* split variable name into components */
511                                 lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
512
513                                 if (sscanf(var_name, "x_%d_%d", &nodenr, &color) == 2) {
514                                         ir_node *irn = pmap_get(lenv->nr_2_irn, INT_TO_PTR(nodenr));
515                                         assert(irn && "This node number must be present in the map");
516
517                                         set_irn_col(ienv->co, irn, color);
518                                 } else
519                                         assert(0 && "This should be a x-var");
520                         }
521                 }
522         }
523
524 #ifdef COPYOPT_STAT
525         /* TODO adapt to multiple possible ILPs */
526         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
527         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
528         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
529         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
530 #endif
531 }
532
533 int co_solve_ilp2(copy_opt_t *co) {
534         lpp_sol_state_t sol_state;
535         ilp_env_t *ienv;
536         local_env_t my;
537
538         ASSERT_OU_AVAIL(co); //See build_clique_st
539         ASSERT_GS_AVAIL(co);
540
541         my.time_limit  = 0;
542         my.first_x_var = -1;
543         my.last_x_var  = -1;
544         my.nr_2_irn    = pmap_create();
545         FIRM_DBG_REGISTER(my.dbg, "firm.be.coilp2");
546
547         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
548
549         sol_state = ilp_go(ienv);
550
551         pmap_destroy(my.nr_2_irn);
552         free_ilp_env(ienv);
553
554         return sol_state == lpp_optimal;
555 }
556
557 #else /* WITH_ILP */
558
559 static INLINE void only_that_you_can_compile_without_WITH_ILP_defined(void) {
560 }
561
562 #endif /* WITH_ILP */