fe140dcd832bb7b746e493cb49f0329bc535e561
[libfirm] / ir / opt / code_placement.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    Code Placement.  Pins all floating nodes to a block where they
23  *           will be executed only if needed.
24  * @author   Christian Schaefer, Goetz Lindenmaier, Sebastian Felis,
25  *           Michael Beck
26  * @version  $Id$
27  */
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include "adt/pdeq.h"
33 #include "irnode_t.h"
34 #include "irouts.h"
35 #include "irgopt.h"
36
37 /**
38  * Returns non-zero, is a block is not reachable from Start.
39  *
40  * @param block  the block to test
41  */
42 static int
43 is_Block_unreachable(ir_node *block) {
44         return is_Block_dead(block) || get_Block_dom_depth(block) < 0;
45 }
46
47 /**
48  * Find the earliest correct block for node n.  --- Place n into the
49  * same Block as its dominance-deepest Input.
50  *
51  * We have to avoid calls to get_nodes_block() here
52  * because the graph is floating.
53  *
54  * move_out_of_loops() expects that place_floats_early() have placed
55  * all "living" nodes into a living block. That's why we must
56  * move nodes in dead block with "live" successors into a valid
57  * block.
58  * We move them just into the same block as it's successor (or
59  * in case of a Phi into the effective use block). For Phi successors,
60  * this may still be a dead block, but then there is no real use, as
61  * the control flow will be dead later.
62  *
63  * @param n         the node to be placed
64  * @param worklist  a worklist, predecessors of non-floating nodes are placed here
65  */
66 static void
67 place_floats_early(ir_node *n, waitq *worklist) {
68         int i, irn_arity;
69
70         /* we must not run into an infinite loop */
71         assert(!irn_visited(n));
72         mark_irn_visited(n);
73
74         /* Place floating nodes. */
75         if (get_irn_pinned(n) == op_pin_state_floats) {
76                 ir_node *curr_block = get_nodes_block(n);
77                 int in_dead_block   = is_Block_unreachable(curr_block);
78                 int depth           = 0;
79                 ir_node *b          = NULL;   /* The block to place this node in */
80
81                 assert(is_no_Block(n));
82
83                 if (is_irn_start_block_placed(n)) {
84                         /* These nodes will not be placed by the loop below. */
85                         b = get_irg_start_block(current_ir_graph);
86                         depth = 1;
87                 }
88
89                 /* find the block for this node. */
90                 irn_arity = get_irn_arity(n);
91                 for (i = 0; i < irn_arity; i++) {
92                         ir_node *pred = get_irn_n(n, i);
93                         ir_node *pred_block;
94
95                         if (!irn_visited(pred)
96                             && (get_irn_pinned(pred) == op_pin_state_floats)) {
97
98                                 /*
99                                  * If the current node is NOT in a dead block, but one of its
100                                  * predecessors is, we must move the predecessor to a live block.
101                                  * Such thing can happen, if global CSE chose a node from a dead block.
102                                  * We move it simply to our block.
103                                  * Note that neither Phi nor End nodes are floating, so we don't
104                                  * need to handle them here.
105                                  */
106                                 if (! in_dead_block) {
107                                         if (get_irn_pinned(pred) == op_pin_state_floats &&
108                                                 is_Block_unreachable(get_nodes_block(pred)))
109                                                 set_nodes_block(pred, curr_block);
110                                 }
111                                 place_floats_early(pred, worklist);
112                         }
113
114                         /*
115                          * A node in the Bad block must stay in the bad block,
116                          * so don't compute a new block for it.
117                          */
118                         if (in_dead_block)
119                                 continue;
120
121                         /* Because all loops contain at least one op_pin_state_pinned node, now all
122                            our inputs are either op_pin_state_pinned or place_early() has already
123                            been finished on them.  We do not have any unfinished inputs!  */
124                         pred_block = get_nodes_block(pred);
125                         if ((!is_Block_dead(pred_block)) &&
126                                 (get_Block_dom_depth(pred_block) > depth)) {
127                                 b = pred_block;
128                                 depth = get_Block_dom_depth(pred_block);
129                         }
130                         /* Avoid that the node is placed in the Start block if we are not in the
131                            backend phase. */
132                         if (depth == 1 &&
133                                         get_Block_dom_depth(get_nodes_block(n)) > 1 &&
134                                         get_irg_phase_state(current_ir_graph) != phase_backend) {
135                                 b = get_Block_cfg_out(get_irg_start_block(current_ir_graph), 0);
136                                 assert(b != get_irg_start_block(current_ir_graph));
137                                 depth = 2;
138                         }
139                 }
140                 if (b)
141                         set_nodes_block(n, b);
142         }
143
144         /*
145          * Add predecessors of non floating nodes and non-floating predecessors
146          * of floating nodes to worklist and fix their blocks if the are in dead block.
147          */
148         irn_arity = get_irn_arity(n);
149
150         if (is_End(n)) {
151                 /*
152                  * Simplest case: End node. Predecessors are keep-alives,
153                  * no need to move out of dead block.
154                  */
155                 for (i = -1; i < irn_arity; ++i) {
156                         ir_node *pred = get_irn_n(n, i);
157                         if (!irn_visited(pred))
158                                 waitq_put(worklist, pred);
159                 }
160         } else if (is_Block(n)) {
161                 /*
162                  * Blocks: Predecessors are control flow, no need to move
163                  * them out of dead block.
164                  */
165                 for (i = irn_arity - 1; i >= 0; --i) {
166                         ir_node *pred = get_irn_n(n, i);
167                         if (!irn_visited(pred))
168                                 waitq_put(worklist, pred);
169                 }
170         } else if (is_Phi(n)) {
171                 ir_node *pred;
172                 ir_node *curr_block = get_nodes_block(n);
173                 int in_dead_block   = is_Block_unreachable(curr_block);
174
175                 /*
176                  * Phi nodes: move nodes from dead blocks into the effective use
177                  * of the Phi-input if the Phi is not in a bad block.
178                  */
179                 pred = get_nodes_block(n);
180                 if (!irn_visited(pred))
181                         waitq_put(worklist, pred);
182
183                 for (i = irn_arity - 1; i >= 0; --i) {
184                         ir_node *pred = get_irn_n(n, i);
185
186                         if (!irn_visited(pred)) {
187                                 if (! in_dead_block &&
188                                         get_irn_pinned(pred) == op_pin_state_floats &&
189                                         is_Block_unreachable(get_nodes_block(pred))) {
190                                         set_nodes_block(pred, get_Block_cfgpred_block(curr_block, i));
191                                 }
192                                 waitq_put(worklist, pred);
193                         }
194                 }
195         } else {
196                 ir_node *pred;
197                 ir_node *curr_block = get_nodes_block(n);
198                 int in_dead_block   = is_Block_unreachable(curr_block);
199
200                 /*
201                  * All other nodes: move nodes from dead blocks into the same block.
202                  */
203                 pred = get_nodes_block(n);
204                 if (!irn_visited(pred))
205                         waitq_put(worklist, pred);
206
207                 for (i = irn_arity - 1; i >= 0; --i) {
208                         ir_node *pred = get_irn_n(n, i);
209
210                         if (!irn_visited(pred)) {
211                                 if (! in_dead_block &&
212                                         get_irn_pinned(pred) == op_pin_state_floats &&
213                                         is_Block_unreachable(get_nodes_block(pred))) {
214                                         set_nodes_block(pred, curr_block);
215                                 }
216                                 waitq_put(worklist, pred);
217                         }
218                 }
219         }
220 }
221
222 /**
223  * Floating nodes form subgraphs that begin at nodes as Const, Load,
224  * Start, Call and that end at op_pin_state_pinned nodes as Store, Call.  Place_early
225  * places all floating nodes reachable from its argument through floating
226  * nodes and adds all beginnings at op_pin_state_pinned nodes to the worklist.
227  *
228  * @param worklist   a worklist, used for the algorithm, empty on in/output
229  */
230 static void place_early(waitq *worklist) {
231         assert(worklist);
232         inc_irg_visited(current_ir_graph);
233
234         /* this inits the worklist */
235         place_floats_early(get_irg_end(current_ir_graph), worklist);
236
237         /* Work the content of the worklist. */
238         while (!waitq_empty(worklist)) {
239                 ir_node *n = waitq_get(worklist);
240                 if (!irn_visited(n))
241                         place_floats_early(n, worklist);
242         }
243         set_irg_pinned(current_ir_graph, op_pin_state_pinned);
244 }
245
246 /**
247  * Compute the deepest common dominator tree ancestor of block and dca.
248  *
249  * @param dca    the deepest common dominator tree ancestor so far,
250  *               might be NULL
251  * @param block  a block
252  *
253  * @return  the deepest common dominator tree ancestor of block and dca
254  */
255 static ir_node *calc_dom_dca(ir_node *dca, ir_node *block) {
256         assert(block);
257
258         /* we do not want to place nodes in dead blocks */
259         if (is_Block_dead(block))
260                 return dca;
261
262         /* We found a first legal placement. */
263         if (!dca) return block;
264
265         /* Find a placement that is dominates both, dca and block. */
266         while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
267                 block = get_Block_idom(block);
268
269         while (get_Block_dom_depth(dca) > get_Block_dom_depth(block)) {
270                 dca = get_Block_idom(dca);
271         }
272
273         while (block != dca) {
274                 block = get_Block_idom(block); dca = get_Block_idom(dca);
275         }
276         return dca;
277 }
278
279 /**
280  * Deepest common dominance ancestor of DCA and CONSUMER of PRODUCER.
281  * I.e., DCA is the block where we might place PRODUCER.
282  * A data flow edge points from producer to consumer.
283  */
284 static ir_node *consumer_dom_dca(ir_node *dca, ir_node *consumer, ir_node *producer)
285 {
286         /* Compute the last block into which we can place a node so that it is
287            before consumer. */
288         if (is_Phi(consumer)) {
289                 /* our consumer is a Phi-node, the effective use is in all those
290                    blocks through which the Phi-node reaches producer */
291                 ir_node *phi_block = get_nodes_block(consumer);
292                 int      arity     = get_irn_arity(consumer);
293                 int      i;
294
295                 for (i = 0;  i < arity; i++) {
296                         if (get_Phi_pred(consumer, i) == producer) {
297                                 ir_node *new_block = get_Block_cfgpred_block(phi_block, i);
298
299                                 if (!is_Block_unreachable(new_block))
300                                         dca = calc_dom_dca(dca, new_block);
301                         }
302                 }
303         } else {
304                 dca = calc_dom_dca(dca, get_nodes_block(consumer));
305         }
306         return dca;
307 }
308
309 /* FIXME: the name clashes here with the function from ana/field_temperature.c
310  * please rename. */
311 static INLINE int get_irn_loop_depth(ir_node *n) {
312         return get_loop_depth(get_irn_loop(n));
313 }
314
315 /**
316  * Move n to a block with less loop depth than it's current block. The
317  * new block must be dominated by early.
318  *
319  * @param n      the node that should be moved
320  * @param early  the earliest block we can n move to
321  */
322 static void move_out_of_loops(ir_node *n, ir_node *early) {
323         ir_node *best, *dca;
324         assert(n && early);
325
326
327         /* Find the region deepest in the dominator tree dominating
328            dca with the least loop nesting depth, but still dominated
329            by our early placement. */
330         dca = get_nodes_block(n);
331
332         best = dca;
333         while (dca != early) {
334                 dca = get_Block_idom(dca);
335                 if (!dca || is_Bad(dca)) break; /* may be Bad if not reachable from Start */
336                 if (get_irn_loop_depth(dca) < get_irn_loop_depth(best)) {
337                         best = dca;
338                 }
339         }
340         if (best != get_nodes_block(n))
341                 set_nodes_block(n, best);
342 }
343
344 /**
345  * Calculate the deepest common ancestor in the dominator tree of all nodes'
346  * blocks depending on node; our final placement has to dominate DCA.
347  *
348  * @param node  the definition node
349  * @param dca   the deepest common ancestor block so far, initially
350  *              NULL
351  *
352  * @return the deepest common dominator ancestor of all blocks of node's users
353  */
354 static ir_node *get_deepest_common_dom_ancestor(ir_node *node, ir_node *dca) {
355         int i;
356
357         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
358                 ir_node *succ = get_irn_out(node, i);
359
360                 if (is_End(succ)) {
361                         /*
362                          * This consumer is the End node, a keep alive edge.
363                          * This is not a real consumer, so we ignore it
364                          */
365                         continue;
366                 }
367
368                 if (is_Proj(succ)) {
369                         /* Proj nodes are in the same block as node, so
370                          * the users of Proj are our users. */
371                         dca = get_deepest_common_dom_ancestor(succ, dca);
372                 } else {
373                         /* ignore if succ is in dead code */
374                         ir_node *succ_blk = get_nodes_block(succ);
375                         if (is_Block_unreachable(succ_blk))
376                                 continue;
377                         dca = consumer_dom_dca(dca, succ, node);
378                 }
379         }
380         return dca;
381 }
382
383 /**
384  * Put all the Proj nodes of a node into a given block.
385  *
386  * @param node   the mode_T node
387  * @param block  the block to put the Proj nodes to
388  */
389 static void set_projs_block(ir_node *node, ir_node *block) {
390         int i;
391
392         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
393                 ir_node *succ = get_irn_out(node, i);
394
395                 assert(is_Proj(succ));
396
397                 if (get_irn_mode(succ) == mode_T) {
398                         set_projs_block(succ, block);
399                 }
400                 set_nodes_block(succ, block);
401         }
402 }
403
404 /**
405  * Find the latest legal block for N and place N into the
406  * `optimal' Block between the latest and earliest legal block.
407  * The `optimal' block is the dominance-deepest block of those
408  * with the least loop-nesting-depth.  This places N out of as many
409  * loops as possible and then makes it as control dependent as
410  * possible.
411  *
412  * @param n         the node to be placed
413  * @param worklist  a worklist, all successors of non-floating nodes are
414  *                  placed here
415  */
416 static void place_floats_late(ir_node *n, pdeq *worklist) {
417         int i, n_outs;
418         ir_node *early_blk;
419
420         assert(!irn_visited(n)); /* no multiple placement */
421
422         mark_irn_visited(n);
423
424         /* no need to place block nodes, control nodes are already placed. */
425         if (!is_Block(n) &&
426             (!is_cfop(n)) &&
427             (get_irn_mode(n) != mode_X)) {
428                 /* Remember the early_blk placement of this block to move it
429                    out of loop no further than the early_blk placement. */
430                 early_blk = get_nodes_block(n);
431
432                 /*
433                  * BEWARE: Here we also get code, that is live, but
434                  * was in a dead block.  If the node is life, but because
435                  * of CSE in a dead block, we still might need it.
436                  */
437
438                 /* Assure that our users are all placed, except the Phi-nodes.
439                 --- Each data flow cycle contains at least one Phi-node.  We
440                     have to break the `user has to be placed before the
441                     producer' dependence cycle and the Phi-nodes are the
442                     place to do so, because we need to base our placement on the
443                     final region of our users, which is OK with Phi-nodes, as they
444                     are op_pin_state_pinned, and they never have to be placed after a
445                     producer of one of their inputs in the same block anyway. */
446                 for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
447                         ir_node *succ = get_irn_out(n, i);
448                         if (!irn_visited(succ) && !is_Phi(succ))
449                                 place_floats_late(succ, worklist);
450                 }
451
452                 if (! is_Block_dead(early_blk)) {
453                         /* do only move things that where not dead */
454                         ir_op *op = get_irn_op(n);
455
456                         /* We have to determine the final block of this node... except for
457                            constants and Projs */
458                         if ((get_irn_pinned(n) == op_pin_state_floats) &&
459                             (op != op_Const)    &&
460                             (op != op_SymConst) &&
461                             (op != op_Proj))
462                         {
463                                 /* deepest common ancestor in the dominator tree of all nodes'
464                                    blocks depending on us; our final placement has to dominate
465                                    DCA. */
466                                 ir_node *dca = get_deepest_common_dom_ancestor(n, NULL);
467                                 if (dca != NULL) {
468                                         set_nodes_block(n, dca);
469                                         move_out_of_loops(n, early_blk);
470                                         if (get_irn_mode(n) == mode_T) {
471                                                 set_projs_block(n, get_nodes_block(n));
472                                         }
473                                 }
474                         }
475                 }
476         }
477
478         /* Add successors of all non-floating nodes on list. (Those of floating
479            nodes are placed already and therefore are marked.)  */
480         n_outs = get_irn_n_outs(n);
481         for (i = 0; i < n_outs; i++) {
482                 ir_node *succ = get_irn_out(n, i);
483                 if (!irn_visited(succ)) {
484                         pdeq_putr(worklist, succ);
485                 }
486         }
487 }
488
489 /**
490  * Place floating nodes on the given worklist as late as possible using
491  * the dominance tree.
492  *
493  * @param worklist   the worklist containing the nodes to place
494  */
495 static void place_late(waitq *worklist) {
496         assert(worklist);
497         inc_irg_visited(current_ir_graph);
498
499         /* This fills the worklist initially. */
500         place_floats_late(get_irg_start_block(current_ir_graph), worklist);
501
502         /* And now empty the worklist again... */
503         while (!waitq_empty(worklist)) {
504                 ir_node *n = waitq_get(worklist);
505                 if (!irn_visited(n))
506                         place_floats_late(n, worklist);
507         }
508 }
509
510 /* Code Placement. */
511 void place_code(ir_graph *irg) {
512         waitq *worklist;
513         ir_graph *rem = current_ir_graph;
514
515         current_ir_graph = irg;
516         remove_critical_cf_edges(irg);
517
518         /* Handle graph state */
519         assert(get_irg_phase_state(irg) != phase_building);
520         assure_doms(irg);
521
522         if (1 || get_irg_loopinfo_state(irg) != loopinfo_consistent) {
523                 free_loop_information(irg);
524                 construct_cf_backedges(irg);
525         }
526
527         /* Place all floating nodes as early as possible. This guarantees
528          a legal code placement. */
529         worklist = new_waitq();
530         place_early(worklist);
531
532         /* Note: place_early changes only blocks, no data edges. So, the
533          * data out edges are still valid, no need to recalculate them here. */
534
535         /* Now move the nodes down in the dominator tree. This reduces the
536            unnecessary executions of the node. */
537         place_late(worklist);
538
539         set_irg_outs_inconsistent(irg);
540         set_irg_loopinfo_inconsistent(irg);
541         del_waitq(worklist);
542         current_ir_graph = rem;
543 }