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