fix for new requirements generator
[libfirm] / ir / be / bespillmorgan.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       Morgans spill algorithm.
23  * @author      Matthias Braun
24  * @date        05.05.2006
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "irgwalk.h"
32 #include "irloop_t.h"
33 #include "irgraph_t.h"
34 #include "irprintf.h"
35 #include "obst.h"
36
37 #include "bespillmorgan.h"
38 #include "bechordal_t.h"
39 #include "bespill.h"
40 #include "belive_t.h"
41 #include "beabi.h"
42 #include "bespillbelady.h"
43 #include "beverify.h"
44 #include "benodesets.h"
45 #include "bespilloptions.h"
46 #include "besched.h"
47 #include "beutil.h"
48 #include "bemodule.h"
49 #include "beirg_t.h"
50
51 #define DBG_LIVE                1
52 #define DBG_LOOPANA             2
53 #define DBG_PRESSURE    4
54 #define DBG_SPILLS      8
55 #define DBG_CHOOSE              16
56 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
57
58 typedef struct morgan_env {
59         const arch_env_t *arch;
60         const arch_register_class_t *cls;
61         ir_graph *irg;
62         be_lv_t *lv;
63         struct obstack obst;
64         /** maximum safe register pressure */
65         int registers_available;
66
67         spill_env_t *senv;
68
69         set *loop_attr_set;
70         set *block_attr_set;
71 } morgan_env_t;
72
73 typedef struct loop_edge {
74         ir_node *block;
75         int pos;
76 } loop_edge_t;
77
78 typedef struct loop_attr {
79         const ir_loop *loop;
80         set *out_edges;
81         set *in_edges;
82         /** The set of all values that are live in the loop but not used in the loop */
83         bitset_t *livethrough_unused;
84 } loop_attr_t;
85
86 typedef struct morgan_block_attr {
87         const ir_node *block;
88         /** set of all values that are live in the block but not used in the block */
89         bitset_t *livethrough_unused;
90 } block_attr_t;
91
92 //---------------------------------------------------------------------------
93
94 static int loop_edge_cmp(const void* p1, const void* p2, size_t size) {
95         loop_edge_t *e1 = (loop_edge_t*) p1;
96         loop_edge_t *e2 = (loop_edge_t*) p2;
97         (void) size;
98
99         return e1->block != e2->block || e1->pos != e2->pos;
100 }
101
102 static int loop_attr_cmp(const void *e1, const void *e2, size_t size) {
103         loop_attr_t *la1 = (loop_attr_t*) e1;
104         loop_attr_t *la2 = (loop_attr_t*) e2;
105         (void) size;
106
107         return la1->loop != la2->loop;
108 }
109
110 static int block_attr_cmp(const void *e1, const void *e2, size_t size) {
111         block_attr_t *b1 = (block_attr_t*) e1;
112         block_attr_t *b2 = (block_attr_t*) e2;
113         (void) size;
114
115         return b1->block != b2->block;
116 }
117
118 static INLINE int loop_attr_hash(const loop_attr_t *a) {
119 #ifdef DEBUG_libfirm
120         return a->loop->loop_nr;
121 #else
122         return HASH_PTR(a->loop);
123 #endif
124 }
125
126 static INLINE int block_attr_hash(const block_attr_t *b) {
127         return nodeset_hash(b->block);
128 }
129
130 static INLINE int loop_edge_hash(const loop_edge_t *e) {
131         return nodeset_hash(e->block) ^ (e->pos * 31);
132 }
133
134 static INLINE loop_attr_t *get_loop_attr(morgan_env_t *env, const ir_loop *loop) {
135         loop_attr_t l_attr, *res;
136         int hash;
137         l_attr.loop = loop;
138
139         hash = loop_attr_hash(&l_attr);
140         res = set_find(env->loop_attr_set, &l_attr, sizeof(l_attr), hash);
141
142         // create new loop_attr if none exists yet
143         if (res == NULL) {
144                 l_attr.out_edges = new_set(loop_edge_cmp, 1);
145                 l_attr.in_edges = new_set(loop_edge_cmp, 1);
146                 l_attr.livethrough_unused = bitset_obstack_alloc(&env->obst, get_irg_last_idx(env->irg));
147                 res = set_insert(env->loop_attr_set, &l_attr, sizeof(l_attr), hash);
148         }
149
150         return res;
151 }
152
153 static INLINE block_attr_t *get_block_attr(morgan_env_t *env, const ir_node *block) {
154         block_attr_t b_attr, *res;
155         int hash;
156         b_attr.block = block;
157
158         hash = block_attr_hash(&b_attr);
159         res = set_find(env->block_attr_set, &b_attr, sizeof(b_attr), hash);
160
161         if(res == NULL) {
162                 b_attr.livethrough_unused = NULL;
163                 res = set_insert(env->block_attr_set, &b_attr, sizeof(b_attr), hash);
164         }
165
166         return res;
167 }
168
169 //---------------------------------------------------------------------------
170
171 static INLINE int consider_for_spilling(const arch_env_t *env, const arch_register_class_t *cls, const ir_node *node) {
172         if(!arch_irn_has_reg_class(env, node, -1, cls))
173                 return 0;
174
175         return !(arch_irn_get_flags(env, node) & (arch_irn_flags_ignore | arch_irn_flags_dont_spill));
176 }
177
178 /**
179  * Determine edges going out of a loop (= edges that go to a block that is not
180  * inside the loop or one of its subloops)
181  */
182 static INLINE void construct_loop_edges(ir_node *block, void *data) {
183         morgan_env_t *env = data;
184         int n_cfgpreds = get_Block_n_cfgpreds(block);
185         int i;
186         ir_loop* loop = get_irn_loop(block);
187         DBG((dbg, DBG_LOOPANA, "Loop for %+F: %d (depth %d)\n", block, loop->loop_nr, loop->depth));
188
189         for(i = 0; i < n_cfgpreds; ++i) {
190                 loop_edge_t edge;
191                 int hash;
192                 ir_node* cfgpred = get_Block_cfgpred(block, i);
193                 ir_node* cfgpred_block = get_nodes_block(cfgpred);
194                 ir_loop* cfgpred_loop = get_irn_loop(cfgpred_block);
195
196                 if(cfgpred_loop == loop)
197                         continue;
198
199                 assert(get_loop_depth(cfgpred_loop) != get_loop_depth(loop));
200
201                 edge.block = block;
202                 edge.pos = i;
203                 hash = loop_edge_hash(&edge);
204
205                 // edge out of a loop?
206                 if(get_loop_depth(cfgpred_loop) > get_loop_depth(loop)) {
207                         ir_loop *l;
208
209                         DBG((dbg, DBG_LOOPANA, "Loop out edge from %+F (loop %d) to %+F (loop %d)\n", block, get_loop_loop_nr(loop),
210                              cfgpred_block, get_loop_loop_nr(cfgpred_loop)));
211
212                         /* this might be a jump out of multiple loops, so add this to all
213                      * needed outedge sets */
214                         l = cfgpred_loop;
215                         do {
216                                 loop_attr_t *l_attr = get_loop_attr(env, l);
217                                 set_insert(l_attr->out_edges, &edge, sizeof(edge), hash);
218
219                                 l = get_loop_outer_loop(l);
220                                 assert(l != NULL);
221                         } while(l != loop);
222                 } else {
223                         ir_loop *l;
224
225                         // edge into a loop
226                         DBG((dbg, DBG_LOOPANA, "Loop in edge from %+F (loop %d) to %+F (loop %d)\n", block, get_loop_loop_nr(loop),
227                              cfgpred_block, get_loop_loop_nr(cfgpred_loop)));
228
229                         l = loop;
230                         do {
231                                 loop_attr_t *l_attr = get_loop_attr(env, l);
232                                 set_insert(l_attr->in_edges, &edge, sizeof(edge), hash);
233
234                                 l = get_loop_outer_loop(l);
235                         } while(l != cfgpred_loop);
236                 }
237         }
238 }
239
240 static void free_loop_edges(morgan_env_t *env) {
241         loop_attr_t *l_attr;
242
243         for(l_attr = set_first(env->loop_attr_set); l_attr != NULL; l_attr = set_next(env->loop_attr_set)) {
244                 del_set(l_attr->out_edges);
245                 del_set(l_attr->in_edges);
246         }
247 }
248
249 #if 0
250 /**
251  * Debugging help, shows all nodes in a (node-)bitset
252  */
253 static void show_nodebitset(ir_graph* irg, const bitset_t* bitset) {
254         int i;
255
256         bitset_foreach(bitset, i) {
257                 ir_node* node = get_idx_irn(irg, i);
258                 ir_fprintf(stderr, " %+F", node);
259         }
260         fprintf(stderr, "\n");
261 }
262 #endif
263
264 static INLINE void init_livethrough_unuseds(block_attr_t *attr, morgan_env_t *env) {
265         const ir_node *block;
266         int i;
267         const be_lv_t *lv = env->lv;
268
269         if(attr->livethrough_unused != NULL)
270                 return;
271
272         block = attr->block;
273
274         attr->livethrough_unused = bitset_obstack_alloc(&env->obst, get_irg_last_idx(env->irg));
275
276         // copy all live-outs into the livethrough_unused set
277         be_lv_foreach(lv, block, be_lv_state_in | be_lv_state_out, i) {
278                 ir_node *irn = be_lv_get_irn(lv, block, i);
279                 int node_idx;
280
281                 if(!consider_for_spilling(env->arch, env->cls, irn))
282                         continue;
283
284                 node_idx = get_irn_idx(irn);
285                 bitset_set(attr->livethrough_unused, node_idx);
286         }
287 }
288
289 /**
290  * Construct the livethrough unused set for a block
291  */
292 static void construct_block_livethrough_unused(ir_node *block, void *data) {
293         morgan_env_t* env = data;
294         block_attr_t *block_attr = get_block_attr(env, block);
295         ir_node *node;
296         int n_cfgpreds;
297         block_attr_t **pred_attrs = NULL;
298         int i;
299
300         init_livethrough_unuseds(block_attr, env);
301
302         DBG((dbg, DBG_LIVE, "Processing block %d\n", get_irn_node_nr(block)));
303
304         n_cfgpreds = get_Block_n_cfgpreds(block);
305         if(n_cfgpreds > 1) {
306                 pred_attrs = alloca(sizeof(pred_attrs[0]) * n_cfgpreds);
307                 for(i = 0; i < n_cfgpreds; ++i) {
308                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
309                         pred_attrs[i] = get_block_attr(env, pred_block);
310                         init_livethrough_unuseds(pred_attrs[i], env);
311                 }
312         }
313
314         /*
315          * All values that are used within the block are not unused (and therefore not
316          * livethrough_unused)
317          */
318         sched_foreach(block, node) {
319                 int i, arity;
320
321                 // phis are really uses in the pred block
322                 if(is_Phi(node)) {
323                         int j;
324                         for(j = 0; j < n_cfgpreds; ++j) {
325                                 ir_node *used_value = get_Phi_pred(node, j);
326                                 int idx = get_irn_idx(used_value);
327                                 block_attr_t *pred_attr = pred_attrs[j];
328
329                                 bitset_clear(pred_attr->livethrough_unused, idx);
330                         }
331                 } else {
332                         // mark all used values as used
333                         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
334                                 int idx = get_irn_idx(get_irn_n(node, i));
335                                 bitset_clear(block_attr->livethrough_unused, idx);
336                         }
337                 }
338         }
339 }
340
341 /**
342  * Construct the livethrough unused set for a loop (and all its subloops+blocks)
343  */
344 static bitset_t *construct_loop_livethrough_unused(morgan_env_t *env, const ir_loop *loop) {
345         int i;
346         loop_attr_t* loop_attr = get_loop_attr(env, loop);
347
348         DBG((dbg, DBG_LIVE, "Processing Loop %d\n", loop->loop_nr));
349         assert(get_loop_n_elements(loop) > 0);
350         for(i = 0; i < get_loop_n_elements(loop); ++i) {
351                 loop_element elem = get_loop_element(loop, i);
352                 switch (*elem.kind) {
353                 case k_ir_node: {
354                         ir_node *block = elem.node;
355                         block_attr_t *block_attr = get_block_attr(env, block);
356                         bitset_t *livethrough_block_unused = block_attr->livethrough_unused;
357
358                         assert(is_Block(elem.node));
359                         assert(livethrough_block_unused != NULL);
360
361                         if(i == 0) {
362                                 bitset_copy(loop_attr->livethrough_unused, livethrough_block_unused);
363                         } else {
364                                 bitset_and(loop_attr->livethrough_unused, livethrough_block_unused);
365                         }
366                         break;
367                 }
368                 case k_ir_loop: {
369                         bitset_t *livethrough_son_unused;
370
371                         livethrough_son_unused = construct_loop_livethrough_unused(env, elem.son);
372                         if(i == 0) {
373                                 bitset_copy(loop_attr->livethrough_unused, livethrough_son_unused);
374                         } else {
375                                 bitset_and(loop_attr->livethrough_unused, livethrough_son_unused);
376                         }
377                         break;
378                 }
379             default:
380                         assert(0);
381                         break;
382                 }
383     }
384         DBG((dbg, DBG_LIVE, "Done with loop %d\n", loop->loop_nr));
385
386         // remove all unused livethroughs that are remembered for this loop from child loops and blocks
387         for(i = 0; i < get_loop_n_elements(loop); ++i) {
388                 const loop_element elem = get_loop_element(loop, i);
389
390                 if(*elem.kind == k_ir_loop) {
391                         loop_attr_t *son_attr = get_loop_attr(env, elem.son);
392                         bitset_andnot(son_attr->livethrough_unused, loop_attr->livethrough_unused);
393
394                         DBG((dbg, DBG_LIVE, "Livethroughs for loop %d:\n", loop->loop_nr));
395                 } else if(*elem.kind == k_ir_node) {
396                         block_attr_t *block_attr = get_block_attr(env, elem.node);
397                         bitset_andnot(block_attr->livethrough_unused, loop_attr->livethrough_unused);
398
399                         DBG((dbg, DBG_LIVE, "Livethroughs for block %+F\n", elem.node));
400                 } else {
401                         assert(0);
402                 }
403         }
404
405         return loop_attr->livethrough_unused;
406 }
407
408 /*---------------------------------------------------------------------------*/
409
410 typedef struct _spillcandidate_t {
411         ir_node *node;
412         int cost;
413 } spillcandidate_t;
414
415 static int compare_spillcandidates(const void *d1, const void *d2) {
416         const spillcandidate_t *cand1 = d1;
417         const spillcandidate_t *cand2 = d2;
418
419         return cand1->cost - cand2->cost;
420 }
421
422 static void spill_values(morgan_env_t *env, const loop_attr_t *loop_attr, int spills) {
423         const bitset_t *cand_bitset = loop_attr->livethrough_unused;
424         int candidatecount = bitset_popcnt(cand_bitset);
425         spillcandidate_t *candidates;
426         bitset_pos_t idx;
427         int i, c;
428         loop_edge_t *edge;
429
430         assert(spills <= candidatecount);
431
432         candidates = alloca(sizeof(candidates[0]) * candidatecount);
433
434         DBG((dbg, DBG_CHOOSE, "Candidates for loop %d\n", get_loop_loop_nr(loop_attr->loop)));
435         // build candidiatelist
436         c = 0;
437         bitset_foreach(cand_bitset, idx) {
438                 ir_node *node = get_idx_irn(env->irg, idx);
439                 candidates[c].node = node;
440                 candidates[c].cost = 0;
441
442                 for(edge = set_first(loop_attr->out_edges); edge != NULL; edge = set_next(loop_attr->out_edges)) {
443                         candidates[c].cost += be_get_reload_costs_on_edge(env->senv, node, edge->block, edge->pos);
444                 }
445                 DBG((dbg, DBG_CHOOSE, "%+F has costs %d\n", node, candidates[c].cost));
446
447                 c++;
448         }
449         assert(c == candidatecount);
450
451         // sort list
452         qsort(candidates, candidatecount, sizeof(candidates[0]), compare_spillcandidates);
453
454         // spill values
455         for(i = 0; i < spills; ++i) {
456                 ir_node *to_spill = candidates[i].node;
457                 DBG((dbg, DBG_CHOOSE, "Spilling %+F ", to_spill));
458
459                 for(edge = set_first(loop_attr->out_edges); edge != NULL; edge = set_next(loop_attr->out_edges)) {
460                         be_add_reload_on_edge(env->senv, to_spill, edge->block, edge->pos, env->cls, 1);
461                 }
462         }
463 }
464
465 static int reduce_register_pressure_in_block(morgan_env_t *env, const ir_node* block, int loop_unused_spills_possible) {
466         ir_node *node;
467         int max_pressure;
468         int loop_unused_spills_needed;
469         ir_nodeset_t live_nodes;
470         const be_lv_t *lv = env->lv;
471
472         ir_nodeset_init(&live_nodes);
473
474         be_liveness_end_of_block(lv, env->arch, env->cls, block, &live_nodes);
475         max_pressure = ir_nodeset_size(&live_nodes);
476
477         DBG((dbg, DBG_LIVE, "Reduce pressure to %d In Block %+F:\n", env->registers_available, block));
478
479         /**
480          * Determine register pressure in block
481          */
482         sched_foreach_reverse(block, node) {
483                 int pressure;
484
485                 if(is_Phi(node))
486                         break;
487
488                 be_liveness_transfer(env->arch, env->cls, node, &live_nodes);
489                 pressure = ir_nodeset_size(&live_nodes);
490                 if(pressure > max_pressure)
491                         max_pressure = pressure;
492         }
493         ir_nodeset_destroy(&live_nodes);
494
495         loop_unused_spills_needed = max_pressure - env->registers_available;
496
497         if(loop_unused_spills_needed < 0) {
498                 loop_unused_spills_needed = 0;
499         } else if(loop_unused_spills_needed > loop_unused_spills_possible) {
500                 loop_unused_spills_needed = loop_unused_spills_possible;
501         }
502
503         DBG((dbg, DBG_PRESSURE, "Block %+F: max-pressure %d spills possible: %d spills used: %d\n",
504                  block, max_pressure, loop_unused_spills_possible, loop_unused_spills_needed));
505         return loop_unused_spills_needed;
506 }
507
508 /**
509  * Reduce register pressure in a loop
510  *
511  * @param unused_spills_possible        Number of spills from livethrough_unused variables possible in outer loops
512  * @return                                                      Number of spills of livethrough_unused variables needed in outer loops
513  */
514 static int reduce_register_pressure_in_loop(morgan_env_t *env, const ir_loop *loop, int outer_spills_possible) {
515         int i;
516         loop_attr_t* loop_attr = get_loop_attr(env, loop);
517         int spills_needed = 0;
518         int spills_possible = outer_spills_possible + bitset_popcnt(loop_attr->livethrough_unused);
519         int outer_spills_needed;
520
521         DBG((dbg, DBG_PRESSURE, "Reducing Pressure in loop %d\n", loop->loop_nr));
522         for(i = 0; i < get_loop_n_elements(loop); ++i) {
523                 loop_element elem = get_loop_element(loop, i);
524                 switch (*elem.kind) {
525                 case k_ir_node: {
526                         int needed;
527                         assert(is_Block(elem.node));
528                         needed = reduce_register_pressure_in_block(env, elem.node, spills_possible);
529                         assert(needed >= 0);
530                         assert(needed <= spills_possible);
531                         if(needed > spills_needed)
532                                 spills_needed = needed;
533                         break;
534                 }
535                 case k_ir_loop: {
536                         int needed = reduce_register_pressure_in_loop(env, elem.son, spills_possible);
537                         assert(needed >= 0);
538                         assert(needed <= spills_possible);
539                         if(needed > spills_needed)
540                                 spills_needed = needed;
541                         break;
542                 }
543             default:
544                         assert(0);
545                         break;
546                 }
547     }
548
549         /* calculate number of spills needed in outer loop and spill
550          * unused livethrough nodes around this loop */
551         if(spills_needed > outer_spills_possible) {
552                 int spills_to_place;
553                 outer_spills_needed = outer_spills_possible;
554                 spills_needed -= outer_spills_possible;
555
556                 spills_to_place = spills_needed;
557
558                 DBG((dbg, DBG_SPILLS, "%d values unused in loop %d, spilling %d\n",
559                  spills_possible - outer_spills_possible, loop->loop_nr, spills_to_place));
560
561                 spill_values(env, loop_attr, spills_to_place);
562         } else {
563                 outer_spills_needed = spills_needed;
564         }
565
566         return outer_spills_needed;
567 }
568
569 void be_spill_morgan(be_irg_t *birg, const arch_register_class_t *cls) {
570         ir_graph     *irg = be_get_birg_irg(birg);
571         morgan_env_t env;
572
573         be_liveness_assure_sets(be_assure_liveness(birg));
574
575         env.arch = birg->main_env->arch_env;
576         env.irg  = irg;
577         env.cls  = cls;
578         env.lv   = be_get_birg_liveness(birg);
579         env.senv = be_new_spill_env(birg);
580
581         obstack_init(&env.obst);
582
583         env.registers_available = env.cls->n_regs - be_put_ignore_regs(birg, env.cls, NULL);
584
585         env.loop_attr_set  = new_set(loop_attr_cmp, 5);
586         env.block_attr_set = new_set(block_attr_cmp, 20);
587
588         /* -- Part1: Analysis -- */
589
590         /* construct control flow loop tree */
591         if (! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
592                 construct_cf_backedges(irg);
593         }
594
595         /* construct loop out edges and livethrough_unused sets for loops and blocks */
596         irg_block_walk_graph(irg, construct_block_livethrough_unused, construct_loop_edges, &env);
597         construct_loop_livethrough_unused(&env, get_irg_loop(irg));
598
599         /* -- Part2: Transformation -- */
600
601         /* spill unused livethrough values around loops and blocks where
602          * the pressure is too high
603          */
604         reduce_register_pressure_in_loop(&env, get_irg_loop(irg), 0);
605
606         /* Insert real spill/reload nodes and fix usages */
607         be_insert_spills_reloads(env.senv);
608
609         /* Verify the result */
610         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
611                 be_verify_schedule(birg);
612         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
613                 assert(be_verify_schedule(birg));
614         }
615
616         /* cleanup */
617         free_loop_edges(&env);
618         del_set(env.loop_attr_set);
619         del_set(env.block_attr_set);
620
621         /* fix the remaining places with too high register pressure with beladies algorithm */
622         be_spill_belady_spill_env(birg, cls, env.senv);
623
624         be_delete_spill_env(env.senv);
625         obstack_free(&env.obst, NULL);
626 }
627
628 void be_init_spillmorgan(void)
629 {
630         static be_spiller_t morgan_spiller = {
631                 be_spill_morgan
632         };
633
634         be_register_spiller("morgan", &morgan_spiller);
635         FIRM_DBG_REGISTER(dbg, "ir.be.spillmorgan");
636 }
637
638 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillmorgan);