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