Let foreach_pset() declare its iterator variable.
[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    Move nodes to a block where they will be executed the least
23  *           often.
24  * @author   Christian Schaefer, Goetz Lindenmaier, Sebastian Felis,
25  *           Michael Beck
26  *
27  * The idea here is to push nodes as deep into the dominance tree as their
28  * dependencies allow. After pushing them back up out of as many loops as
29  * possible.
30  */
31 #include "config.h"
32
33 #include <stdbool.h>
34
35 #include "iroptimize.h"
36 #include "adt/pdeq.h"
37 #include "irnode_t.h"
38 #include "irouts.h"
39 #include "irgopt.h"
40 #include "irpass.h"
41
42 static bool is_block_reachable(ir_node *block)
43 {
44         return 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  * move_out_of_loops() expects that place_floats_early() have placed
52  * all "living" nodes into a living block. That's why we must
53  * move nodes in dead block with "live" successors into a valid
54  * block.
55  * We move them just into the same block as its successor (or
56  * in case of a Phi into the effective use block). For Phi successors,
57  * this may still be a dead block, but then there is no real use, as
58  * the control flow will be dead later.
59  */
60 static void place_floats_early(ir_node *n, waitq *worklist)
61 {
62         int       i;
63         int       arity;
64         ir_node  *block;
65         int       new_depth;
66         ir_graph *irg;
67         ir_node  *start_block;
68         ir_node  *new_block;
69
70         /* we must not run into an infinite loop */
71         if (irn_visited_else_mark(n))
72                 return;
73
74         /* The algorithm relies on the fact that all predecessors of a block are
75          * moved up after a call to place_float_early of the predecessors
76          * (see the loop below).
77          * However we have to break cycles somewhere. Relying on the visited flag
78          * will result in nodes not being moved up despite their place_floats_early
79          * call.
80          * Instead we break cycles at pinned nodes which won't move anyway:
81          * This works because in firm each cycle contains a Phi or Block node
82          * (which are pinned)
83          */
84         if (get_irn_pinned(n) != op_pin_state_floats) {
85                 /* we can't move pinned nodes */
86                 arity = get_irn_arity(n);
87                 for (i = 0; i < arity; ++i) {
88                         ir_node *pred = get_irn_n(n, i);
89                         pdeq_putr(worklist, pred);
90                 }
91                 if (!is_Block(n))
92                         pdeq_putr(worklist, get_nodes_block(n));
93                 return;
94         }
95
96         block = get_nodes_block(n);
97
98         /* first move predecessors up */
99         arity = get_irn_arity(n);
100         place_floats_early(block, worklist);
101         for (i = 0; i < arity; ++i) {
102                 ir_node *pred = get_irn_n(n, i);
103                 place_floats_early(pred, worklist);
104         }
105
106         /* determine earliest point */
107         new_block = NULL;
108         new_depth = 0;
109         for (i = 0; i < arity; ++i) {
110                 ir_node *pred       = get_irn_n(n, i);
111                 ir_node *pred_block = get_nodes_block(pred);
112                 int      pred_depth = get_Block_dom_depth(pred_block);
113                 if (pred_depth > new_depth) {
114                         new_depth = pred_depth;
115                         new_block = pred_block;
116                 }
117         }
118
119         /* avoid moving nodes into the start block if we are not in the backend */
120         irg         = get_irn_irg(n);
121         start_block = get_irg_start_block(irg);
122         if (new_block == start_block && block != start_block &&
123             get_irg_phase_state(irg) != phase_backend) {
124                 assert(get_Block_n_cfg_outs(start_block) == 1);
125                 new_block = get_Block_cfg_out(start_block, 0);
126         }
127
128         /* Set the new block */
129         if (new_block != NULL)
130                 set_nodes_block(n, new_block);
131 }
132
133 /**
134  * Floating nodes form subgraphs that begin at nodes as Const, Load,
135  * Start, Call and that end at op_pin_state_pinned nodes as Store, Call.
136  * Place_early places all floating nodes reachable from its argument through
137  * floating nodes and adds all beginnings at op_pin_state_pinned nodes to the
138  * worklist.
139  *
140  * @param worklist   a worklist, used for the algorithm, empty on in/output
141  */
142 static void place_early(ir_graph *irg, waitq *worklist)
143 {
144         assert(worklist);
145         inc_irg_visited(irg);
146
147         /* this inits the worklist */
148         place_floats_early(get_irg_end(irg), worklist);
149
150         /* Work the content of the worklist. */
151         while (!waitq_empty(worklist)) {
152                 ir_node *n = (ir_node*)waitq_get(worklist);
153                 if (!irn_visited(n))
154                         place_floats_early(n, worklist);
155         }
156         set_irg_pinned(irg, op_pin_state_pinned);
157 }
158
159 /**
160  * Compute the deepest common dominator tree ancestor of block and dca.
161  *
162  * @param dca    the deepest common dominator tree ancestor so far,
163  *               might be NULL
164  * @param block  a block
165  *
166  * @return  the deepest common dominator tree ancestor of block and dca
167  */
168 static ir_node *calc_dom_dca(ir_node *dca, ir_node *block)
169 {
170         assert(block != NULL);
171
172         /* We found a first legal placement. */
173         if (!dca)
174                 return block;
175
176         /* Find a placement that is dominates both, dca and block. */
177         while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
178                 block = get_Block_idom(block);
179
180         while (get_Block_dom_depth(dca) > get_Block_dom_depth(block)) {
181                 dca = get_Block_idom(dca);
182         }
183
184         while (block != dca) {
185                 block = get_Block_idom(block); dca = get_Block_idom(dca);
186         }
187         return dca;
188 }
189
190 /**
191  * Deepest common dominance ancestor of DCA and CONSUMER of PRODUCER.
192  * I.e., DCA is the block where we might place PRODUCER.
193  * A data flow edge points from producer to consumer.
194  */
195 static ir_node *consumer_dom_dca(ir_node *dca, ir_node *consumer,
196                                  ir_node *producer)
197 {
198         /* Compute the last block into which we can place a node so that it is
199            before consumer. */
200         if (is_Phi(consumer)) {
201                 /* our consumer is a Phi-node, the effective use is in all those
202                    blocks through which the Phi-node reaches producer */
203                 ir_node *phi_block = get_nodes_block(consumer);
204                 int      arity     = get_irn_arity(consumer);
205                 int      i;
206
207                 for (i = 0;  i < arity; i++) {
208                         if (get_Phi_pred(consumer, i) == producer) {
209                                 ir_node *new_block = get_Block_cfgpred_block(phi_block, i);
210                                 if (is_Bad(new_block))
211                                         continue;
212
213                                 assert(is_block_reachable(new_block));
214                                 dca = calc_dom_dca(dca, new_block);
215                         }
216                 }
217         } else {
218                 dca = calc_dom_dca(dca, get_nodes_block(consumer));
219         }
220         return dca;
221 }
222
223 static inline int get_block_loop_depth(ir_node *block)
224 {
225         return get_loop_depth(get_irn_loop(block));
226 }
227
228 /**
229  * Move n to a block with less loop depth than its current block. The
230  * new block must be dominated by early.
231  *
232  * @param n      the node that should be moved
233  * @param early  the earliest block we can n move to
234  */
235 static void move_out_of_loops(ir_node *n, ir_node *early)
236 {
237         ir_node *block      = get_nodes_block(n);
238         ir_node *best       = block;
239         int      best_depth = get_block_loop_depth(best);
240
241         /* Find the region deepest in the dominator tree dominating
242            dca with the least loop nesting depth, but still dominated
243            by our early placement. */
244         while (block != early) {
245                 ir_node *idom       = get_Block_idom(block);
246                 int      idom_depth = get_block_loop_depth(idom);
247                 if (idom_depth < best_depth) {
248                         best       = idom;
249                         best_depth = idom_depth;
250                 }
251                 block = idom;
252         }
253         if (best != get_nodes_block(n))
254                 set_nodes_block(n, best);
255 }
256
257 /**
258  * Calculate the deepest common ancestor in the dominator tree of all nodes'
259  * blocks depending on node; our final placement has to dominate DCA.
260  *
261  * @param node  the definition node
262  * @param dca   the deepest common ancestor block so far, initially
263  *              NULL
264  *
265  * @return the deepest common dominator ancestor of all blocks of node's users
266  */
267 static ir_node *get_deepest_common_dom_ancestor(ir_node *node, ir_node *dca)
268 {
269         int i;
270
271         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
272                 ir_node *succ = get_irn_out(node, i);
273
274                 /* keepalive edges are special and don't respect the dominance */
275                 if (is_End(succ))
276                         continue;
277
278                 if (is_Proj(succ)) {
279                         /* Proj nodes are in the same block as node, so
280                          * the users of Proj are our users. */
281                         dca = get_deepest_common_dom_ancestor(succ, dca);
282                 } else {
283                         assert(is_block_reachable(get_nodes_block(succ)));
284                         dca = consumer_dom_dca(dca, succ, node);
285                 }
286         }
287         return dca;
288 }
289
290 /**
291  * Put all the Proj nodes of a node into a given block.
292  *
293  * @param node   the mode_T node
294  * @param block  the block to put the Proj nodes to
295  */
296 static void set_projs_block(ir_node *node, ir_node *block)
297 {
298         int i;
299
300         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
301                 ir_node *succ = get_irn_out(node, i);
302
303                 assert(is_Proj(succ));
304
305                 if (get_irn_mode(succ) == mode_T) {
306                         set_projs_block(succ, block);
307                 }
308                 set_nodes_block(succ, block);
309         }
310 }
311
312 /**
313  * Find the latest legal block for N and place N into the
314  * `optimal' Block between the latest and earliest legal block.
315  * The `optimal' block is the dominance-deepest block of those
316  * with the least loop-nesting-depth.  This places N out of as many
317  * loops as possible and then makes it as control dependent as
318  * possible.
319  */
320 static void place_floats_late(ir_node *n, pdeq *worklist)
321 {
322         int      n_outs;
323         int      i;
324         ir_node *block;
325         ir_node *dca;
326
327         if (irn_visited_else_mark(n))
328                 return;
329
330         n_outs = get_irn_n_outs(n);
331         /* break cycles at pinned nodes (see place place_floats_early) as to why */
332         if (get_irn_pinned(n) != op_pin_state_floats) {
333                 for (i = 0; i < n_outs; ++i) {
334                         ir_node *succ = get_irn_out(n, i);
335                         pdeq_putr(worklist, succ);
336                 }
337                 return;
338         }
339
340         /* place our users */
341         for (i = 0; i < n_outs; ++i) {
342                 ir_node *succ = get_irn_out(n, i);
343                 place_floats_late(succ, worklist);
344         }
345
346         /* no point in moving Projs around, they are moved with their predecessor */
347         if (is_Proj(n))
348                 return;
349         /* some nodes should simply stay in the startblock */
350         if (is_irn_start_block_placed(n)) {
351                 assert(get_nodes_block(n) == get_irg_start_block(get_irn_irg(n)));
352                 return;
353         }
354
355         block = get_nodes_block(n);
356         assert(is_block_reachable(block));
357
358         /* deepest common ancestor in the dominator tree of all nodes'
359            blocks depending on us; our final placement has to dominate
360            DCA. */
361         dca = get_deepest_common_dom_ancestor(n, NULL);
362         if (dca != NULL) {
363                 set_nodes_block(n, dca);
364                 move_out_of_loops(n, block);
365                 if (get_irn_mode(n) == mode_T) {
366                         set_projs_block(n, get_nodes_block(n));
367                 }
368         }
369 }
370
371 /**
372  * Place floating nodes on the given worklist as late as possible using
373  * the dominance tree.
374  *
375  * @param worklist   the worklist containing the nodes to place
376  */
377 static void place_late(ir_graph *irg, waitq *worklist)
378 {
379         assert(worklist);
380         inc_irg_visited(irg);
381
382         /* This fills the worklist initially. */
383         place_floats_late(get_irg_start_block(irg), worklist);
384
385         /* And now empty the worklist again... */
386         while (!waitq_empty(worklist)) {
387                 ir_node *n = (ir_node*)waitq_get(worklist);
388                 if (!irn_visited(n))
389                         place_floats_late(n, worklist);
390         }
391 }
392
393 /* Code Placement. */
394 void place_code(ir_graph *irg)
395 {
396         waitq *worklist;
397
398         /* Handle graph state */
399         assert(get_irg_phase_state(irg) != phase_building);
400         assure_irg_properties(irg,
401                 IR_GRAPH_PROPERTY_NO_CRITICAL_EDGES |
402                 IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE |
403                 IR_GRAPH_PROPERTY_CONSISTENT_OUTS |
404                 IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE |
405                 IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
406
407         /* Place all floating nodes as early as possible. This guarantees
408          a legal code placement. */
409         worklist = new_waitq();
410         place_early(irg, worklist);
411
412         /* While GCSE might place nodes in unreachable blocks,
413          * these are now placed in reachable blocks. */
414
415         /* Note: place_early changes only blocks, no data edges. So, the
416          * data out edges are still valid, no need to recalculate them here. */
417
418         /* Now move the nodes down in the dominator tree. This reduces the
419            unnecessary executions of the node. */
420         place_late(irg, worklist);
421
422         del_waitq(worklist);
423         confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_NONE);
424 }
425
426 /**
427  * Wrapper for place_code() inside the place_code pass.
428  */
429 static void place_code_wrapper(ir_graph *irg)
430 {
431         set_opt_global_cse(1);
432         optimize_graph_df(irg);
433         place_code(irg);
434         set_opt_global_cse(0);
435 }
436
437 ir_graph_pass_t *place_code_pass(const char *name)
438 {
439         return def_graph_pass(name ? name : "place", place_code_wrapper);
440 }