Added search for free colors in neighbourhood.
[libfirm] / ir / be / becopyheur.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                12.04.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6
7  * Heuristic for minimizing copies using a queue which holds 'qnodes' not yet
8  * examined. A qnode has a 'target color', nodes out of the opt unit and
9  * a 'conflict graph'. 'Conflict graph' = "Interference graph' + 'conflict edges'
10  * A 'max indep set' is determined form these. We try to color this mis using a
11  * color-exchanging mechanism. Occuring conflicts are modeled with 'conflict edges'
12  * and the qnode is reinserted in the queue. The first qnode colored without
13  * conflicts is the best one.
14  */
15 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif
18
19 #ifdef HAVE_ALLOCA_H
20 #include <alloca.h>
21 #endif
22 #ifdef HAVE_MALLOC_H
23 #include <malloc.h>
24 #endif
25
26 #include "xmalloc.h"
27 #include "becopyopt.h"
28 #include "becopystat.h"
29 #include "bitset.h"
30 #include "bearch.h"
31
32 static firm_dbg_module_t *dbg = NULL;
33
34 #define SEARCH_FREE_COLORS
35
36 #define SLOTS_PINNED_GLOBAL 256
37 #define SLOTS_CONFLICTS 8
38 #define SLOTS_CHANGED_NODES 32
39
40 #define MIN(a,b) ((a<b)?(a):(b))
41 #define list_entry_queue(lh) list_entry(lh, qnode_t, queue)
42 #define HASH_CONFLICT(c) (HASH_PTR(c.n1) ^ HASH_PTR(c.n2))
43
44 /**
45  * Modeling additional conflicts between nodes. NOT live range interference
46  */
47 typedef struct _conflict_t {
48         const ir_node *n1, *n2;
49 } conflict_t;
50
51 /**
52  * If an irn is changed, the changes first get stored in a node_stat_t,
53  * to allow undo of changes (=drop new data) in case of conflicts.
54  */
55 typedef struct _node_stat_t {
56         ir_node *irn;
57         int new_color;
58         int pinned_local :1;
59 } node_stat_t;
60
61 /**
62  * Represents a node in the optimization queue.
63  */
64 typedef struct _qnode_t {
65         struct list_head queue;         /**< chaining of unit_t->queue */
66         const unit_t *ou;                       /**< the opt unit this qnode belongs to */
67         int color;                                      /**< target color */
68         set *conflicts;                         /**< contains conflict_t's. All internal conflicts */
69         int mis_costs;                          /**< costs of nodes/copies in the mis. */
70         int mis_size;                           /**< size of the array below */
71         ir_node **mis;                          /**< the nodes of unit_t->nodes[] being part of the max independent set */
72         set *changed_nodes;                     /**< contains node_stat_t's. */
73 } qnode_t;
74
75 static pset *pinned_global;                     /**< optimized nodes should not be altered any more */
76
77 static int set_cmp_conflict_t(const void *x, const void *y, size_t size) {
78         const conflict_t *xx = x;
79         const conflict_t *yy = y;
80         return ! (xx->n1 == yy->n1 && xx->n2 == yy->n2);
81 }
82
83 /**
84  * If a local pinned conflict occurs, a new edge in the conflict graph is added.
85  * The next maximum independent set build, will regard it.
86  */
87 static INLINE void qnode_add_conflict(const qnode_t *qn, const ir_node *n1, const ir_node *n2) {
88         conflict_t c;
89         DBG((dbg, LEVEL_4, "\t      %+F -- %+F\n", n1, n2));
90
91         if ((int)n1 < (int)n2) {
92                 c.n1 = n1;
93                 c.n2 = n2;
94         } else {
95                 c.n1 = n2;
96                 c.n2 = n1;
97         }
98         set_insert(qn->conflicts, &c, sizeof(c), HASH_CONFLICT(c));
99 }
100
101 /**
102  * Checks if two nodes are in a conflict.
103  */
104 static INLINE int qnode_are_conflicting(const qnode_t *qn, const ir_node *n1, const ir_node *n2) {
105         conflict_t c;
106         /* search for live range interference */
107         if (n1!=n2 && nodes_interfere(qn->ou->co->chordal_env, n1, n2))
108                 return 1;
109         /* search for recoloring conflicts */
110         if ((int)n1 < (int)n2) {
111                 c.n1 = n1;
112                 c.n2 = n2;
113         } else {
114                 c.n1 = n2;
115                 c.n2 = n1;
116         }
117         return (int) set_find(qn->conflicts, &c, sizeof(c), HASH_CONFLICT(c));
118 }
119
120 static int set_cmp_node_stat_t(const void *x, const void *y, size_t size) {
121         return ((node_stat_t *)x)->irn != ((node_stat_t *)y)->irn;
122 }
123
124 /**
125  * Finds a node status entry of a node if existent. Otherwise return NULL
126  */
127 static INLINE node_stat_t *qnode_find_node(const qnode_t *qn, ir_node *irn) {
128         node_stat_t find;
129         find.irn = irn;
130         return set_find(qn->changed_nodes, &find, sizeof(find), HASH_PTR(irn));
131 }
132
133 /**
134  * Finds a node status entry of a node if existent. Otherwise it will return
135  * an initialized new entry for this node.
136  */
137 static INLINE node_stat_t *qnode_find_or_insert_node(const qnode_t *qn, ir_node *irn) {
138         node_stat_t find;
139         find.irn = irn;
140         find.new_color = NO_COLOR;
141         find.pinned_local = 0;
142         return set_insert(qn->changed_nodes, &find, sizeof(find), HASH_PTR(irn));
143 }
144
145 /**
146  * Returns the virtual color of a node if set before, else returns the real color.
147  */
148 static INLINE int qnode_get_new_color(const qnode_t *qn, ir_node *irn) {
149         node_stat_t *found = qnode_find_node(qn, irn);
150         if (found)
151                 return found->new_color;
152         else
153                 return get_irn_col(qn->ou->co, irn);
154 }
155
156 /**
157  * Sets the virtual color of a node.
158  */
159 static INLINE void qnode_set_new_color(const qnode_t *qn, ir_node *irn, int color) {
160         node_stat_t *found = qnode_find_or_insert_node(qn, irn);
161         found->new_color = color;
162         DBG((dbg, LEVEL_3, "\t      col(%+F) := %d\n", irn, color));
163 }
164
165 /**
166  * Checks if a node is local pinned. A node is local pinned, iff it belongs
167  * to the same optimization unit and has been optimized before the current
168  * processed node.
169  */
170 static INLINE int qnode_is_pinned_local(const qnode_t *qn, ir_node *irn) {
171         node_stat_t *found = qnode_find_node(qn, irn);
172         if (found)
173                 return found->pinned_local;
174         else
175                 return 0;
176 }
177
178 /**
179  * Local-pins a node, so optimizations of further nodes of the same opt unit
180  * can handle situations in which a color change would undo prior optimizations.
181  */
182 static INLINE void qnode_pin_local(const qnode_t *qn, ir_node *irn) {
183         node_stat_t *found = qnode_find_or_insert_node(qn, irn);
184         found->pinned_local = 1;
185         if (found->new_color == NO_COLOR)
186                 found->new_color = get_irn_col(qn->ou->co, irn);
187 }
188
189
190 /**
191  * Possible return values of qnode_color_irn()
192  */
193 #define CHANGE_SAVE NULL
194 #define CHANGE_IMPOSSIBLE (ir_node *)1
195 #define is_conflicting_node(n) (((int)n) > 1)
196
197 /**
198  * Performs virtual re-coloring of node @p n to color @p col. Virtual colors of
199  * other nodes are changed too, as required to preserve correctness. Function is
200  * aware of local and global pinning. Recursive.
201  *
202  * If irn == trigger the color @p col must be used. (the first recoloring)
203  * If irn != trigger an arbitrary free color may be used. If no color is free, @p col is used.
204  *
205  * @param  irn     The node to set the color for
206  * @param  col     The color to set
207  * @param  trigger The irn that caused the wish to change the color of the irn
208  *                 External callers must call with trigger = irn
209  *
210  * @return CHANGE_SAVE iff setting the color is possible, with all transitive effects.
211  *         CHANGE_IMPOSSIBLE iff conflicts with reg-constraintsis occured.
212  *         Else the first conflicting ir_node encountered is returned.
213  *
214  */
215 static ir_node *qnode_color_irn(const qnode_t *qn, ir_node *irn, int col, const ir_node *trigger) {
216         const be_chordal_env_t *chordal_env = qn->ou->co->chordal_env;
217         const arch_register_class_t *cls = chordal_env->cls;
218         const arch_env_t *arch_env = chordal_env->main_env->arch_env;
219         int irn_col = qnode_get_new_color(qn, irn);
220         ir_node *sub_res, *curr;
221         be_ifg_t *ifg = chordal_env->ifg;
222         void *iter = be_ifg_neighbours_iter_alloca(ifg);
223
224
225         DBG((dbg, LEVEL_3, "\t    %+F \tcaused col(%+F) \t%2d --> %2d\n", trigger, irn, irn_col, col));
226
227         /* If the target color is already set do nothing */
228         if (irn_col == col) {
229                 DBG((dbg, LEVEL_3, "\t      %+F same color\n", irn));
230                 return CHANGE_SAVE;
231         }
232
233         /* If the irn is pinned, changing color is impossible */
234         if (pset_find_ptr(pinned_global, irn) || qnode_is_pinned_local(qn, irn)) {
235                 DBG((dbg, LEVEL_3, "\t      %+F conflicting\n", irn));
236                 return irn;
237         }
238
239 #ifdef SEARCH_FREE_COLORS
240         /* If we resolve conflicts (recursive calls) we can use any unused color.
241          * In case of the first call @p col must be used.
242          */
243         if (irn != trigger) {
244                 bitset_t *free_cols = bitset_alloca(cls->n_regs);
245                 arch_register_req_t req;
246                 ir_node *curr;
247                 int free_col;
248
249                 /* Get all possible colors */
250                 arch_put_non_ignore_regs(arch_env, cls, free_cols);
251
252                 /* Exclude colors not assignable to the irn */
253                 arch_get_register_req(arch_env, &req, irn, -1);
254                 if (arch_register_req_is(&req, limited)) {
255                         bitset_t *limited = bitset_alloca(cls->n_regs);
256                         req.limited(req.limited_env, limited);
257                         bitset_and(free_cols, limited);
258                 }
259
260                 /* Exclude the color of the irn, because it must _change_ its color */
261                 bitset_clear(free_cols, irn_col);
262
263                 /* Exclude all colors used by adjacent nodes */
264                 be_ifg_foreach_neighbour(ifg, iter, irn, curr)
265                         bitset_clear(free_cols, qnode_get_new_color(qn, curr));
266
267                 free_col = bitset_next_set(free_cols, 0);
268
269                 if (free_col != -1) {
270                         qnode_set_new_color(qn, irn, free_col);
271                         return CHANGE_SAVE;
272                 }
273         }
274 #endif /* SEARCH_FREE_COLORS */
275
276         /* If target color is not allocatable changing color is impossible */
277         if (!arch_reg_is_allocatable(arch_env, irn, -1, arch_register_for_index(cls, col))) {
278                 DBG((dbg, LEVEL_3, "\t      %+F impossible\n", irn));
279                 return CHANGE_IMPOSSIBLE;
280         }
281
282         /*
283          * If we arrive here changing color may be possible, but there may be conflicts.
284          * Try to color all conflicting nodes 'curr' with the color of the irn itself.
285          */
286         be_ifg_foreach_neighbour(ifg, iter, irn, curr) {
287                 DBG((dbg, LEVEL_3, "\t      Confl %+F(%d)\n", curr, qnode_get_new_color(qn, curr)));
288                 if (qnode_get_new_color(qn, curr) == col && curr != trigger) {
289                         sub_res = qnode_color_irn(qn, curr, irn_col, irn);
290                         if (sub_res != CHANGE_SAVE) {
291                                 be_ifg_neighbours_break(ifg, iter);
292                                 return sub_res;
293                         }
294                 }
295         }
296
297         /*
298          * If we arrive here, all conflicts were resolved.
299          * So it is save to change this irn
300          */
301         qnode_set_new_color(qn, irn, col);
302         return CHANGE_SAVE;
303 }
304
305
306 /**
307  * Tries to set the colors for all members of this queue node;
308  * to the target color qn->color
309  * @returns 1 iff all members colors could be set
310  *          0 else
311  */
312 static int qnode_try_color(const qnode_t *qn) {
313         int i;
314         for (i=0; i<qn->mis_size; ++i) {
315                 ir_node *test_node, *confl_node;
316
317                 test_node = qn->mis[i];
318                 DBG((dbg, LEVEL_3, "\t    Testing %+F\n", test_node));
319                 confl_node = qnode_color_irn(qn, test_node, qn->color, test_node);
320
321                 if (confl_node == CHANGE_SAVE) {
322                         DBG((dbg, LEVEL_3, "\t    Save --> pin local\n"));
323                         qnode_pin_local(qn, test_node);
324                 } else if (confl_node == CHANGE_IMPOSSIBLE) {
325                         DBG((dbg, LEVEL_3, "\t    Impossible --> remove from qnode\n"));
326                         qnode_add_conflict(qn, test_node, test_node);
327                 } else {
328                         if (qnode_is_pinned_local(qn, confl_node)) {
329                                 /* changing test_node would change back a node of current ou */
330                                 if (confl_node == qn->ou->nodes[0]) {
331                                         /* Adding a conflict edge between testnode and conflnode
332                                          * would introduce a root -- arg interference.
333                                          * So remove the arg of the qn */
334                                         DBG((dbg, LEVEL_3, "\t    Conflicting local with phi --> remove from qnode\n"));
335                                         qnode_add_conflict(qn, test_node, test_node);
336                                 } else {
337                                         DBG((dbg, LEVEL_3, "\t    Conflicting local --> add conflict\n"));
338                                         qnode_add_conflict(qn, confl_node, test_node);
339                                 }
340                         }
341                         if (pset_find_ptr(pinned_global, confl_node)) {
342                                 /* changing test_node would change back a node of a prior ou */
343                                 DBG((dbg, LEVEL_3, "\t    Conflicting global --> remove from qnode\n"));
344                                 qnode_add_conflict(qn, test_node, test_node);
345                         }
346                 }
347
348                 if (confl_node != CHANGE_SAVE)
349                         return 0;
350         }
351         return 1;
352 }
353
354 /**
355  * Determines a maximum weighted independent set with respect to
356  * the interference and conflict edges of all nodes in a qnode.
357  */
358 static INLINE void qnode_max_ind_set(qnode_t *qn, const unit_t *ou) {
359         ir_node **safe, **unsafe;
360         int i, o, safe_count, safe_costs, unsafe_count, *unsafe_costs;
361         bitset_t *curr, *best;
362         int max, next, pos, curr_weight, best_weight = 0;
363
364         /* assign the nodes into two groups.
365          * safe: node has no interference, hence it is in every max stable set.
366          * unsafe: node has an interference
367          */
368         safe = alloca((ou->node_count-1) * sizeof(*safe));
369         safe_costs = 0;
370         safe_count = 0;
371         unsafe = alloca((ou->node_count-1) * sizeof(*unsafe));
372         unsafe_costs = alloca((ou->node_count-1) * sizeof(*unsafe_costs));
373         unsafe_count = 0;
374         for(i=1; i<ou->node_count; ++i) {
375                 int is_safe = 1;
376                 for(o=1; o<ou->node_count; ++o) {
377                         if (qnode_are_conflicting(qn, ou->nodes[i], ou->nodes[o])) {
378                                 if (i!=o) {
379                                         unsafe_costs[unsafe_count] = ou->costs[i];
380                                         unsafe[unsafe_count] = ou->nodes[i];
381                                         ++unsafe_count;
382                                 }
383                                 is_safe = 0;
384                                 break;
385                         }
386                 }
387                 if (is_safe) {
388                         safe_costs += ou->costs[i];
389                         safe[safe_count++] = ou->nodes[i];
390                 }
391         }
392
393
394
395         /* now compute the best set out of the unsafe nodes*/
396         best = bitset_alloca(unsafe_count);
397
398         if (unsafe_count > MIS_HEUR_TRIGGER) {
399                 /* Heuristic: Greedy trial and error form index 0 to unsafe_count-1 */
400                 for (i=0; i<unsafe_count; ++i) {
401                         bitset_set(best, i);
402                         /* check if it is a stable set */
403                         for (o=bitset_next_set(best, 0); o!=-1 && o<=i; o=bitset_next_set(best, o+1))
404                                 if (qnode_are_conflicting(qn, unsafe[i], unsafe[o])) {
405                                         bitset_clear(best, i); /* clear the bit and try next one */
406                                         break;
407                                 }
408                 }
409                 /* compute the weight */
410                 bitset_foreach(best, pos)
411                         best_weight += unsafe_costs[pos];
412         } else {
413                 /* Exact Algorithm: Brute force */
414                 curr = bitset_alloca(unsafe_count);
415                 bitset_set_all(curr);
416                 while ((max = bitset_popcnt(curr)) != 0) {
417                         /* check if curr is a stable set */
418                         for (i=bitset_next_set(curr, 0); i!=-1; i=bitset_next_set(curr, i+1))
419                                 for (o=bitset_next_set(curr, i); o!=-1; o=bitset_next_set(curr, o+1)) /* !!!!! difference to ou_max_ind_set_costs(): NOT (curr, i+1) */
420                                                 if (qnode_are_conflicting(qn, unsafe[i], unsafe[o]))
421                                                         goto no_stable_set;
422
423                         /* if we arrive here, we have a stable set */
424                         /* compute the weigth of the stable set*/
425                         curr_weight = 0;
426                         bitset_foreach(curr, pos)
427                                 curr_weight += unsafe_costs[pos];
428
429                         /* any better ? */
430                         if (curr_weight > best_weight) {
431                                 best_weight = curr_weight;
432                                 bitset_copy(best, curr);
433                         }
434
435 no_stable_set:
436                         bitset_minus1(curr);
437                 }
438         }
439
440         /* transfer the best set into the qn */
441         qn->mis_size = 1+safe_count+bitset_popcnt(best);
442         qn->mis_costs = safe_costs+best_weight;
443         qn->mis[0] = ou->nodes[0]; /* the root is always in a max stable set */
444         next = 1;
445         for (i=0; i<safe_count; ++i)
446                 qn->mis[next++] = safe[i];
447         bitset_foreach(best, pos)
448                 qn->mis[next++] = unsafe[pos];
449 }
450
451 /**
452  * Creates a new qnode
453  */
454 static INLINE qnode_t *new_qnode(const unit_t *ou, int color) {
455         qnode_t *qn = xmalloc(sizeof(*qn));
456         qn->ou = ou;
457         qn->color = color;
458         qn->mis = malloc(ou->node_count * sizeof(*qn->mis));
459         qn->conflicts = new_set(set_cmp_conflict_t, SLOTS_CONFLICTS);
460         qn->changed_nodes = new_set(set_cmp_node_stat_t, SLOTS_CHANGED_NODES);
461         return qn;
462 }
463
464 /**
465  * Frees space used by a queue node
466  */
467 static INLINE void free_qnode(qnode_t *qn) {
468         del_set(qn->conflicts);
469         del_set(qn->changed_nodes);
470         xfree(qn->mis);
471         xfree(qn);
472 }
473
474 /**
475  * Inserts a qnode in the sorted queue of the optimization unit. Queue is
476  * ordered by field 'size' (the size of the mis) in decreasing order.
477  */
478 static INLINE void ou_insert_qnode(unit_t *ou, qnode_t *qn) {
479         struct list_head *lh;
480
481         if (qnode_are_conflicting(qn, ou->nodes[0], ou->nodes[0])) {
482                 /* root node is not in qnode */
483                 free_qnode(qn);
484                 return;
485         }
486
487         qnode_max_ind_set(qn, ou);
488         /* do the insertion */
489         DBG((dbg, LEVEL_4, "\t  Insert qnode color %d with cost %d\n", qn->color, qn->mis_costs));
490         lh = &ou->queue;
491         while (lh->next != &ou->queue) {
492                 qnode_t *curr = list_entry_queue(lh->next);
493                 if (curr->mis_costs <= qn->mis_costs)
494                         break;
495                 lh = lh->next;
496         }
497         list_add(&qn->queue, lh);
498 }
499
500 /**
501  * Tries to re-allocate colors of nodes in this opt unit, to achieve lower
502  * costs of copy instructions placed during SSA-destruction and lowering.
503  * Works only for opt units with exactly 1 root node, which is the
504  * case for approximately 80% of all phi classes and 100% of register constrained
505  * nodes. (All other phi classes are reduced to this case.)
506  */
507 static void ou_optimize(unit_t *ou) {
508         int i;
509         qnode_t *curr = NULL, *tmp;
510         arch_env_t *aenv = get_arch_env(ou->co);
511         const arch_register_class_t *cls = ou->co->chordal_env->cls;
512         bitset_t *pos_regs = bitset_alloca(cls->n_regs);
513         bitset_t *ign_regs = bitset_alloca(cls->n_regs);
514
515         DBG((dbg, LEVEL_1, "\tOptimizing unit:\n"));
516         for (i=0; i<ou->node_count; ++i)
517                 DBG((dbg, LEVEL_1, "\t %+F\n", ou->nodes[i]));
518
519         /* init queue */
520         INIT_LIST_HEAD(&ou->queue);
521
522         arch_get_allocatable_regs(aenv, ou->nodes[0], -1, pos_regs);
523
524         /* exclude ingore colors */
525         arch_put_non_ignore_regs(aenv, cls, ign_regs);
526         bitset_and(pos_regs, ign_regs);
527
528         /* create new qnode */
529         bitset_foreach(pos_regs, i)
530                 ou_insert_qnode(ou, new_qnode(ou, i));
531
532         /* search best */
533         while (!list_empty(&ou->queue)) {
534                 /* get head of queue */
535                 curr = list_entry_queue(ou->queue.next);
536                 list_del(&curr->queue);
537                 DBG((dbg, LEVEL_2, "\t  Examine qnode color %d with cost %d\n", curr->color, curr->mis_costs));
538
539                 /* try */
540                 if (qnode_try_color(curr))
541                         break;
542
543                 /* no success, so re-insert */
544                 del_set(curr->changed_nodes);
545                 curr->changed_nodes = new_set(set_cmp_node_stat_t, SLOTS_CHANGED_NODES);
546                 ou_insert_qnode(ou, curr);
547         }
548
549         /* apply the best found qnode */
550         if (curr->mis_size >= 2) {
551                 node_stat_t *ns;
552                 int root_col = qnode_get_new_color(curr, ou->nodes[0]);
553                 DBG((dbg, LEVEL_1, "\t  Best color: %d  Costs: %d << %d << %d\n", curr->color, ou->min_nodes_costs, ou->all_nodes_costs - curr->mis_costs, ou->all_nodes_costs));
554                 /* globally pin root and all args which have the same color */
555                 pset_insert_ptr(pinned_global, ou->nodes[0]);
556                 for (i=1; i<ou->node_count; ++i) {
557                         ir_node *irn = ou->nodes[i];
558                         int nc = qnode_get_new_color(curr, irn);
559                         if (nc != NO_COLOR && nc == root_col)
560                                 pset_insert_ptr(pinned_global, irn);
561                 }
562
563                 /* set color of all changed nodes */
564                 for (ns = set_first(curr->changed_nodes); ns; ns = set_next(curr->changed_nodes)) {
565                         /* NO_COLOR is possible, if we had an undo */
566                         if (ns->new_color != NO_COLOR) {
567                                 DBG((dbg, LEVEL_1, "\t    color(%+F) := %d\n", ns->irn, ns->new_color));
568                                 set_irn_col(ou->co, ns->irn, ns->new_color);
569                         }
570                 }
571         }
572
573         /* free best qnode (curr) and queue */
574         free_qnode(curr);
575         list_for_each_entry_safe(qnode_t, curr, tmp, &ou->queue, queue)
576                 free_qnode(curr);
577 }
578
579 void co_heur_opt(copy_opt_t *co) {
580         unit_t *curr;
581         dbg = firm_dbg_register("ir.be.copyoptheur");
582
583         pinned_global = pset_new_ptr(SLOTS_PINNED_GLOBAL);
584         list_for_each_entry(unit_t, curr, &co->units, units)
585                 if (curr->node_count > 1)
586                         ou_optimize(curr);
587
588         del_pset(pinned_global);
589 }