beinsn: Do not store, whether insn operands are constrained.
[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  *
26  * ILP formalization using G=(V, E, Q):
27  *  - 2 class of variables: coloring vars x_ic   and   equal color vars y_ij
28  *  - Path constraints
29  *  - Clique-star constraints
30  *
31  *
32  * \min \sum_{ (i,j) \in Q }  w_ij y_ij
33  *
34  *     \sum_c x_nc           =  1           n \in N, c \in C
35  *
36  *     x_nc                  =  0           n \in N, c \not\in C(n)
37  *
38  *     \sum x_nc            <=  1           x_nc \in Clique \in AllCliques,  c \in C
39  *
40  *     \sum_{e \in p} y_e   >=  1           p \in P      path constraints
41  *
42  *     \sum_{e \in cs} y_e  >= |cs| - 1     cs \in CP    clique-star constraints
43  *
44  *     x_nc, y_ij \in N,   w_ij \in R^+
45  */
46 #include "config.h"
47
48 #include "be_t.h"
49 #include "bitset.h"
50 #include "error.h"
51 #include "raw_bitset.h"
52 #include "pdeq.h"
53
54 #include "util.h"
55 #include "irgwalk.h"
56 #include "becopyilp_t.h"
57 #include "beifg.h"
58 #include "besched.h"
59 #include "bemodule.h"
60
61 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
62
63 typedef struct local_env_t {
64         int             first_x_var;
65         int             last_x_var;
66         const unsigned *allocatable_colors;
67 } local_env_t;
68
69 static unsigned check_alignment_constraints(ir_node *node)
70 {
71         const arch_register_req_t *req = arch_get_irn_register_req(node);
72         // For larger than 1 variables, support only aligned constraints
73         assert(((!(req->type & arch_register_req_type_aligned)
74                          && req->width == 1)
75                         || (req->type & arch_register_req_type_aligned))
76                    && "Unaligned large (width > 1) variables not supported");
77         return (req->type & arch_register_req_type_aligned) && req->width > 1;
78 }
79
80 static void make_color_var_name(char *buf, size_t buf_size,
81                                 const ir_node *node, unsigned color)
82 {
83         unsigned node_idx = get_irn_idx(node);
84         snprintf(buf, buf_size, "x_%u_%u", node_idx, color);
85 }
86
87 static void build_coloring_cstr(ilp_env_t *ienv)
88 {
89         local_env_t    *lenv   = (local_env_t*)ienv->env;
90         be_ifg_t       *ifg    = ienv->co->cenv->ifg;
91         unsigned        n_regs = arch_register_class_n_regs(ienv->co->cls);
92         const unsigned *allocatable_colors = lenv->allocatable_colors;
93         nodes_iter_t    iter;
94         unsigned       *colors;
95         ir_node        *irn;
96         char            buf[32];
97
98         rbitset_alloca(colors, n_regs);
99
100         be_ifg_foreach_node(ifg, &iter, irn) {
101                 const arch_register_req_t *req;
102                 unsigned                   col;
103                 int                        cst_idx;
104                 unsigned                   curr_node_color;
105                 unsigned                   has_alignment_cstr;
106
107                 if (sr_is_removed(ienv->sr, irn))
108                         continue;
109
110                 has_alignment_cstr = check_alignment_constraints(irn);
111
112                 req = arch_get_irn_register_req(irn);
113
114                 /* get assignable colors */
115                 if (arch_register_req_is(req, limited)) {
116                         rbitset_copy(colors, req->limited, n_regs);
117                 } else {
118                         rbitset_copy(colors, allocatable_colors, n_regs);
119                 }
120
121                 /* add the coloring constraint */
122                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
123
124                 curr_node_color = get_irn_col(irn);
125                 for (col = 0; col < n_regs; ++col) {
126                         int    var_idx;
127                         double val;
128                         if (!rbitset_is_set(colors, col)
129                                 || (has_alignment_cstr && ((col % req->width) != 0)))
130                                 continue;
131
132                         make_color_var_name(buf, sizeof(buf), irn, col);
133                         var_idx = lpp_add_var(ienv->lp, buf, lpp_binary, 0.0);
134                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
135
136                         val = (col == curr_node_color) ? 1.0 : 0.0;
137                         lpp_set_start_value(ienv->lp, var_idx, val);
138
139                         lenv->last_x_var = var_idx;
140                         if (lenv->first_x_var == -1)
141                                 lenv->first_x_var = var_idx;
142                 }
143
144                 /* add register constraint constraints */
145                 for (col = 0; col < n_regs; ++col) {
146                         int cst_idx;
147                         int var_idx;
148                         if (rbitset_is_set(colors, col)
149                                 // for aligned variable, we set the unaligned part to 0
150                                 && (!has_alignment_cstr || ((col % req->width) == 0)))
151                                 continue;
152
153                         make_color_var_name(buf, sizeof(buf), irn, col);
154                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
155                         var_idx = lpp_add_var(ienv->lp, buf, lpp_binary, 0.0);
156                         lpp_set_start_value(ienv->lp, var_idx, 0.0);
157                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
158
159                         lenv->last_x_var = var_idx;
160                 }
161         }
162 }
163
164 static void build_interference_cstr(ilp_env_t *ienv)
165 {
166         lpp_t          *lpp      = ienv->lp;
167         local_env_t    *lenv     = (local_env_t*)ienv->env;
168         be_ifg_t       *ifg      = ienv->co->cenv->ifg;
169         unsigned        n_colors = arch_register_class_n_regs(ienv->co->cls);
170         ir_node       **clique   = ALLOCAN(ir_node*, n_colors);
171         const unsigned *allocatable_colors = lenv->allocatable_colors;
172         cliques_iter_t iter;
173         int            size;
174         unsigned       col;
175         int            i;
176
177         /* for each maximal clique */
178         be_ifg_foreach_clique(ifg, &iter, clique, &size) {
179                 unsigned realsize = 0;
180
181                 for (i=0; i<size; ++i) {
182                         if (!sr_is_removed(ienv->sr, clique[i]))
183                                 ++realsize;
184                 }
185
186                 if (realsize < 2)
187                         continue;
188
189                 /* for all colors */
190                 for (col=0; col<n_colors; ++col) {
191                         int cst_idx;
192                         if (!rbitset_is_set(allocatable_colors, col))
193                                 continue;
194
195                         cst_idx = lpp_add_cst(lpp, NULL, lpp_less_equal, 1.0);
196
197                         /* for each member of this clique */
198                         for (i=0; i<size; ++i) {
199                                 ir_node *irn = clique[i];
200                                 char     buf[32];
201                                 int      var_idx;
202                                 unsigned aligment_offset = 0;
203
204                                 if (sr_is_removed(ienv->sr, irn))
205                                         continue;
206
207                                 // Use the first part of the large registers for all
208                                 // interference, since it is the only colorable one.
209                                 if (check_alignment_constraints(irn)) {
210                                         const arch_register_req_t *req
211                                                 = arch_get_irn_register_req(irn);
212                                         aligment_offset = col % req->width;
213                                 }
214
215                                 make_color_var_name(buf, sizeof(buf), irn,
216                                                                         col - aligment_offset);
217                                 var_idx = lpp_get_var_idx(lpp, buf);
218                                 lpp_set_factor_fast(lpp, cst_idx, var_idx, 1);
219                         }
220                 }
221         }
222 }
223
224 static void make_affinity_var_name(char *buf, size_t buf_size,
225                                    const ir_node *node1, const ir_node *node2)
226 {
227         unsigned n1 = get_irn_idx(node1);
228         unsigned n2 = get_irn_idx(node2);
229         if (n1 < n2) {
230                 snprintf(buf, buf_size, "y_%u_%u", n1, n2);
231         } else {
232                 snprintf(buf, buf_size, "y_%u_%u", n2, n1);
233         }
234 }
235
236
237 /**
238  * TODO: Remove the dependency of the opt-units data structure
239  *       by walking over all affinity edges. Graph structure
240  *       does not provide this walker, yet.
241  */
242 static void build_affinity_cstr(ilp_env_t *ienv)
243 {
244         unsigned  n_colors = arch_register_class_n_regs(ienv->co->cls);
245
246         /* for all optimization units */
247         list_for_each_entry(unit_t, curr, &ienv->co->units, units) {
248                 ir_node *root     = curr->nodes[0];
249                 unsigned root_col = get_irn_col(root);
250                 int      i;
251
252                 for (i = 1; i < curr->node_count; ++i) {
253                         ir_node *arg     = curr->nodes[i];
254                         unsigned arg_col = get_irn_col(arg);
255                         double   val;
256                         char     buf[32];
257                         unsigned col;
258                         int      y_idx;
259
260                         /* add a new affinity variable */
261                         make_affinity_var_name(buf, sizeof(buf), arg, root);
262                         y_idx = lpp_add_var(ienv->lp, buf, lpp_binary, curr->costs[i]);
263                         val   = (root_col == arg_col) ? 0.0 : 1.0;
264                         lpp_set_start_value(ienv->lp, y_idx, val);
265
266                         /* add constraints relating the affinity var to the color vars */
267                         for (col=0; col<n_colors; ++col) {
268                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_less_equal, 0.0);
269                                 int root_idx;
270                                 int arg_idx;
271
272                                 make_color_var_name(buf, sizeof(buf), root, col);
273                                 root_idx = lpp_get_var_idx(ienv->lp, buf);
274                                 make_color_var_name(buf, sizeof(buf), arg, col);
275                                 arg_idx  = lpp_get_var_idx(ienv->lp, buf);
276
277                                 lpp_set_factor_fast(ienv->lp, cst_idx, root_idx,  1.0);
278                                 lpp_set_factor_fast(ienv->lp, cst_idx, arg_idx,  -1.0);
279                                 lpp_set_factor_fast(ienv->lp, cst_idx, y_idx, -1.0);
280                         }
281                 }
282         }
283 }
284
285 /**
286  * Helping stuff for build_clique_star_cstr
287  */
288 typedef struct edge_t {
289         ir_node *n1;
290         ir_node *n2;
291 } edge_t;
292
293 static int compare_edge_t(const void *k1, const void *k2, size_t size)
294 {
295         const edge_t *e1 = (const edge_t*)k1;
296         const edge_t *e2 = (const edge_t*)k2;
297         (void) size;
298
299         return ! (e1->n1 == e2->n1 && e1->n2 == e2->n2);
300 }
301
302 #define HASH_EDGE(e) (hash_irn((e)->n1) ^ hash_irn((e)->n2))
303
304 static inline edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, size_t *counter)
305 {
306         edge_t new_edge;
307
308         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
309                 new_edge.n1 = n1;
310                 new_edge.n2 = n2;
311         } else {
312                 new_edge.n1 = n2;
313                 new_edge.n2 = n1;
314         }
315         (*counter)++;
316         return set_insert(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
317 }
318
319 static inline edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2)
320 {
321         edge_t new_edge;
322
323         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
324                 new_edge.n1 = n1;
325                 new_edge.n2 = n2;
326         } else {
327                 new_edge.n1 = n2;
328                 new_edge.n2 = n1;
329         }
330         return set_find(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
331 }
332
333 static inline void remove_edge(set *edges, ir_node *n1, ir_node *n2, size_t *counter)
334 {
335         edge_t new_edge, *e;
336
337         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
338                 new_edge.n1 = n1;
339                 new_edge.n2 = n2;
340         } else {
341                 new_edge.n1 = n2;
342                 new_edge.n2 = n1;
343         }
344         e = set_find(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
345         if (e) {
346                 e->n1 = NULL;
347                 e->n2 = NULL;
348                 (*counter)--;
349         }
350 }
351
352 #define pset_foreach(pset, irn) foreach_pset((pset), ir_node, (irn))
353
354 /**
355  * Search for an interference clique and an external node
356  * with affinity edges to all nodes of the clique.
357  * At most 1 node of the clique can be colored equally with the external node.
358  */
359 static void build_clique_star_cstr(ilp_env_t *ienv)
360 {
361         /* for each node with affinity edges */
362         co_gs_foreach_aff_node(ienv->co, aff) {
363                 struct obstack ob;
364                 const ir_node *center = aff->irn;
365                 ir_node **nodes;
366                 set *edges;
367                 int i, o, n_nodes;
368                 size_t n_edges;
369
370                 if (arch_irn_is_ignore(aff->irn))
371                         continue;
372
373                 obstack_init(&ob);
374                 edges = new_set(compare_edge_t, 8);
375
376                 /* get all affinity neighbours */
377                 n_nodes = 0;
378                 co_gs_foreach_neighb(aff, nbr) {
379                         if (!arch_irn_is_ignore(nbr->irn)) {
380                                 obstack_ptr_grow(&ob, nbr->irn);
381                                 ++n_nodes;
382                         }
383                 }
384                 nodes = (ir_node**)obstack_finish(&ob);
385
386                 /* get all interference edges between these */
387                 n_edges = 0;
388                 for (i=0; i<n_nodes; ++i) {
389                         for (o=0; o<i; ++o) {
390                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
391                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
392                         }
393                 }
394
395                 /* cover all these interference edges with maximal cliques */
396                 while (n_edges) {
397                         edge_t *e;
398                         pset   *clique = pset_new_ptr(8);
399                         bool    growed;
400
401                         /* get 2 starting nodes to form a clique */
402                         for (e = set_first(edge_t, edges); !e->n1; e = set_next(edge_t, edges)) {}
403
404                         /* we could be stepped out of the loop before the set iterated to the end */
405                         set_break(edges);
406
407                         pset_insert_ptr(clique, e->n1);
408                         pset_insert_ptr(clique, e->n2);
409                         remove_edge(edges, e->n1, e->n2, &n_edges);
410
411                         /* while the clique is growing */
412                         do {
413                                 growed = false;
414
415                                 /* search for a candidate to extend the clique */
416                                 for (i=0; i<n_nodes; ++i) {
417                                         ir_node *cand = nodes[i];
418                                         bool     is_cand;
419
420                                         /* if its already in the clique try the next */
421                                         if (pset_find_ptr(clique, cand))
422                                                 continue;
423
424                                         /* are there all necessary interferences? */
425                                         is_cand = true;
426                                         pset_foreach(clique, member) {
427                                                 if (!find_edge(edges, cand, member)) {
428                                                         is_cand = false;
429                                                         pset_break(clique);
430                                                         break;
431                                                 }
432                                         }
433
434                                         /* now we know if we have a clique extender */
435                                         if (is_cand) {
436                                                 /* first remove all covered edges */
437                                                 pset_foreach(clique, member)
438                                                         remove_edge(edges, cand, member, &n_edges);
439
440                                                 /* insert into clique */
441                                                 pset_insert_ptr(clique, cand);
442                                                 growed = true;
443                                                 break;
444                                         }
445                                 }
446                         } while (growed);
447
448                         /* now the clique is maximal. Finally add the constraint */
449                         {
450                                 int  var_idx;
451                                 int  cst_idx;
452                                 char buf[32];
453
454                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater_equal, pset_count(clique)-1);
455
456                                 pset_foreach(clique, member) {
457                                         make_affinity_var_name(buf, sizeof(buf), center, member);
458                                         var_idx = lpp_get_var_idx(ienv->lp, buf);
459                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
460                                 }
461                         }
462
463                         del_pset(clique);
464                 }
465
466                 del_set(edges);
467                 obstack_free(&ob, NULL);
468         }
469 }
470
471 static void extend_path(ilp_env_t *ienv, pdeq *path, const ir_node *irn)
472 {
473         be_ifg_t *ifg = ienv->co->cenv->ifg;
474         int i, len;
475         ir_node **curr_path;
476         affinity_node_t *aff;
477
478         /* do not walk backwards or in circles */
479         if (pdeq_contains(path, irn))
480                 return;
481
482         if (arch_irn_is_ignore(irn))
483                 return;
484
485         /* insert the new irn */
486         pdeq_putr(path, irn);
487
488         /* check for forbidden interferences */
489         len       = pdeq_len(path);
490         curr_path = ALLOCAN(ir_node*, len);
491         pdeq_copyl(path, (const void **)curr_path);
492
493         for (i=1; i<len; ++i) {
494                 if (be_ifg_connected(ifg, irn, curr_path[i]))
495                         goto end;
496         }
497
498         /* check for terminating interference */
499         if (be_ifg_connected(ifg, irn, curr_path[0])) {
500                 /* One node is not a path. */
501                 /* And a path of length 2 is covered by a clique star constraint. */
502                 if (len > 2) {
503                         /* finally build the constraint */
504                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater_equal, 1.0);
505                         for (i=1; i<len; ++i) {
506                                 char buf[32];
507                                 int  var_idx;
508
509                                 make_affinity_var_name(buf, sizeof(buf), curr_path[i-1], curr_path[i]);
510                                 var_idx = lpp_get_var_idx(ienv->lp, buf);
511                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
512                         }
513                 }
514
515                 /* this path cannot be extended anymore */
516                 goto end;
517         }
518
519         /* recursively extend the path */
520         aff = get_affinity_info(ienv->co, irn);
521         co_gs_foreach_neighb(aff, nbr) {
522                 extend_path(ienv, path, nbr->irn);
523         }
524
525 end:
526         /* remove the irn */
527         pdeq_getr(path);
528 }
529
530 /**
531  * Search a path of affinity edges, whose ends are connected
532  * by an interference edge and there are no other interference
533  * edges in between.
534  * Then at least one of these affinity edges must break.
535  */
536 static void build_path_cstr(ilp_env_t *ienv)
537 {
538         /* for each node with affinity edges */
539         co_gs_foreach_aff_node(ienv->co, aff_info) {
540                 pdeq *path = new_pdeq();
541
542                 extend_path(ienv, path, aff_info->irn);
543
544                 del_pdeq(path);
545         }
546 }
547
548 static void ilp2_build(ilp_env_t *ienv)
549 {
550         int lower_bound;
551
552         ienv->lp = lpp_new(ienv->co->name, lpp_minimize);
553         build_coloring_cstr(ienv);
554         build_interference_cstr(ienv);
555         build_affinity_cstr(ienv);
556         build_clique_star_cstr(ienv);
557         build_path_cstr(ienv);
558
559         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
560         lpp_set_bound(ienv->lp, lower_bound);
561 }
562
563 static void ilp2_apply(ilp_env_t *ienv)
564 {
565         local_env_t *lenv = (local_env_t*)ienv->env;
566         ir_graph    *irg  = ienv->co->irg;
567
568         /* first check if there was sth. to optimize */
569         if (lenv->first_x_var >= 0) {
570                 int              count = lenv->last_x_var - lenv->first_x_var + 1;
571                 double          *sol   = XMALLOCN(double, count);
572                 lpp_sol_state_t  state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
573                 int              i;
574
575                 if (state != lpp_optimal) {
576                         printf("WARNING %s: Solution state is not 'optimal': %d\n",
577                                ienv->co->name, (int)state);
578                         if (state < lpp_feasible) {
579                                 panic("Copy coalescing solution not feasible!");
580                         }
581                 }
582
583                 for (i=0; i<count; ++i) {
584                         unsigned nodenr;
585                         unsigned color;
586                         char     var_name[32];
587                         if (sol[i] <= 1-EPSILON)
588                                 continue;
589                         /* split variable name into components */
590                         lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
591
592                         if (sscanf(var_name, "x_%u_%u", &nodenr, &color) == 2) {
593                                 ir_node *irn = get_idx_irn(irg, nodenr);
594                                 set_irn_col(ienv->co->cls, irn, color);
595                         } else {
596                                 panic("This should be a x-var");
597                         }
598                 }
599
600                 xfree(sol);
601         }
602
603 #ifdef COPYOPT_STAT
604         /* TODO adapt to multiple possible ILPs */
605         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
606         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
607         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
608         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
609 #endif
610 }
611
612 /**
613  * Solves the problem using mixed integer programming
614  * @returns 1 iff solution state was optimal
615  * Uses the OU and the GRAPH data structure
616  * Dependency of the OU structure can be removed
617  */
618 static int co_solve_ilp2(copy_opt_t *co)
619 {
620         unsigned       *allocatable_colors;
621         unsigned        n_regs = arch_register_class_n_regs(co->cls);
622         lpp_sol_state_t sol_state;
623         ilp_env_t      *ienv;
624         local_env_t     my;
625
626         ASSERT_OU_AVAIL(co); //See build_clique_st
627         ASSERT_GS_AVAIL(co);
628
629         my.first_x_var = -1;
630         my.last_x_var  = -1;
631         FIRM_DBG_REGISTER(dbg, "firm.be.coilp2");
632
633         rbitset_alloca(allocatable_colors, n_regs);
634         be_set_allocatable_regs(co->irg, co->cls, allocatable_colors);
635         my.allocatable_colors = allocatable_colors;
636
637         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
638
639         sol_state = ilp_go(ienv);
640
641         free_ilp_env(ienv);
642
643         return sol_state == lpp_optimal;
644 }
645
646 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyilp2)
647 void be_init_copyilp2(void)
648 {
649         static co_algo_info copyheur = {
650                 co_solve_ilp2, 1
651         };
652
653         be_register_copyopt("ilp", &copyheur);
654 }