45db09588778c9ca846d004779799b1680d60a1c
[libfirm] / ir / be / beirgmod.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include <stdlib.h>
6
7 #ifdef HAVE_MALLOC_H
8  #include <malloc.h>
9 #endif
10 #ifdef HAVE_ALLOCA_H
11  #include <alloca.h>
12 #endif
13
14 #include "hashptr.h"
15 #include "pdeq.h"
16 #include "pset.h"
17 #include "pmap.h"
18 #include "util.h"
19 #include "debug.h"
20
21 #include "irflag_t.h"
22 #include "ircons_t.h"
23 #include "irnode_t.h"
24 #include "ircons_t.h"
25 #include "irmode_t.h"
26 #include "irdom_t.h"
27 #include "iredges_t.h"
28 #include "irgopt.h"
29 #include "irprintf_t.h"
30 #include "irgwalk.h"
31
32 #include "be_t.h"
33 #include "bechordal_t.h"
34 #include "bearch.h"
35 #include "besched_t.h"
36 #include "belive_t.h"
37 #include "benode_t.h"
38 #include "beutil.h"
39 #include "beinsn_t.h"
40
41 #include "beirgmod.h"
42
43 #define DBG_MODULE "firm.be.irgmod"
44 #define DBG_LEVEL SET_LEVEL_0
45
46 /*
47   ____                  _
48  |  _ \  ___  _ __ ___ (_)_ __   __ _ _ __   ___ ___
49  | | | |/ _ \| '_ ` _ \| | '_ \ / _` | '_ \ / __/ _ \
50  | |_| | (_) | | | | | | | | | | (_| | | | | (_|  __/
51  |____/ \___/|_| |_| |_|_|_| |_|\__,_|_| |_|\___\___|
52  |  ___| __ ___  _ __ | |_(_) ___ _ __ ___
53  | |_ | '__/ _ \| '_ \| __| |/ _ \ '__/ __|
54  |  _|| | | (_) | | | | |_| |  __/ |  \__ \
55  |_|  |_|  \___/|_| |_|\__|_|\___|_|  |___/
56
57 */
58
59
60 struct _dom_front_info_t {
61   pmap *df_map;
62 };
63
64 /**
65  * A wrapper for get_Block_idom.
66  * This function returns the block itself, if the block is the start
67  * block. Returning NULL would make any != comparison true which
68  * suggests, that the start block is dominated by some other node.
69  * @param bl The block.
70  * @return The immediate dominator of the block.
71  */
72 static INLINE ir_node *get_idom(ir_node *bl)
73 {
74   ir_node *idom = get_Block_idom(bl);
75   return idom == NULL ? bl : idom;
76 }
77
78 static void compute_df(ir_node *n, pmap *df_map)
79 {
80   ir_node *c;
81   const ir_edge_t *edge;
82   pset *df = pset_new_ptr_default();
83
84   /* Add local dominance frontiers */
85   foreach_block_succ(n, edge) {
86     ir_node *y = edge->src;
87
88     if(get_idom(y) != n)
89       pset_insert_ptr(df, y);
90   }
91
92   /*
93    * Go recursively down the dominance tree and add all blocks
94    * int the dominance frontiers of the children, which are not
95    * dominated by the given block.
96    */
97   for(c = get_Block_dominated_first(n); c; c = get_Block_dominated_next(c)) {
98     pset *df_c;
99     ir_node *w;
100
101     compute_df(c, df_map);
102     df_c = pmap_get(df_map, c);
103
104     for(w = pset_first(df_c); w; w = pset_next(df_c)) {
105       if(get_idom(w) != n)
106         pset_insert_ptr(df, w);
107     }
108   }
109
110   pmap_insert(df_map, n, df);
111
112 }
113
114 dom_front_info_t *be_compute_dominance_frontiers(ir_graph *irg)
115 {
116   dom_front_info_t *info = xmalloc(sizeof(*info));
117
118   edges_assure(irg);
119   info->df_map = pmap_create();
120   compute_doms(irg);
121   compute_df(get_irg_start_block(irg), info->df_map);
122
123   return info;
124 }
125
126 void be_free_dominance_frontiers(dom_front_info_t *info)
127 {
128   pmap_entry *ent;
129
130   for(ent = pmap_first(info->df_map); ent; ent = pmap_next(info->df_map))
131     del_pset(ent->value);
132
133   pmap_destroy(info->df_map);
134   free(info);
135 }
136
137 pset *be_get_dominance_frontier(dom_front_info_t *info, ir_node *block)
138 {
139   return pmap_get(info->df_map, block);
140 }
141
142 static void determine_phi_blocks(pset *copies, pset *copy_blocks, pset *phi_blocks, dom_front_info_t *df_info)
143 {
144         ir_node *bl;
145         pdeq *worklist = new_pdeq();
146         FIRM_DBG_REGISTER(firm_dbg_module_t *dbg, DBG_MODULE);
147
148         /*
149          * Fill the worklist queue and the rest of the orig blocks array.
150          */
151         for(bl = pset_first(copy_blocks); bl; bl = pset_next(copy_blocks)) {
152                 pdeq_putr(worklist, bl);
153         }
154
155         while (!pdeq_empty(worklist)) {
156                 ir_node *bl = pdeq_getl(worklist);
157                 pset *df    = be_get_dominance_frontier(df_info, bl);
158
159                 ir_node *y;
160
161                 DBG((dbg, LEVEL_3, "dom front of %+F\n", bl));
162                 DEBUG_ONLY(
163                         for (y = pset_first(df); y; y = pset_next(df))
164                                 DBG((dbg, LEVEL_3, "\t%+F\n", y))
165                 );
166
167                 for(y = pset_first(df); y; y = pset_next(df)) {
168                         if(!pset_find_ptr(phi_blocks, y)) {
169                                 pset_insert_ptr(phi_blocks, y);
170
171                                 /*
172                                  * Clear the link field of a possible phi block, since
173                                  * the possibly created phi will be stored there. See,
174                                  * search_def()
175                                  */
176                                 set_irn_link(y, NULL);
177
178                                 if(!pset_find_ptr(copy_blocks, y))
179                                         pdeq_putr(worklist, y);
180                         }
181                 }
182         }
183
184         del_pdeq(worklist);
185 }
186
187 /*
188   ____ ____    _
189  / ___/ ___|  / \
190  \___ \___ \ / _ \
191   ___) |__) / ___ \
192  |____/____/_/   \_\
193    ____                _                   _   _
194   / ___|___  _ __  ___| |_ _ __ _   _  ___| |_(_) ___  _ __
195  | |   / _ \| '_ \/ __| __| '__| | | |/ __| __| |/ _ \| '_ \
196  | |__| (_) | | | \__ \ |_| |  | |_| | (__| |_| | (_) | | | |
197   \____\___/|_| |_|___/\__|_|   \__,_|\___|\__|_|\___/|_| |_|
198
199 */
200
201 /**
202  * Find the copy of the given original node whose value is 'active'
203  * at a usage.
204  *
205  * The usage is given as a node and a position. Initially, the given operand
206  * points to a node for which copies were introduced. We have to find
207  * the valid copy for this usage. This is done by traversing the
208  * dominance tree upwards. If the usage is a phi function, we start
209  * traversing from the predecessor block which corresponds to the phi
210  * usage.
211  *
212  * @param usage       The node which uses the original node.
213  * @param pos         The position of the argument which corresponds to the original node.
214  * @param copies      A set containing all node which are copies from the original node.
215  * @param copy_blocks A set containing all basic block in which copies of the original node are located.
216  * @param phis        A set where all created phis are recorded.
217  * @param phi_blocks  A set of all blocks where Phis shall be inserted (iterated dominance frontier).
218  * @param mode        The mode for the Phi if one has to be created.
219  * @return            The valid copy for usage.
220  */
221 static ir_node *search_def(ir_node *usage, int pos, pset *copies, pset *copy_blocks, pset *phis, pset *phi_blocks, ir_mode *mode)
222 {
223         ir_node *curr_bl;
224         ir_node *start_irn;
225         FIRM_DBG_REGISTER(firm_dbg_module_t *dbg, DBG_MODULE);
226
227         curr_bl = get_nodes_block(usage);
228
229         DBG((dbg, LEVEL_1, "Searching valid def for use %+F at pos %d\n", usage, pos));
230         /*
231          * If the usage is in a phi node, search the copy in the
232          * predecessor denoted by pos.
233          */
234         if(is_Phi(usage)) {
235                 curr_bl = get_Block_cfgpred_block(curr_bl, pos);
236                 start_irn = sched_last(curr_bl);
237         } else {
238                 start_irn = sched_prev(usage);
239         }
240
241         /*
242          * Traverse the dominance tree upwards from the
243          * predecessor block of the usage.
244          */
245         while(curr_bl != NULL) {
246
247             /*
248                  * If this block contains a copy, search the block
249                  * instruction by instruction.
250                  */
251                 if(pset_find_ptr(copy_blocks, curr_bl)) {
252                         ir_node *irn;
253
254                         /* Look at each instruction from last to first. */
255                         sched_foreach_reverse_from(start_irn, irn) {
256
257                                 /* Take the first copy we find. */
258                                 if(pset_find_ptr(copies, irn))
259                                         return irn;
260                         }
261                 }
262
263                 if(pset_find_ptr(phi_blocks, curr_bl)) {
264                         ir_node *phi = get_irn_link(curr_bl);
265
266                         if(phi == NULL) {
267                                 int i, n_preds = get_irn_arity(curr_bl);
268                                 ir_graph *irg = get_irn_irg(curr_bl);
269                                 ir_node **ins = alloca(n_preds * sizeof(ins[0]));
270
271                                 for(i = 0; i < n_preds; ++i)
272                                         ins[i] = new_r_Bad(irg);
273
274                                 phi = new_r_Phi(irg, curr_bl, n_preds, ins, mode);
275                                 DBG((dbg, LEVEL_2, "\tcreating phi %+F in %+F\n", phi, curr_bl));
276
277                                 set_irn_link(curr_bl, phi);
278                                 if(mode != mode_M)
279                                         sched_add_after(curr_bl, phi);
280
281                                 for(i = 0; i < n_preds; ++i) {
282                                         ir_node *arg = search_def(phi, i, copies, copy_blocks, phis, phi_blocks, mode);
283                                         DBG((dbg, LEVEL_2, "\t\t%+F(%d) -> %+F\n", phi, i, arg));
284                                         set_irn_n(phi, i, arg);
285                                 }
286
287                                 if(phis != NULL)
288                                         pset_insert_ptr(phis, phi);
289                         }
290
291                         return phi;
292                 }
293
294                 /* If were not done yet, look in the immediate dominator */
295                 curr_bl = get_Block_idom(curr_bl);
296                 if(curr_bl)
297                         start_irn = sched_last(curr_bl);
298         }
299
300         return NULL;
301 }
302
303 static void fix_usages(pset *copies, pset *copy_blocks, pset *phi_blocks, pset *phis, pset *ignore_uses)
304 {
305         int n_outs = 0;
306         struct obstack obst;
307         ir_node *irn;
308         int i;
309         struct out {
310                 ir_node *irn;
311                 int pos;
312         } *outs;
313
314         FIRM_DBG_REGISTER(firm_dbg_module_t *dbg, DBG_MODULE);
315
316         obstack_init(&obst);
317
318         /*
319          * Put all outs into an array.
320          * This is necessary, since the outs would be modified while
321          * iterating on them what could bring the outs module in trouble.
322          */
323         for (irn = pset_first(copies); irn; irn = pset_next(copies)) {
324                 const ir_edge_t *edge;
325                 foreach_out_edge(irn, edge) {
326                         if (!pset_find_ptr(ignore_uses, get_edge_src_irn(edge))) {
327                                 struct out tmp;
328                                 tmp.irn = get_edge_src_irn(edge);
329                                 tmp.pos = get_edge_src_pos(edge);
330                                 obstack_grow(&obst, &tmp, sizeof(tmp));
331                                 n_outs++;
332                         }
333                 }
334         }
335         outs = obstack_finish(&obst);
336
337         /*
338          * Search the valid def for each out and set it.
339          */
340         for(i = 0; i < n_outs; ++i) {
341                 ir_node *irn  = outs[i].irn;
342                 int pos       = outs[i].pos;
343                 ir_mode *mode = get_irn_mode(get_irn_n(irn, pos));
344
345                 ir_node *def;
346
347                 def = search_def(irn, pos, copies, copy_blocks, phis, phi_blocks, mode);
348                 DBG((dbg, LEVEL_2, "\t%+F(%d) -> %+F\n", irn, pos, def));
349
350                 if(def != NULL)
351                         set_irn_n(irn, pos, def);
352         }
353
354         obstack_free(&obst, NULL);
355 }
356
357 #if 0
358 /**
359  * Remove phis which are not necessary.
360  * During place_phi_functions() phi functions are put on the dominance
361  * frontiers blindly. However some of them will never be used (these
362  * have at least one predecessor which is NULL, see search_def() for
363  * this case). Since place_phi_functions() enters them into the
364  * schedule, we have to remove them from there.
365  *
366  * @param copies The set of all copies made (including the phi functions).
367  */
368 static void remove_odd_phis(pset *copies, pset *unused_copies)
369 {
370         ir_node *irn;
371
372         for(irn = pset_first(copies); irn; irn = pset_next(copies)) {
373                 if(is_Phi(irn)) {
374                         int i, n;
375                         int illegal = 0;
376
377                         assert(sched_is_scheduled(irn) && "phi must be scheduled");
378                         for(i = 0, n = get_irn_arity(irn); i < n && !illegal; ++i)
379                                 illegal = get_irn_n(irn, i) == NULL;
380
381                         if(illegal) {
382                                 for(i = 0, n = get_irn_arity(irn); i < n; ++i)
383                                         set_irn_n(irn, i, new_Bad());
384                                 sched_remove(irn);
385                         }
386                 }
387         }
388
389         for(irn = pset_first(unused_copies); irn; irn = pset_next(unused_copies)) {
390                 for(i = 0, n = get_irn_arity(irn); i < n; ++i)
391                         set_irn_n(irn, i, new_Bad());
392                 sched_remove(irn);
393         }
394 }
395 #endif
396
397 void be_ssa_constr_phis_ignore(dom_front_info_t *info, be_lv_t *lv, int n, ir_node *nodes[], pset *phis, pset *ignore_uses)
398 {
399         pset *irns = pset_new_ptr(n);
400         int i;
401
402         for(i = 0; i < n; ++i)
403                 pset_insert_ptr(irns, nodes[i]);
404         be_ssa_constr_set_phis_ignore(info, lv, irns, phis, ignore_uses);
405         del_pset(irns);
406 }
407
408 void be_ssa_constr_ignore(dom_front_info_t *info, be_lv_t *lv, int n, ir_node *nodes[], pset *ignore_uses)
409 {
410         be_ssa_constr_phis_ignore(info, lv, n, nodes, NULL, ignore_uses);
411 }
412
413 void be_ssa_constr(dom_front_info_t *info, be_lv_t *lv, int n, ir_node *nodes[])
414 {
415         pset *empty_set = be_empty_set();
416         be_ssa_constr_ignore(info, lv, n, nodes, empty_set);
417 }
418
419 void be_ssa_constr_set_phis_ignore(dom_front_info_t *df, be_lv_t *lv, pset *nodes, pset *phis, pset *ignore_uses)
420 {
421         int n                  = pset_count(nodes);
422         pset *blocks           = pset_new_ptr(n);
423         pset *phi_blocks       = pset_new_ptr(n);
424         int save_optimize      = get_optimize();
425         int save_normalize     = get_opt_normalize();
426         int phis_set_created   = 0;
427         FIRM_DBG_REGISTER(firm_dbg_module_t *dbg, DBG_MODULE);
428
429         ir_node *irn;
430
431         /* We need to collect the phi functions to compute their liveness. */
432         if(lv && !phis) {
433                 phis_set_created = 1;
434                 phis = pset_new_ptr_default();
435         }
436
437         DBG((dbg, LEVEL_1, "Introducing following copies for:\n"));
438
439         /* Fill the sets. */
440         for(irn = pset_first(nodes); irn; irn = pset_next(nodes)) {
441                 ir_node *bl = get_nodes_block(irn);
442                 pset_insert_ptr(blocks, bl);
443                 DBG((dbg, LEVEL_1, "\t%+F in %+F\n", irn, bl));
444         }
445
446         /*
447          * Disable optimization so that the phi functions do not
448          * disappear.
449          */
450         set_optimize(0);
451         set_opt_normalize(0);
452
453         /*
454          * Place the phi functions and reroute the usages.
455          */
456         determine_phi_blocks(nodes, blocks, phi_blocks, df);
457         fix_usages(nodes, blocks, phi_blocks, phis, ignore_uses);
458
459         /* reset the optimizations */
460         set_optimize(save_optimize);
461         set_opt_normalize(save_normalize);
462
463         del_pset(phi_blocks);
464         del_pset(blocks);
465
466         /* Recompute the liveness (if wanted) of the original nodes, the copies and the inserted phis. */
467         if(lv) {
468 #if 1
469                 foreach_pset(nodes, irn)
470                         be_liveness_update(lv, irn);
471
472                 foreach_pset(phis, irn)
473                         be_liveness_introduce(lv, irn);
474 #else
475                 be_liveness_recompute(lv);
476 #endif
477         }
478
479         /* Free the phi set of we created it. */
480         if(phis_set_created)
481                 del_pset(phis);
482
483 }
484
485 void be_ssa_constr_set_phis(dom_front_info_t *df, be_lv_t *lv, pset *nodes, pset *phis)
486 {
487         pset *empty_set = be_empty_set();
488         be_ssa_constr_set_phis_ignore(df, lv, nodes, phis, empty_set);
489 }
490
491 void be_ssa_constr_set_ignore(dom_front_info_t *df, be_lv_t *lv, pset *nodes, pset *ignore_uses)
492 {
493         be_ssa_constr_set_phis_ignore(df, lv, nodes, NULL, ignore_uses);
494 }
495
496 void be_ssa_constr_set(dom_front_info_t *info, be_lv_t *lv, pset *nodes)
497 {
498         pset *empty_set = be_empty_set();
499         be_ssa_constr_set_ignore(info, lv, nodes, empty_set);
500 }
501
502 /*
503   ___                     _     ____
504  |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___ _ __ _ __ ___
505   | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ '__| '_ ` _ \
506   | || | | \__ \  __/ |  | |_  |  __/  __/ |  | | | | | |
507  |___|_| |_|___/\___|_|   \__| |_|   \___|_|  |_| |_| |_|
508
509 */
510
511 ir_node *insert_Perm_after(const arch_env_t *arch_env,
512                                                    be_lv_t *lv,
513                                                    const arch_register_class_t *cls,
514                                                    dom_front_info_t *dom_front,
515                                                    ir_node *pos)
516 {
517         ir_node *bl     = is_Block(pos) ? pos : get_nodes_block(pos);
518         ir_graph *irg   = get_irn_irg(bl);
519         pset *live      = pset_new_ptr_default();
520         FIRM_DBG_REGISTER(firm_dbg_module_t *dbg, "be.node");
521
522         ir_node *curr, *irn, *perm, **nodes;
523         int i, n;
524
525         DBG((dbg, LEVEL_1, "Insert Perm after: %+F\n", pos));
526
527         be_liveness_nodes_live_at(lv, arch_env, cls, pos, live);
528
529         n = pset_count(live);
530
531         if(n == 0) {
532                 del_pset(live);
533                 return NULL;
534         }
535
536         nodes = xmalloc(n * sizeof(nodes[0]));
537
538         DBG((dbg, LEVEL_1, "live:\n"));
539         for(irn = pset_first(live), i = 0; irn; irn = pset_next(live), i++) {
540                 DBG((dbg, LEVEL_1, "\t%+F\n", irn));
541                 nodes[i] = irn;
542         }
543         del_pset(live);
544
545         perm = be_new_Perm(cls, irg, bl, n, nodes);
546         sched_add_after(pos, perm);
547         free(nodes);
548
549         curr = perm;
550         for(i = 0; i < n; ++i) {
551                 ir_node *copies[2];
552                 ir_node *perm_op = get_irn_n(perm, i);
553                 const arch_register_t *reg = arch_get_irn_register(arch_env, perm_op);
554
555                 ir_mode *mode = get_irn_mode(perm_op);
556                 ir_node *proj = new_r_Proj(irg, bl, perm, mode, i);
557                 arch_set_irn_register(arch_env, proj, reg);
558
559                 sched_add_after(curr, proj);
560                 curr = proj;
561
562                 copies[0] = perm_op;
563                 copies[1] = proj;
564
565                 be_ssa_constr(dom_front, lv, 2, copies);
566         }
567
568         return perm;
569 }
570
571 struct _elr_closure_t {
572         struct obstack obst;
573         const be_chordal_env_t *cenv;
574 };
575
576 static void elr_split_walker(ir_node *bl, void *data)
577 {
578         struct _elr_closure_t *c     = data;
579         const be_chordal_env_t *cenv = c->cenv;
580         const arch_env_t *aenv       = cenv->birg->main_env->arch_env;
581         be_insn_t *insn;
582         be_insn_env_t ie;
583
584         be_insn_env_init(&ie, cenv->birg, cenv->cls, &c->obst);
585
586         for(insn = be_scan_insn(&ie, sched_first(bl)); !is_Block(insn->irn); insn = be_scan_insn(&ie, insn->next_insn)) {
587                 ir_node *pred = sched_prev(insn->irn);
588                 if(!is_Block(pred) && !is_Phi(insn->irn))
589                         insert_Perm_after(aenv, cenv->lv, cenv->cls, cenv->dom_front, insn->irn);
590         }
591 }
592
593 void extreme_liverange_splitting(struct _be_chordal_env_t *cenv)
594 {
595         struct _elr_closure_t c;
596
597         c.cenv = cenv;
598         obstack_init(&c.obst);
599         be_liveness_recompute(cenv->lv);
600         irg_block_walk_graph(cenv->irg, elr_split_walker, NULL, &c);
601         be_liveness_recompute(cenv->lv);
602         obstack_free(&c.obst, NULL);
603 }
604
605 static void remove_empty_block(ir_node *block, void *data) {
606         ir_graph *irg;
607         const ir_edge_t *edge, *next;
608         ir_node *node;
609         ir_node *jump = NULL;
610
611         assert(is_Block(block));
612
613         if(get_Block_n_cfgpreds(block) != 1)
614                 return;
615
616         sched_foreach(block, node) {
617                 if(!is_Jmp(node))
618                         return;
619                 if(jump != NULL) {
620                         // we should never have 2 jumps in a block
621                         assert(0);
622                         return;
623                 }
624                 jump = node;
625         }
626         if(jump == NULL)
627                 return;
628
629         node = get_Block_cfgpred(block, 0);
630         foreach_out_edge_safe(jump, edge, next) {
631                 ir_node *block = get_edge_src_irn(edge);
632                 int pos = get_edge_src_pos(edge);
633
634                 set_irn_n(block, pos, node);
635         }
636
637         set_Block_cfgpred(block, 0, new_Bad());
638         sched_remove(jump);
639
640         irg = get_irn_irg(block);
641         set_irg_doms_inconsistent(irg);
642         set_irg_extblk_inconsistent(irg);
643 }
644
645 /**
646  * removes basic blocks that just contain a jump instruction
647  */
648 void be_remove_empty_blocks(ir_graph *irg) {
649         irg_block_walk_graph(irg, remove_empty_block, NULL, NULL);
650 }