346b36f650ee0de6fa5a93cbc6dc5884b81e4647
[libfirm] / ir / ir / irgopt.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    Optimizations for a whole ir graph, i.e., a procedure.
23  * @author   Christian Schaefer, Goetz Lindenmaier, Sebastian Felis,
24  *           Michael Beck
25  * @version  $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <assert.h>
32
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "irprog_t.h"
36
37 #include "iroptimize.h"
38 #include "ircons_t.h"
39 #include "iropt_t.h"
40 #include "irgopt.h"
41 #include "irgmod.h"
42 #include "irgwalk.h"
43
44 #include "array.h"
45 #include "pset.h"
46 #include "pmap.h"
47 #include "pdeq.h"       /* Fuer code placement */
48 #include "xmalloc.h"
49
50 #include "irouts.h"
51 #include "irloop_t.h"
52 #include "irbackedge_t.h"
53 #include "cgana.h"
54 #include "trouts.h"
55
56
57 #include "irflag_t.h"
58 #include "irhooks.h"
59 #include "iredges_t.h"
60 #include "irtools.h"
61
62 /*------------------------------------------------------------------*/
63 /* apply optimizations of iropt to all nodes.                       */
64 /*------------------------------------------------------------------*/
65
66 /**
67  * A wrapper around optimize_inplace_2() to be called from a walker.
68  */
69 static void optimize_in_place_wrapper (ir_node *n, void *env) {
70         ir_node *optimized = optimize_in_place_2(n);
71         (void) env;
72
73         if (optimized != n) {
74                 exchange (n, optimized);
75         }
76 }
77
78 /**
79  * Do local optimizations for a node.
80  *
81  * @param n  the IR-node where to start. Typically the End node
82  *           of a graph
83  *
84  * @note current_ir_graph must be set
85  */
86 static INLINE void do_local_optimize(ir_node *n) {
87         /* Handle graph state */
88         assert(get_irg_phase_state(current_ir_graph) != phase_building);
89
90         if (get_opt_global_cse())
91         set_irg_pinned(current_ir_graph, op_pin_state_floats);
92         set_irg_outs_inconsistent(current_ir_graph);
93         set_irg_doms_inconsistent(current_ir_graph);
94         set_irg_loopinfo_inconsistent(current_ir_graph);
95
96         /* Clean the value_table in irg for the CSE. */
97         del_identities(current_ir_graph->value_table);
98         current_ir_graph->value_table = new_identities();
99
100         /* walk over the graph */
101         irg_walk(n, firm_clear_link, optimize_in_place_wrapper, NULL);
102 }
103
104 /* Applies local optimizations (see iropt.h) to all nodes reachable from node n */
105 void local_optimize_node(ir_node *n) {
106         ir_graph *rem = current_ir_graph;
107         current_ir_graph = get_irn_irg(n);
108
109         do_local_optimize(n);
110
111         current_ir_graph = rem;
112 }
113
114 /**
115  * Block-Walker: uses dominance depth to mark dead blocks.
116  */
117 static void kill_dead_blocks(ir_node *block, void *env) {
118         (void) env;
119
120         if (get_Block_dom_depth(block) < 0) {
121                 /*
122                  * Note that the new dominance code correctly handles
123                  * the End block, i.e. it is always reachable from Start
124                  */
125                 set_Block_dead(block);
126         }
127 }
128
129 /* Applies local optimizations (see iropt.h) to all nodes reachable from node n. */
130 void local_optimize_graph(ir_graph *irg) {
131         ir_graph *rem = current_ir_graph;
132         current_ir_graph = irg;
133
134         if (get_irg_dom_state(irg) == dom_consistent)
135                 irg_block_walk_graph(irg, NULL, kill_dead_blocks, NULL);
136
137         do_local_optimize(get_irg_end(irg));
138
139         current_ir_graph = rem;
140 }
141
142 /**
143  * Enqueue all users of a node to a wait queue.
144  * Handles mode_T nodes.
145  */
146 static void enqueue_users(ir_node *n, pdeq *waitq) {
147         const ir_edge_t *edge;
148
149         foreach_out_edge(n, edge) {
150                 ir_node *succ = get_edge_src_irn(edge);
151
152                 if (get_irn_link(succ) != waitq) {
153                         pdeq_putr(waitq, succ);
154                         set_irn_link(succ, waitq);
155                 }
156                 if (get_irn_mode(succ) == mode_T) {
157                 /* A mode_T node has Proj's. Because most optimizations
158                         run on the Proj's we have to enqueue them also. */
159                         enqueue_users(succ, waitq);
160                 }
161         }
162 }
163
164 /**
165  * Data flow optimization walker.
166  * Optimizes all nodes and enqueue it's users
167  * if done.
168  */
169 static void opt_walker(ir_node *n, void *env) {
170         pdeq *waitq = env;
171         ir_node *optimized;
172
173         optimized = optimize_in_place_2(n);
174         set_irn_link(optimized, NULL);
175
176         if (optimized != n) {
177                 enqueue_users(n, waitq);
178                 exchange(n, optimized);
179         }
180 }
181
182 /* Applies local optimizations to all nodes in the graph until fixpoint. */
183 void optimize_graph_df(ir_graph *irg) {
184         pdeq     *waitq = new_pdeq();
185         int      state = edges_activated(irg);
186         ir_graph *rem = current_ir_graph;
187         ir_node  *end;
188         int      i;
189
190         current_ir_graph = irg;
191
192         if (! state)
193                 edges_activate(irg);
194
195         if (get_opt_global_cse())
196                 set_irg_pinned(current_ir_graph, op_pin_state_floats);
197
198         /* Clean the value_table in irg for the CSE. */
199         del_identities(irg->value_table);
200         irg->value_table = new_identities();
201
202         if (get_irg_dom_state(irg) == dom_consistent)
203                 irg_block_walk_graph(irg, NULL, kill_dead_blocks, NULL);
204
205         /* invalidate info */
206         set_irg_outs_inconsistent(irg);
207         set_irg_doms_inconsistent(irg);
208         set_irg_loopinfo_inconsistent(irg);
209
210         set_using_irn_link(irg);
211
212         /* walk over the graph, but don't touch keep-alives */
213         irg_walk(get_irg_end_block(irg), NULL, opt_walker, waitq);
214
215         end = get_irg_end(irg);
216
217         /* optimize keep-alives by removing superfluous ones */
218         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
219                 ir_node *ka = get_End_keepalive(end, i);
220
221                 if (irn_visited(ka) && !is_irn_keep(ka)) {
222                         /* this node can be regularly visited, no need to keep it */
223                         set_End_keepalive(end, i, get_irg_bad(irg));
224                 }
225         }
226         /* now walk again and visit all not yet visited nodes */
227         set_irg_visited(current_ir_graph, get_irg_visited(irg) - 1);
228         irg_walk(get_irg_end(irg), NULL, opt_walker, waitq);
229
230         /* finish the wait queue */
231         while (! pdeq_empty(waitq)) {
232                 ir_node *n = pdeq_getl(waitq);
233                 if (! is_Bad(n))
234                         opt_walker(n, waitq);
235         }
236
237         del_pdeq(waitq);
238
239         clear_using_irn_link(irg);
240
241         if (! state)
242                 edges_deactivate(irg);
243
244         current_ir_graph = rem;
245 }
246
247
248 /*------------------------------------------------------------------*/
249 /* Routines for dead node elimination / copying garbage collection  */
250 /* of the obstack.                                                  */
251 /*------------------------------------------------------------------*/
252
253 /**
254  * Remember the new node in the old node by using a field all nodes have.
255  */
256 #define set_new_node(oldn, newn)  set_irn_link(oldn, newn)
257
258 /**
259  * Get this new node, before the old node is forgotten.
260  */
261 #define get_new_node(oldn) get_irn_link(oldn)
262
263 /**
264  * Check if a new node was set.
265  */
266 #define has_new_node(n) (get_new_node(n) != NULL)
267
268 /**
269  * We use the block_visited flag to mark that we have computed the
270  * number of useful predecessors for this block.
271  * Further we encode the new arity in this flag in the old blocks.
272  * Remembering the arity is useful, as it saves a lot of pointer
273  * accesses.  This function is called for all Phi and Block nodes
274  * in a Block.
275  */
276 static INLINE int
277 compute_new_arity(ir_node *b) {
278         int i, res, irn_arity;
279         int irg_v, block_v;
280
281         irg_v = get_irg_block_visited(current_ir_graph);
282         block_v = get_Block_block_visited(b);
283         if (block_v >= irg_v) {
284                 /* we computed the number of preds for this block and saved it in the
285                    block_v flag */
286                 return block_v - irg_v;
287         } else {
288                 /* compute the number of good predecessors */
289                 res = irn_arity = get_irn_arity(b);
290                 for (i = 0; i < irn_arity; i++)
291                         if (get_irn_opcode(get_irn_n(b, i)) == iro_Bad) res--;
292                         /* save it in the flag. */
293                         set_Block_block_visited(b, irg_v + res);
294                         return res;
295         }
296 }
297
298 /**
299  * Copies the node to the new obstack. The Ins of the new node point to
300  * the predecessors on the old obstack.  For block/phi nodes not all
301  * predecessors might be copied.  n->link points to the new node.
302  * For Phi and Block nodes the function allocates in-arrays with an arity
303  * only for useful predecessors.  The arity is determined by counting
304  * the non-bad predecessors of the block.
305  *
306  * @param n    The node to be copied
307  * @param env  if non-NULL, the node number attribute will be copied to the new node
308  *
309  * Note: Also used for loop unrolling.
310  */
311 static void copy_node(ir_node *n, void *env) {
312         ir_node *nn, *block;
313         int new_arity;
314         ir_op *op = get_irn_op(n);
315
316         /* The end node looses it's flexible in array.  This doesn't matter,
317            as dead node elimination builds End by hand, inlineing doesn't use
318            the End node. */
319         /* assert(op == op_End ||  ((_ARR_DESCR(n->in))->cookie != ARR_F_MAGIC)); */
320
321         if (op == op_Bad) {
322                 /* node copied already */
323                 return;
324         } else if (op == op_Block) {
325                 block = NULL;
326                 new_arity = compute_new_arity(n);
327                 n->attr.block.graph_arr = NULL;
328         } else {
329                 block = get_nodes_block(n);
330                 if (op == op_Phi) {
331                         new_arity = compute_new_arity(block);
332                 } else {
333                         new_arity = get_irn_arity(n);
334                 }
335         }
336         nn = new_ir_node(get_irn_dbg_info(n),
337                 current_ir_graph,
338                 block,
339                 op,
340                 get_irn_mode(n),
341                 new_arity,
342                 get_irn_in(n) + 1);
343                 /* Copy the attributes.  These might point to additional data.  If this
344                 was allocated on the old obstack the pointers now are dangling.  This
345         frees e.g. the memory of the graph_arr allocated in new_immBlock. */
346         copy_node_attr(n, nn);
347
348 #ifdef DEBUG_libfirm
349         {
350                 int copy_node_nr = env != NULL;
351                 if (copy_node_nr) {
352                         /* for easier debugging, we want to copy the node numbers too */
353                         nn->node_nr = n->node_nr;
354                 }
355         }
356 #endif
357
358         set_new_node(n, nn);
359         hook_dead_node_elim_subst(current_ir_graph, n, nn);
360 }
361
362 /**
363  * Copies new predecessors of old node to new node remembered in link.
364  * Spare the Bad predecessors of Phi and Block nodes.
365  */
366 static void copy_preds(ir_node *n, void *env) {
367         ir_node *nn, *block;
368         int i, j, irn_arity;
369         (void) env;
370
371         nn = get_new_node(n);
372
373         if (is_Block(n)) {
374                 /* copy the macro block header */
375                 ir_node *mbh = get_Block_MacroBlock(n);
376
377                 if (! is_Bad(mbh))
378                         set_irn_n(nn, -1, get_new_node(mbh));
379
380                 /* Don't copy Bad nodes. */
381                 j = 0;
382                 irn_arity = get_irn_arity(n);
383                 for (i = 0; i < irn_arity; i++) {
384                         if (! is_Bad(get_irn_n(n, i))) {
385                                 set_irn_n(nn, j, get_new_node(get_irn_n(n, i)));
386                                 /*if (is_backedge(n, i)) set_backedge(nn, j);*/
387                                 j++;
388                         }
389                 }
390                 /* repair the block visited flag from above misuse. Repair it in both
391                    graphs so that the old one can still be used. */
392                 set_Block_block_visited(nn, 0);
393                 set_Block_block_visited(n, 0);
394                 /* Local optimization could not merge two subsequent blocks if
395                    in array contained Bads.  Now it's possible.
396                    We don't call optimize_in_place as it requires
397                    that the fields in ir_graph are set properly. */
398                 if ((get_opt_control_flow_straightening()) &&
399                         (get_Block_n_cfgpreds(nn) == 1) &&
400                         (get_irn_op(get_Block_cfgpred(nn, 0)) == op_Jmp)) {
401                         ir_node *old = get_nodes_block(get_Block_cfgpred(nn, 0));
402                         if (nn == old) {
403                                 /* Jmp jumps into the block it is in -- deal self cycle. */
404                                 assert(is_Bad(get_new_node(get_irg_bad(current_ir_graph))));
405                                 exchange(nn, get_new_node(get_irg_bad(current_ir_graph)));
406                         } else {
407                                 exchange(nn, old);
408                         }
409                 }
410         } else if (is_Phi(n)) {
411                 /* Don't copy node if corresponding predecessor in block is Bad.
412                    The Block itself should not be Bad. */
413                 block = get_nodes_block(n);
414                 set_irn_n(nn, -1, get_new_node(block));
415                 j = 0;
416                 irn_arity = get_irn_arity(n);
417                 for (i = 0; i < irn_arity; i++) {
418                         if (! is_Bad(get_irn_n(block, i))) {
419                                 set_irn_n(nn, j, get_new_node(get_irn_n(n, i)));
420                                 /*if (is_backedge(n, i)) set_backedge(nn, j);*/
421                                 j++;
422                         }
423                 }
424                 /* If the pre walker reached this Phi after the post walker visited the
425                    block block_visited is > 0. */
426                 set_Block_block_visited(get_nodes_block(n), 0);
427                 /* Compacting the Phi's ins might generate Phis with only one
428                    predecessor. */
429                 if (get_irn_arity(nn) == 1)
430                         exchange(nn, get_irn_n(nn, 0));
431         } else {
432                 irn_arity = get_irn_arity(n);
433                 for (i = -1; i < irn_arity; i++)
434                         set_irn_n (nn, i, get_new_node(get_irn_n(n, i)));
435         }
436         /* Now the new node is complete.  We can add it to the hash table for CSE.
437            @@@ inlining aborts if we identify End. Why? */
438         if (get_irn_op(nn) != op_End)
439                 add_identities(current_ir_graph->value_table, nn);
440 }
441
442 /**
443  * Copies the graph recursively, compacts the keep-alives of the end node.
444  *
445  * @param irg           the graph to be copied
446  * @param copy_node_nr  If non-zero, the node number will be copied
447  */
448 static void copy_graph(ir_graph *irg, int copy_node_nr) {
449         ir_node *oe, *ne, *ob, *nb, *om, *nm; /* old end, new end, old bad, new bad, old NoMem, new NoMem */
450         ir_node *ka;      /* keep alive */
451         int i, irn_arity;
452         unsigned long vfl;
453
454         /* Some nodes must be copied by hand, sigh */
455         vfl = get_irg_visited(irg);
456         set_irg_visited(irg, vfl + 1);
457
458         oe = get_irg_end(irg);
459         mark_irn_visited(oe);
460         /* copy the end node by hand, allocate dynamic in array! */
461         ne = new_ir_node(get_irn_dbg_info(oe),
462                 irg,
463                 NULL,
464                 op_End,
465                 mode_X,
466                 -1,
467                 NULL);
468         /* Copy the attributes.  Well, there might be some in the future... */
469         copy_node_attr(oe, ne);
470         set_new_node(oe, ne);
471
472         /* copy the Bad node */
473         ob = get_irg_bad(irg);
474         mark_irn_visited(ob);
475         nb = new_ir_node(get_irn_dbg_info(ob),
476                 irg,
477                 NULL,
478                 op_Bad,
479                 mode_T,
480                 0,
481                 NULL);
482         copy_node_attr(ob, nb);
483         set_new_node(ob, nb);
484
485         /* copy the NoMem node */
486         om = get_irg_no_mem(irg);
487         mark_irn_visited(om);
488         nm = new_ir_node(get_irn_dbg_info(om),
489                 irg,
490                 NULL,
491                 op_NoMem,
492                 mode_M,
493                 0,
494                 NULL);
495         copy_node_attr(om, nm);
496         set_new_node(om, nm);
497
498         /* copy the live nodes */
499         set_irg_visited(irg, vfl);
500         irg_walk(get_nodes_block(oe), copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
501
502         /* Note: from yet, the visited flag of the graph is equal to vfl + 1 */
503
504         /* visit the anchors as well */
505         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
506                 ir_node *n = get_irg_anchor(irg, i);
507
508                 if (n && (get_irn_visited(n) <= vfl)) {
509                         set_irg_visited(irg, vfl);
510                         irg_walk(n, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
511                 }
512         }
513
514         /* copy_preds for the end node ... */
515         set_nodes_block(ne, get_new_node(get_nodes_block(oe)));
516
517         /*- ... and now the keep alives. -*/
518         /* First pick the not marked block nodes and walk them.  We must pick these
519            first as else we will oversee blocks reachable from Phis. */
520         irn_arity = get_End_n_keepalives(oe);
521         for (i = 0; i < irn_arity; i++) {
522                 ka = get_End_keepalive(oe, i);
523                 if (is_Block(ka)) {
524                         if (get_irn_visited(ka) <= vfl) {
525                                 /* We must keep the block alive and copy everything reachable */
526                                 set_irg_visited(irg, vfl);
527                                 irg_walk(ka, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
528                         }
529                         add_End_keepalive(ne, get_new_node(ka));
530                 }
531         }
532
533         /* Now pick other nodes.  Here we will keep all! */
534         irn_arity = get_End_n_keepalives(oe);
535         for (i = 0; i < irn_arity; i++) {
536                 ka = get_End_keepalive(oe, i);
537                 if (!is_Block(ka)) {
538                         if (get_irn_visited(ka) <= vfl) {
539                                 /* We didn't copy the node yet.  */
540                                 set_irg_visited(irg, vfl);
541                                 irg_walk(ka, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
542                         }
543                         add_End_keepalive(ne, get_new_node(ka));
544                 }
545         }
546
547         /* start block sometimes only reached after keep alives */
548         set_nodes_block(nb, get_new_node(get_nodes_block(ob)));
549         set_nodes_block(nm, get_new_node(get_nodes_block(om)));
550 }
551
552 /**
553  * Copies the graph reachable from current_ir_graph->end to the obstack
554  * in current_ir_graph and fixes the environment.
555  * Then fixes the fields in current_ir_graph containing nodes of the
556  * graph.
557  *
558  * @param copy_node_nr  If non-zero, the node number will be copied
559  */
560 static void
561 copy_graph_env(int copy_node_nr) {
562         ir_graph *irg = current_ir_graph;
563         ir_node *old_end, *new_anchor;
564         int i;
565
566         /* remove end_except and end_reg nodes */
567         old_end = get_irg_end(irg);
568         set_irg_end_except (irg, old_end);
569         set_irg_end_reg    (irg, old_end);
570
571         /* Not all nodes remembered in irg might be reachable
572            from the end node.  Assure their link is set to NULL, so that
573            we can test whether new nodes have been computed. */
574         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
575                 ir_node *n = get_irg_anchor(irg, i);
576                 if (n != NULL)
577                         set_new_node(n, NULL);
578         }
579         /* we use the block walk flag for removing Bads from Blocks ins. */
580         inc_irg_block_visited(irg);
581
582         /* copy the graph */
583         copy_graph(irg, copy_node_nr);
584
585         /* fix the anchor */
586         old_end    = get_irg_end(irg);
587         new_anchor = new_Anchor(irg);
588
589         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
590                 ir_node *n = get_irg_anchor(irg, i);
591                 if (n)
592                         set_irn_n(new_anchor, i, get_new_node(n));
593         }
594         free_End(old_end);
595         irg->anchor = new_anchor;
596
597         /* ensure the new anchor is placed in the endblock */
598         set_irn_n(new_anchor, -1, get_irg_end_block(irg));
599 }
600
601 /**
602  * Copies all reachable nodes to a new obstack.  Removes bad inputs
603  * from block nodes and the corresponding inputs from Phi nodes.
604  * Merges single exit blocks with single entry blocks and removes
605  * 1-input Phis.
606  * Adds all new nodes to a new hash table for CSE.  Does not
607  * perform CSE, so the hash table might contain common subexpressions.
608  */
609 void
610 dead_node_elimination(ir_graph *irg) {
611         if (get_opt_optimize() && get_opt_dead_node_elimination()) {
612                 ir_graph *rem;
613                 int rem_ipview = get_interprocedural_view();
614                 struct obstack *graveyard_obst = NULL;
615                 struct obstack *rebirth_obst   = NULL;
616                 assert(! edges_activated(irg) && "dead node elimination requires disabled edges");
617
618                 /* inform statistics that we started a dead-node elimination run */
619                 hook_dead_node_elim(irg, 1);
620
621                 /* Remember external state of current_ir_graph. */
622                 rem = current_ir_graph;
623                 current_ir_graph = irg;
624                 set_interprocedural_view(0);
625
626                 assert(get_irg_phase_state(irg) != phase_building);
627
628                 /* Handle graph state */
629                 free_callee_info(irg);
630                 free_irg_outs(irg);
631                 free_trouts();
632
633                 /* @@@ so far we loose loops when copying */
634                 free_loop_information(irg);
635
636                 set_irg_doms_inconsistent(irg);
637
638                 /* A quiet place, where the old obstack can rest in peace,
639                    until it will be cremated. */
640                 graveyard_obst = irg->obst;
641
642                 /* A new obstack, where the reachable nodes will be copied to. */
643                 rebirth_obst = xmalloc(sizeof(*rebirth_obst));
644                 irg->obst = rebirth_obst;
645                 obstack_init(irg->obst);
646                 irg->last_node_idx = 0;
647
648                 /* We also need a new value table for CSE */
649                 del_identities(irg->value_table);
650                 irg->value_table = new_identities();
651
652                 /* Copy the graph from the old to the new obstack */
653                 copy_graph_env(/*copy_node_nr=*/1);
654
655                 /* Free memory from old unoptimized obstack */
656                 obstack_free(graveyard_obst, 0);  /* First empty the obstack ... */
657                 xfree (graveyard_obst);           /* ... then free it.           */
658
659                 /* inform statistics that the run is over */
660                 hook_dead_node_elim(irg, 0);
661
662                 current_ir_graph = rem;
663                 set_interprocedural_view(rem_ipview);
664         }
665 }
666
667 /**
668  * Relink bad predecessors of a block and store the old in array to the
669  * link field. This function is called by relink_bad_predecessors().
670  * The array of link field starts with the block operand at position 0.
671  * If block has bad predecessors, create a new in array without bad preds.
672  * Otherwise let in array untouched.
673  */
674 static void relink_bad_block_predecessors(ir_node *n, void *env) {
675         ir_node **new_in, *irn;
676         int i, new_irn_n, old_irn_arity, new_irn_arity = 0;
677         (void) env;
678
679         /* if link field of block is NULL, look for bad predecessors otherwise
680            this is already done */
681         if (get_irn_op(n) == op_Block &&
682                 get_irn_link(n) == NULL) {
683
684                 /* save old predecessors in link field (position 0 is the block operand)*/
685                 set_irn_link(n, get_irn_in(n));
686
687                 /* count predecessors without bad nodes */
688                 old_irn_arity = get_irn_arity(n);
689                 for (i = 0; i < old_irn_arity; i++)
690                         if (!is_Bad(get_irn_n(n, i))) new_irn_arity++;
691
692                         /* arity changing: set new predecessors without bad nodes */
693                         if (new_irn_arity < old_irn_arity) {
694                                 /* Get new predecessor array. We do not resize the array, as we must
695                                    keep the old one to update Phis. */
696                                 new_in = NEW_ARR_D (ir_node *, current_ir_graph->obst, (new_irn_arity+1));
697
698                                 /* set new predecessors in array */
699                                 new_in[0] = NULL;
700                                 new_irn_n = 1;
701                                 for (i = 0; i < old_irn_arity; i++) {
702                                         irn = get_irn_n(n, i);
703                                         if (!is_Bad(irn)) {
704                                                 new_in[new_irn_n] = irn;
705                                                 is_backedge(n, i) ? set_backedge(n, new_irn_n-1) : set_not_backedge(n, new_irn_n-1);
706                                                 ++new_irn_n;
707                                         }
708                                 }
709                                 /* ARR_SETLEN(int, n->attr.block.backedge, new_irn_arity); */
710                                 ARR_SHRINKLEN(n->attr.block.backedge, new_irn_arity);
711                                 n->in = new_in;
712                         } /* ir node has bad predecessors */
713         } /* Block is not relinked */
714 }
715
716 /**
717  * Relinks Bad predecessors from Blocks and Phis called by walker
718  * remove_bad_predecesors(). If n is a Block, call
719  * relink_bad_block_redecessors(). If n is a Phi-node, call also the relinking
720  * function of Phi's Block. If this block has bad predecessors, relink preds
721  * of the Phi-node.
722  */
723 static void relink_bad_predecessors(ir_node *n, void *env) {
724         ir_node *block, **old_in;
725         int i, old_irn_arity, new_irn_arity;
726
727         /* relink bad predecessors of a block */
728         if (get_irn_op(n) == op_Block)
729                 relink_bad_block_predecessors(n, env);
730
731         /* If Phi node relink its block and its predecessors */
732         if (get_irn_op(n) == op_Phi) {
733
734                 /* Relink predecessors of phi's block */
735                 block = get_nodes_block(n);
736                 if (get_irn_link(block) == NULL)
737                         relink_bad_block_predecessors(block, env);
738
739                 old_in = (ir_node **)get_irn_link(block); /* Of Phi's Block */
740                 old_irn_arity = ARR_LEN(old_in);
741
742                 /* Relink Phi predecessors if count of predecessors changed */
743                 if (old_irn_arity != ARR_LEN(get_irn_in(block))) {
744                         /* set new predecessors in array
745                            n->in[0] remains the same block */
746                         new_irn_arity = 1;
747                         for(i = 1; i < old_irn_arity; i++)
748                                 if (!is_Bad((ir_node *)old_in[i])) {
749                                         n->in[new_irn_arity] = n->in[i];
750                                         is_backedge(n, i) ? set_backedge(n, new_irn_arity) : set_not_backedge(n, new_irn_arity);
751                                         ++new_irn_arity;
752                                 }
753
754                                 ARR_SETLEN(ir_node *, n->in, new_irn_arity);
755                                 ARR_SETLEN(int, n->attr.phi_backedge, new_irn_arity);
756                 }
757         } /* n is a Phi node */
758 }
759
760 /*
761  * Removes Bad Bad predecessors from Blocks and the corresponding
762  * inputs to Phi nodes as in dead_node_elimination but without
763  * copying the graph.
764  * On walking up set the link field to NULL, on walking down call
765  * relink_bad_predecessors() (This function stores the old in array
766  * to the link field and sets a new in array if arity of predecessors
767  * changes).
768  */
769 void remove_bad_predecessors(ir_graph *irg) {
770         irg_walk_graph(irg, firm_clear_link, relink_bad_predecessors, NULL);
771 }
772
773
774 /*
775    __                      _  __ __
776   (_     __    o     _    | \/  |_
777   __)|_| | \_/ | \_/(/_   |_/\__|__
778
779   The following stuff implements a facility that automatically patches
780   registered ir_node pointers to the new node when a dead node elimination occurs.
781 */
782
783 struct _survive_dce_t {
784         struct obstack obst;
785         pmap *places;
786         pmap *new_places;
787         hook_entry_t dead_node_elim;
788         hook_entry_t dead_node_elim_subst;
789 };
790
791 typedef struct _survive_dce_list_t {
792         struct _survive_dce_list_t *next;
793         ir_node **place;
794 } survive_dce_list_t;
795
796 static void dead_node_hook(void *context, ir_graph *irg, int start) {
797         survive_dce_t *sd = context;
798         (void) irg;
799
800         /* Create a new map before the dead node elimination is performed. */
801         if (start) {
802                 sd->new_places = pmap_create_ex(pmap_count(sd->places));
803         } else {
804                 /* Patch back all nodes if dead node elimination is over and something is to be done. */
805                 pmap_destroy(sd->places);
806                 sd->places     = sd->new_places;
807                 sd->new_places = NULL;
808         }
809 }
810
811 /**
812  * Hook called when dead node elimination replaces old by nw.
813  */
814 static void dead_node_subst_hook(void *context, ir_graph *irg, ir_node *old, ir_node *nw) {
815         survive_dce_t *sd = context;
816         survive_dce_list_t *list = pmap_get(sd->places, old);
817         (void) irg;
818
819         /* If the node is to be patched back, write the new address to all registered locations. */
820         if (list) {
821                 survive_dce_list_t *p;
822
823                 for (p = list; p; p = p->next)
824                         *(p->place) = nw;
825
826                 pmap_insert(sd->new_places, nw, list);
827         }
828 }
829
830 /**
831  * Make a new Survive DCE environment.
832  */
833 survive_dce_t *new_survive_dce(void) {
834         survive_dce_t *res = xmalloc(sizeof(res[0]));
835         obstack_init(&res->obst);
836         res->places     = pmap_create();
837         res->new_places = NULL;
838
839         res->dead_node_elim.hook._hook_dead_node_elim = dead_node_hook;
840         res->dead_node_elim.context                   = res;
841         res->dead_node_elim.next                      = NULL;
842
843         res->dead_node_elim_subst.hook._hook_dead_node_elim_subst = dead_node_subst_hook;
844         res->dead_node_elim_subst.context = res;
845         res->dead_node_elim_subst.next    = NULL;
846
847 #ifndef FIRM_ENABLE_HOOKS
848         assert(0 && "need hooks enabled");
849 #endif
850
851         register_hook(hook_dead_node_elim, &res->dead_node_elim);
852         register_hook(hook_dead_node_elim_subst, &res->dead_node_elim_subst);
853         return res;
854 }
855
856 /**
857  * Free a Survive DCE environment.
858  */
859 void free_survive_dce(survive_dce_t *sd) {
860         obstack_free(&sd->obst, NULL);
861         pmap_destroy(sd->places);
862         unregister_hook(hook_dead_node_elim, &sd->dead_node_elim);
863         unregister_hook(hook_dead_node_elim_subst, &sd->dead_node_elim_subst);
864         xfree(sd);
865 }
866
867 /**
868  * Register a node pointer to be patched upon DCE.
869  * When DCE occurs, the node pointer specified by @p place will be
870  * patched to the new address of the node it is pointing to.
871  *
872  * @param sd    The Survive DCE environment.
873  * @param place The address of the node pointer.
874  */
875 void survive_dce_register_irn(survive_dce_t *sd, ir_node **place) {
876         if (*place != NULL) {
877                 ir_node *irn      = *place;
878                 survive_dce_list_t *curr = pmap_get(sd->places, irn);
879                 survive_dce_list_t *nw   = obstack_alloc(&sd->obst, sizeof(nw[0]));
880
881                 nw->next  = curr;
882                 nw->place = place;
883
884                 pmap_insert(sd->places, irn, nw);
885         }
886 }
887
888 /*--------------------------------------------------------------------*/
889 /*  Functionality for inlining                                         */
890 /*--------------------------------------------------------------------*/
891
892 /**
893  * Copy node for inlineing.  Updates attributes that change when
894  * inlineing but not for dead node elimination.
895  *
896  * Copies the node by calling copy_node() and then updates the entity if
897  * it's a local one.  env must be a pointer of the frame type of the
898  * inlined procedure. The new entities must be in the link field of
899  * the entities.
900  */
901 static INLINE void
902 copy_node_inline(ir_node *n, void *env) {
903         ir_node *nn;
904         ir_type *frame_tp = (ir_type *)env;
905
906         copy_node(n, NULL);
907         if (get_irn_op(n) == op_Sel) {
908                 nn = get_new_node (n);
909                 assert(is_Sel(nn));
910                 if (get_entity_owner(get_Sel_entity(n)) == frame_tp) {
911                         set_Sel_entity(nn, get_entity_link(get_Sel_entity(n)));
912                 }
913         } else if (get_irn_op(n) == op_Block) {
914                 nn = get_new_node (n);
915                 nn->attr.block.irg = current_ir_graph;
916         }
917 }
918
919 /**
920  * Walker: checks if P_value_arg_base is used.
921  */
922 static void find_addr(ir_node *node, void *env) {
923         int *allow_inline = env;
924         if (is_Proj(node) && get_irn_op(get_Proj_pred(node)) == op_Start) {
925                 if (get_Proj_proj(node) == pn_Start_P_value_arg_base)
926                         *allow_inline = 0;
927         }
928 }
929
930 /**
931  * Check if we can inline a given call.
932  * Currently, we cannot inline two cases:
933  * - call with compound arguments
934  * - graphs that take the address of a parameter
935  *
936  * check these conditions here
937  */
938 static int can_inline(ir_node *call, ir_graph *called_graph) {
939         ir_type *call_type = get_Call_type(call);
940         int params, ress, i, res;
941         assert(is_Method_type(call_type));
942
943         params = get_method_n_params(call_type);
944         ress   = get_method_n_ress(call_type);
945
946         /* check parameters for compound arguments */
947         for (i = 0; i < params; ++i) {
948                 ir_type *p_type = get_method_param_type(call_type, i);
949
950                 if (is_compound_type(p_type))
951                         return 0;
952         }
953
954         /* check results for compound arguments */
955         for (i = 0; i < ress; ++i) {
956                 ir_type *r_type = get_method_res_type(call_type, i);
957
958                 if (is_compound_type(r_type))
959                         return 0;
960         }
961
962         res = 1;
963         irg_walk_graph(called_graph, find_addr, NULL, &res);
964
965         return res;
966 }
967
968 enum exc_mode {
969            exc_handler    = 0, /**< There is a handler. */
970            exc_to_end     = 1, /**< Branches to End. */
971            exc_no_handler = 2  /**< Exception handling not represented. */
972 };
973
974 /* Inlines a method at the given call site. */
975 int inline_method(ir_node *call, ir_graph *called_graph) {
976         ir_node *pre_call;
977         ir_node *post_call, *post_bl;
978         ir_node *in[pn_Start_max];
979         ir_node *end, *end_bl;
980         ir_node **res_pred;
981         ir_node **cf_pred;
982         ir_node *ret, *phi;
983         int arity, n_ret, n_exc, n_res, i, j, rem_opt, irn_arity;
984         enum exc_mode exc_handling;
985         ir_type *called_frame;
986         irg_inline_property prop = get_irg_inline_property(called_graph);
987
988         if ( (prop < irg_inline_forced) &&
989              (!get_opt_optimize() || !get_opt_inline() || (prop == irg_inline_forbidden))) return 0;
990
991         /* Do not inline variadic functions. */
992         if (get_method_variadicity(get_entity_type(get_irg_entity(called_graph))) == variadicity_variadic)
993                 return 0;
994
995         assert(get_method_n_params(get_entity_type(get_irg_entity(called_graph))) ==
996                get_method_n_params(get_Call_type(call)));
997
998         /*
999          * currently, we cannot inline two cases:
1000          * - call with compound arguments
1001          * - graphs that take the address of a parameter
1002          */
1003         if (! can_inline(call, called_graph))
1004                 return 0;
1005
1006         /* --  Turn off optimizations, this can cause problems when allocating new nodes. -- */
1007         rem_opt = get_opt_optimize();
1008         set_optimize(0);
1009
1010         /* Handle graph state */
1011         assert(get_irg_phase_state(current_ir_graph) != phase_building);
1012         assert(get_irg_pinned(current_ir_graph) == op_pin_state_pinned);
1013         assert(get_irg_pinned(called_graph) == op_pin_state_pinned);
1014         set_irg_outs_inconsistent(current_ir_graph);
1015         set_irg_extblk_inconsistent(current_ir_graph);
1016         set_irg_doms_inconsistent(current_ir_graph);
1017         set_irg_loopinfo_inconsistent(current_ir_graph);
1018         set_irg_callee_info_state(current_ir_graph, irg_callee_info_inconsistent);
1019
1020         /* -- Check preconditions -- */
1021         assert(is_Call(call));
1022         /* @@@ does not work for InterfaceIII.java after cgana
1023          assert(get_Call_type(call) == get_entity_type(get_irg_entity(called_graph)));
1024          assert(smaller_type(get_entity_type(get_irg_entity(called_graph)),
1025          get_Call_type(call)));
1026         */
1027         if (called_graph == current_ir_graph) {
1028                 set_optimize(rem_opt);
1029                 return 0;
1030         }
1031
1032         /* here we know we WILL inline, so inform the statistics */
1033         hook_inline(call, called_graph);
1034
1035         /* -- Decide how to handle exception control flow: Is there a handler
1036            for the Call node, or do we branch directly to End on an exception?
1037            exc_handling:
1038            0 There is a handler.
1039            1 Branches to End.
1040            2 Exception handling not represented in Firm. -- */
1041         {
1042                 ir_node *proj, *Mproj = NULL, *Xproj = NULL;
1043                 for (proj = get_irn_link(call); proj; proj = get_irn_link(proj)) {
1044                         long proj_nr = get_Proj_proj(proj);
1045                         if (proj_nr == pn_Call_X_except) Xproj = proj;
1046                         if (proj_nr == pn_Call_M_except) Mproj = proj;
1047                 }
1048                 if      (Mproj) { assert(Xproj); exc_handling = exc_handler; } /*  Mproj           */
1049                 else if (Xproj) {                exc_handling = exc_to_end; } /* !Mproj &&  Xproj   */
1050                 else            {                exc_handling = exc_no_handler; } /* !Mproj && !Xproj   */
1051         }
1052
1053         /* --
1054            the procedure and later replaces the Start node of the called graph.
1055            Post_call is the old Call node and collects the results of the called
1056            graph. Both will end up being a tuple.  -- */
1057         post_bl = get_nodes_block(call);
1058         set_irg_current_block(current_ir_graph, post_bl);
1059         /* XxMxPxPxPxT of Start + parameter of Call */
1060         in[pn_Start_X_initial_exec]   = new_Jmp();
1061         in[pn_Start_M]                = get_Call_mem(call);
1062         in[pn_Start_P_frame_base]     = get_irg_frame(current_ir_graph);
1063         in[pn_Start_P_globals]        = get_irg_globals(current_ir_graph);
1064         in[pn_Start_P_tls]            = get_irg_tls(current_ir_graph);
1065         in[pn_Start_T_args]           = new_Tuple(get_Call_n_params(call), get_Call_param_arr(call));
1066         /* in[pn_Start_P_value_arg_base] = ??? */
1067         assert(pn_Start_P_value_arg_base == pn_Start_max - 1 && "pn_Start_P_value_arg_base not supported, fix");
1068         pre_call = new_Tuple(pn_Start_max - 1, in);
1069         post_call = call;
1070
1071         /* --
1072            The new block gets the ins of the old block, pre_call and all its
1073            predecessors and all Phi nodes. -- */
1074         part_block(pre_call);
1075
1076         /* -- Prepare state for dead node elimination -- */
1077         /* Visited flags in calling irg must be >= flag in called irg.
1078            Else walker and arity computation will not work. */
1079         if (get_irg_visited(current_ir_graph) <= get_irg_visited(called_graph))
1080                 set_irg_visited(current_ir_graph, get_irg_visited(called_graph)+1);
1081         if (get_irg_block_visited(current_ir_graph)< get_irg_block_visited(called_graph))
1082                 set_irg_block_visited(current_ir_graph, get_irg_block_visited(called_graph));
1083         /* Set pre_call as new Start node in link field of the start node of
1084            calling graph and pre_calls block as new block for the start block
1085            of calling graph.
1086            Further mark these nodes so that they are not visited by the
1087            copying. */
1088         set_irn_link(get_irg_start(called_graph), pre_call);
1089         set_irn_visited(get_irg_start(called_graph), get_irg_visited(current_ir_graph));
1090         set_irn_link(get_irg_start_block(called_graph), get_nodes_block(pre_call));
1091         set_irn_visited(get_irg_start_block(called_graph), get_irg_visited(current_ir_graph));
1092         set_irn_link(get_irg_bad(called_graph), get_irg_bad(current_ir_graph));
1093         set_irn_visited(get_irg_bad(called_graph), get_irg_visited(current_ir_graph));
1094
1095         /* Initialize for compaction of in arrays */
1096         inc_irg_block_visited(current_ir_graph);
1097
1098         /* -- Replicate local entities of the called_graph -- */
1099         /* copy the entities. */
1100         called_frame = get_irg_frame_type(called_graph);
1101         for (i = 0; i < get_class_n_members(called_frame); i++) {
1102                 ir_entity *new_ent, *old_ent;
1103                 old_ent = get_class_member(called_frame, i);
1104                 new_ent = copy_entity_own(old_ent, get_cur_frame_type());
1105                 set_entity_link(old_ent, new_ent);
1106         }
1107
1108         /* visited is > than that of called graph.  With this trick visited will
1109            remain unchanged so that an outer walker, e.g., searching the call nodes
1110             to inline, calling this inline will not visit the inlined nodes. */
1111         set_irg_visited(current_ir_graph, get_irg_visited(current_ir_graph)-1);
1112
1113         /* -- Performing dead node elimination inlines the graph -- */
1114         /* Copies the nodes to the obstack of current_ir_graph. Updates links to new
1115            entities. */
1116         irg_walk(get_irg_end(called_graph), copy_node_inline, copy_preds,
1117                  get_irg_frame_type(called_graph));
1118
1119         /* Repair called_graph */
1120         set_irg_visited(called_graph, get_irg_visited(current_ir_graph));
1121         set_irg_block_visited(called_graph, get_irg_block_visited(current_ir_graph));
1122         set_Block_block_visited(get_irg_start_block(called_graph), 0);
1123
1124         /* -- Merge the end of the inlined procedure with the call site -- */
1125         /* We will turn the old Call node into a Tuple with the following
1126            predecessors:
1127            -1:  Block of Tuple.
1128            0: Phi of all Memories of Return statements.
1129            1: Jmp from new Block that merges the control flow from all exception
1130            predecessors of the old end block.
1131            2: Tuple of all arguments.
1132            3: Phi of Exception memories.
1133            In case the old Call directly branches to End on an exception we don't
1134            need the block merging all exceptions nor the Phi of the exception
1135            memories.
1136         */
1137
1138         /* -- Precompute some values -- */
1139         end_bl = get_new_node(get_irg_end_block(called_graph));
1140         end = get_new_node(get_irg_end(called_graph));
1141         arity = get_irn_arity(end_bl);    /* arity = n_exc + n_ret  */
1142         n_res = get_method_n_ress(get_Call_type(call));
1143
1144         res_pred = xmalloc(n_res * sizeof(*res_pred));
1145         cf_pred  = xmalloc(arity * sizeof(*res_pred));
1146
1147         set_irg_current_block(current_ir_graph, post_bl); /* just to make sure */
1148
1149         /* -- archive keepalives -- */
1150         irn_arity = get_irn_arity(end);
1151         for (i = 0; i < irn_arity; i++) {
1152                 ir_node *ka = get_End_keepalive(end, i);
1153                 if (! is_Bad(ka))
1154                         add_End_keepalive(get_irg_end(current_ir_graph), ka);
1155         }
1156
1157         /* The new end node will die.  We need not free as the in array is on the obstack:
1158            copy_node() only generated 'D' arrays. */
1159
1160         /* -- Replace Return nodes by Jump nodes. -- */
1161         n_ret = 0;
1162         for (i = 0; i < arity; i++) {
1163                 ir_node *ret;
1164                 ret = get_irn_n(end_bl, i);
1165                 if (is_Return(ret)) {
1166                         cf_pred[n_ret] = new_r_Jmp(current_ir_graph, get_nodes_block(ret));
1167                         n_ret++;
1168                 }
1169         }
1170         set_irn_in(post_bl, n_ret, cf_pred);
1171
1172         /* -- Build a Tuple for all results of the method.
1173            Add Phi node if there was more than one Return.  -- */
1174         turn_into_tuple(post_call, pn_Call_max);
1175         /* First the Memory-Phi */
1176         n_ret = 0;
1177         for (i = 0; i < arity; i++) {
1178                 ret = get_irn_n(end_bl, i);
1179                 if (is_Return(ret)) {
1180                         cf_pred[n_ret] = get_Return_mem(ret);
1181                         n_ret++;
1182                 }
1183         }
1184         phi = new_Phi(n_ret, cf_pred, mode_M);
1185         set_Tuple_pred(call, pn_Call_M_regular, phi);
1186         /* Conserve Phi-list for further inlinings -- but might be optimized */
1187         if (get_nodes_block(phi) == post_bl) {
1188                 set_irn_link(phi, get_irn_link(post_bl));
1189                 set_irn_link(post_bl, phi);
1190         }
1191         /* Now the real results */
1192         if (n_res > 0) {
1193                 for (j = 0; j < n_res; j++) {
1194                         n_ret = 0;
1195                         for (i = 0; i < arity; i++) {
1196                                 ret = get_irn_n(end_bl, i);
1197                                 if (get_irn_op(ret) == op_Return) {
1198                                         cf_pred[n_ret] = get_Return_res(ret, j);
1199                                         n_ret++;
1200                                 }
1201                         }
1202                         if (n_ret > 0)
1203                                 phi = new_Phi(n_ret, cf_pred, get_irn_mode(cf_pred[0]));
1204                         else
1205                                 phi = new_Bad();
1206                         res_pred[j] = phi;
1207                         /* Conserve Phi-list for further inlinings -- but might be optimized */
1208                         if (get_nodes_block(phi) == post_bl) {
1209                                 set_irn_link(phi, get_irn_link(post_bl));
1210                                 set_irn_link(post_bl, phi);
1211                         }
1212                 }
1213                 set_Tuple_pred(call, pn_Call_T_result, new_Tuple(n_res, res_pred));
1214         } else {
1215                 set_Tuple_pred(call, pn_Call_T_result, new_Bad());
1216         }
1217
1218         /* For now, we cannot inline calls with value_base */
1219         set_Tuple_pred(call, pn_Call_P_value_res_base, new_Bad());
1220
1221         /* Finally the exception control flow.
1222            We have two (three) possible situations:
1223            First if the Call branches to an exception handler: We need to add a Phi node to
1224            collect the memory containing the exception objects.  Further we need
1225            to add another block to get a correct representation of this Phi.  To
1226            this block we add a Jmp that resolves into the X output of the Call
1227            when the Call is turned into a tuple.
1228            Second the Call branches to End, the exception is not handled.  Just
1229            add all inlined exception branches to the End node.
1230            Third: there is no Exception edge at all. Handle as case two. */
1231         if (exc_handling == exc_handler) {
1232                 n_exc = 0;
1233                 for (i = 0; i < arity; i++) {
1234                         ir_node *ret, *irn;
1235                         ret = get_irn_n(end_bl, i);
1236                         irn = skip_Proj(ret);
1237                         if (is_fragile_op(irn) || (get_irn_op(irn) == op_Raise)) {
1238                                 cf_pred[n_exc] = ret;
1239                                 ++n_exc;
1240                         }
1241                 }
1242                 if (n_exc > 0) {
1243                         new_Block(n_exc, cf_pred);      /* watch it: current_block is changed! */
1244                         set_Tuple_pred(call, pn_Call_X_except, new_Jmp());
1245                         /* The Phi for the memories with the exception objects */
1246                         n_exc = 0;
1247                         for (i = 0; i < arity; i++) {
1248                                 ir_node *ret;
1249                                 ret = skip_Proj(get_irn_n(end_bl, i));
1250                                 if (is_Call(ret)) {
1251                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 3);
1252                                         n_exc++;
1253                                 } else if (is_fragile_op(ret)) {
1254                                         /* We rely that all cfops have the memory output at the same position. */
1255                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 0);
1256                                         n_exc++;
1257                                 } else if (get_irn_op(ret) == op_Raise) {
1258                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 1);
1259                                         n_exc++;
1260                                 }
1261                         }
1262                         set_Tuple_pred(call, pn_Call_M_except, new_Phi(n_exc, cf_pred, mode_M));
1263                 } else {
1264                         set_Tuple_pred(call, pn_Call_X_except, new_Bad());
1265                         set_Tuple_pred(call, pn_Call_M_except, new_Bad());
1266                 }
1267                 set_Tuple_pred(call, pn_Call_X_regular, new_Bad());
1268         } else {
1269                 ir_node *main_end_bl;
1270                 int main_end_bl_arity;
1271                 ir_node **end_preds;
1272
1273                 /* assert(exc_handling == 1 || no exceptions. ) */
1274                 n_exc = 0;
1275                 for (i = 0; i < arity; i++) {
1276                         ir_node *ret = get_irn_n(end_bl, i);
1277                         ir_node *irn = skip_Proj(ret);
1278
1279                         if (is_fragile_op(irn) || (get_irn_op(irn) == op_Raise)) {
1280                                 cf_pred[n_exc] = ret;
1281                                 n_exc++;
1282                         }
1283                 }
1284                 main_end_bl = get_irg_end_block(current_ir_graph);
1285                 main_end_bl_arity = get_irn_arity(main_end_bl);
1286                 end_preds =  xmalloc((n_exc + main_end_bl_arity) * sizeof(*end_preds));
1287
1288                 for (i = 0; i < main_end_bl_arity; ++i)
1289                         end_preds[i] = get_irn_n(main_end_bl, i);
1290                 for (i = 0; i < n_exc; ++i)
1291                         end_preds[main_end_bl_arity + i] = cf_pred[i];
1292                 set_irn_in(main_end_bl, n_exc + main_end_bl_arity, end_preds);
1293                 set_Tuple_pred(call, pn_Call_X_regular, new_Bad());
1294                 set_Tuple_pred(call, pn_Call_X_except,  new_Bad());
1295                 set_Tuple_pred(call, pn_Call_M_except,  new_Bad());
1296                 free(end_preds);
1297         }
1298         free(res_pred);
1299         free(cf_pred);
1300
1301         /* --  Turn CSE back on. -- */
1302         set_optimize(rem_opt);
1303
1304         return 1;
1305 }
1306
1307 /********************************************************************/
1308 /* Apply inlineing to small methods.                                */
1309 /********************************************************************/
1310
1311 /** Represents a possible inlinable call in a graph. */
1312 typedef struct _call_entry call_entry;
1313 struct _call_entry {
1314         ir_node    *call;   /**< the Call */
1315         ir_graph   *callee; /**< the callee called here */
1316         call_entry *next;   /**< for linking the next one */
1317 };
1318
1319 /**
1320  * environment for inlining small irgs
1321  */
1322 typedef struct _inline_env_t {
1323         struct obstack obst;  /**< an obstack where call_entries are allocated on. */
1324         call_entry *head;     /**< the head of the call entry list */
1325         call_entry *tail;     /**< the tail of the call entry list */
1326 } inline_env_t;
1327
1328 /**
1329  * Returns the irg called from a Call node. If the irg is not
1330  * known, NULL is returned.
1331  */
1332 static ir_graph *get_call_called_irg(ir_node *call) {
1333         ir_node *addr;
1334         ir_graph *called_irg = NULL;
1335
1336         addr = get_Call_ptr(call);
1337         if (is_SymConst(addr) && get_SymConst_kind(addr) == symconst_addr_ent) {
1338                 called_irg = get_entity_irg(get_SymConst_entity(addr));
1339         }
1340
1341         return called_irg;
1342 }
1343
1344 /**
1345  * Walker: Collect all calls to known graphs inside a graph.
1346  */
1347 static void collect_calls(ir_node *call, void *env) {
1348         if (is_Call(call)) {
1349                 ir_graph *called_irg = get_call_called_irg(call);
1350                 if (called_irg) {
1351                         /* The Call node calls a locally defined method.  Remember to inline. */
1352                         inline_env_t *ienv  = env;
1353                         call_entry   *entry = obstack_alloc(&ienv->obst, sizeof(*entry));
1354                         entry->call   = call;
1355                         entry->callee = called_irg;
1356                         entry->next   = NULL;
1357
1358                         if (ienv->tail == NULL)
1359                                 ienv->head = entry;
1360                         else
1361                                 ienv->tail->next = entry;
1362                         ienv->tail = entry;
1363                 }
1364         }
1365 }
1366
1367 /**
1368  * Inlines all small methods at call sites where the called address comes
1369  * from a Const node that references the entity representing the called
1370  * method.
1371  * The size argument is a rough measure for the code size of the method:
1372  * Methods where the obstack containing the firm graph is smaller than
1373  * size are inlined.
1374  */
1375 void inline_small_irgs(ir_graph *irg, int size) {
1376   ir_graph *rem = current_ir_graph;
1377         inline_env_t env;
1378         call_entry *entry;
1379         DEBUG_ONLY(firm_dbg_module_t *dbg;)
1380
1381         if (!(get_opt_optimize() && get_opt_inline())) return;
1382
1383         FIRM_DBG_REGISTER(dbg, "firm.opt.inline");
1384
1385         current_ir_graph = irg;
1386         /* Handle graph state */
1387         assert(get_irg_phase_state(irg) != phase_building);
1388         free_callee_info(irg);
1389
1390         /* Find Call nodes to inline.
1391            (We can not inline during a walk of the graph, as inlineing the same
1392            method several times changes the visited flag of the walked graph:
1393            after the first inlineing visited of the callee equals visited of
1394            the caller.  With the next inlineing both are increased.) */
1395         obstack_init(&env.obst);
1396         env.head = env.tail = NULL;
1397         irg_walk_graph(irg, NULL, collect_calls, &env);
1398
1399         if (env.head != NULL) {
1400                 /* There are calls to inline */
1401                 collect_phiprojs(irg);
1402                 for (entry = env.head; entry != NULL; entry = entry->next) {
1403                         ir_graph *callee = entry->callee;
1404                         if (((_obstack_memory_used(callee->obst) - (int)obstack_room(callee->obst)) < size) ||
1405                             (get_irg_inline_property(callee) >= irg_inline_forced)) {
1406                                 inline_method(entry->call, callee);
1407                         }
1408                 }
1409         }
1410         obstack_free(&env.obst, NULL);
1411         current_ir_graph = rem;
1412 }
1413
1414 /**
1415  * Environment for inlining irgs.
1416  */
1417 typedef struct {
1418   int n_nodes;             /**< Number of nodes in graph except Id, Tuple, Proj, Start, End. */
1419         int n_nodes_orig;        /**< for statistics */
1420         call_entry *call_head;   /**< The head of the list of all call nodes in this graph. */
1421         call_entry *call_tail;   /**< The tail of the list of all call nodes in this graph .*/
1422         int n_call_nodes;        /**< Number of Call nodes in the graph. */
1423         int n_call_nodes_orig;   /**< for statistics */
1424         int n_callers;           /**< Number of known graphs that call this graphs. */
1425         int n_callers_orig;      /**< for statistics */
1426         int got_inline;          /**< Set, if at leat one call inside this graph was inlined. */
1427 } inline_irg_env;
1428
1429 /**
1430  * Allocate a new environment for inlining.
1431  */
1432 static inline_irg_env *alloc_inline_irg_env(struct obstack *obst) {
1433         inline_irg_env *env    = obstack_alloc(obst, sizeof(*env));
1434         env->n_nodes           = -2; /* do not count count Start, End */
1435         env->n_nodes_orig      = -2; /* do not count Start, End */
1436         env->call_head         = NULL;
1437         env->call_tail         = NULL;
1438         env->n_call_nodes      = 0;
1439         env->n_call_nodes_orig = 0;
1440         env->n_callers         = 0;
1441         env->n_callers_orig    = 0;
1442         env->got_inline        = 0;
1443         return env;
1444 }
1445
1446 typedef struct walker_env {
1447         struct obstack *obst; /**< the obstack for allocations. */
1448         inline_irg_env *x;    /**< the inline environment */
1449         int ignore_runtime;   /**< the ignore runtime flag */
1450 } wenv_t;
1451
1452 /**
1453  * post-walker: collect all calls in the inline-environment
1454  * of a graph and sum some statistics.
1455  */
1456 static void collect_calls2(ir_node *call, void *ctx) {
1457         wenv_t         *env = ctx;
1458         inline_irg_env *x = env->x;
1459         ir_op          *op = get_irn_op(call);
1460         ir_graph       *callee;
1461         call_entry     *entry;
1462
1463         /* count meaningful nodes in irg */
1464         if (op != op_Proj && op != op_Tuple && op != op_Sync) {
1465                 ++x->n_nodes;
1466                 ++x->n_nodes_orig;
1467         }
1468
1469         if (op != op_Call) return;
1470
1471         /* check, if it's a runtime call */
1472         if (env->ignore_runtime) {
1473                 ir_node *symc = get_Call_ptr(call);
1474
1475                 if (is_SymConst(symc) && get_SymConst_kind(symc) == symconst_addr_ent) {
1476                         ir_entity *ent = get_SymConst_entity(symc);
1477
1478                         if (get_entity_additional_properties(ent) & mtp_property_runtime)
1479                                 return;
1480                 }
1481         }
1482
1483         /* collect all call nodes */
1484         ++x->n_call_nodes;
1485         ++x->n_call_nodes_orig;
1486
1487         callee = get_call_called_irg(call);
1488         if (callee) {
1489                 inline_irg_env *callee_env = get_irg_link(callee);
1490                 /* count all static callers */
1491                 ++callee_env->n_callers;
1492                 ++callee_env->n_callers_orig;
1493
1494                 /* link it in the list of possible inlinable entries */
1495                 entry = obstack_alloc(env->obst, sizeof(*entry));
1496                 entry->call   = call;
1497                 entry->callee = callee;
1498                 entry->next   = NULL;
1499                 if (x->call_tail == NULL)
1500                         x->call_head = entry;
1501                 else
1502                         x->call_tail->next = entry;
1503                 x->call_tail = entry;
1504         }
1505 }
1506
1507 /**
1508  * Returns TRUE if the number of callers in 0 in the irg's environment,
1509  * hence this irg is a leave.
1510  */
1511 INLINE static int is_leave(ir_graph *irg) {
1512         inline_irg_env *env = get_irg_link(irg);
1513         return env->n_call_nodes == 0;
1514 }
1515
1516 /**
1517  * Returns TRUE if the number of callers is smaller size in the irg's environment.
1518  */
1519 INLINE static int is_smaller(ir_graph *callee, int size) {
1520         inline_irg_env *env = get_irg_link(callee);
1521         return env->n_nodes < size;
1522 }
1523
1524 /**
1525  * Append the nodes of the list src to the nodes of the list in environment dst.
1526  */
1527 static void append_call_list(struct obstack *obst, inline_irg_env *dst, call_entry *src) {
1528         call_entry *entry, *nentry;
1529
1530         /* Note that the src list points to Call nodes in the inlined graph, but
1531            we need Call nodes in our graph. Luckily the inliner leaves this information
1532            in the link field. */
1533         for (entry = src; entry != NULL; entry = entry->next) {
1534                 nentry = obstack_alloc(obst, sizeof(*nentry));
1535                 nentry->call   = get_irn_link(entry->call);
1536                 nentry->callee = entry->callee;
1537                 nentry->next   = NULL;
1538                 dst->call_tail->next = nentry;
1539                 dst->call_tail       = nentry;
1540         }
1541 }
1542
1543 /*
1544  * Inlines small leave methods at call sites where the called address comes
1545  * from a Const node that references the entity representing the called
1546  * method.
1547  * The size argument is a rough measure for the code size of the method:
1548  * Methods where the obstack containing the firm graph is smaller than
1549  * size are inlined.
1550  */
1551 void inline_leave_functions(int maxsize, int leavesize, int size, int ignore_runtime) {
1552         inline_irg_env   *env;
1553         ir_graph         *irg;
1554         int              i, n_irgs;
1555         ir_graph         *rem;
1556         int              did_inline;
1557         wenv_t           wenv;
1558         call_entry       *entry, *tail;
1559         const call_entry *centry;
1560         struct obstack   obst;
1561         DEBUG_ONLY(firm_dbg_module_t *dbg;)
1562
1563         if (!(get_opt_optimize() && get_opt_inline())) return;
1564
1565         FIRM_DBG_REGISTER(dbg, "firm.opt.inline");
1566         rem = current_ir_graph;
1567         obstack_init(&obst);
1568
1569         /* extend all irgs by a temporary data structure for inlining. */
1570         n_irgs = get_irp_n_irgs();
1571         for (i = 0; i < n_irgs; ++i)
1572                 set_irg_link(get_irp_irg(i), alloc_inline_irg_env(&obst));
1573
1574         /* Precompute information in temporary data structure. */
1575         wenv.obst           = &obst;
1576         wenv.ignore_runtime = ignore_runtime;
1577         for (i = 0; i < n_irgs; ++i) {
1578                 ir_graph *irg = get_irp_irg(i);
1579
1580                 assert(get_irg_phase_state(irg) != phase_building);
1581                 free_callee_info(irg);
1582
1583                 wenv.x = get_irg_link(irg);
1584                 irg_walk_graph(irg, NULL, collect_calls2, &wenv);
1585         }
1586
1587         /* -- and now inline. -- */
1588
1589         /* Inline leaves recursively -- we might construct new leaves. */
1590         do {
1591                 did_inline = 0;
1592
1593                 for (i = 0; i < n_irgs; ++i) {
1594                         ir_node *call;
1595                         int phiproj_computed = 0;
1596
1597                         current_ir_graph = get_irp_irg(i);
1598                         env = (inline_irg_env *)get_irg_link(current_ir_graph);
1599
1600                         tail = NULL;
1601                         for (entry = env->call_head; entry != NULL; entry = entry->next) {
1602                                 ir_graph *callee;
1603
1604                                 if (env->n_nodes > maxsize) break;
1605
1606                                 call   = entry->call;
1607                                 callee = entry->callee;
1608
1609                                 if (is_leave(callee) && is_smaller(callee, leavesize)) {
1610                                         if (!phiproj_computed) {
1611                                                 phiproj_computed = 1;
1612                                                 collect_phiprojs(current_ir_graph);
1613                                         }
1614                                         did_inline = inline_method(call, callee);
1615
1616                                         if (did_inline) {
1617                                                 /* Do some statistics */
1618                                                 inline_irg_env *callee_env = (inline_irg_env *)get_irg_link(callee);
1619
1620                                                 env->got_inline = 1;
1621                                                 --env->n_call_nodes;
1622                                                 env->n_nodes += callee_env->n_nodes;
1623                                                 --callee_env->n_callers;
1624
1625                                                 /* remove this call from the list */
1626                                                 if (tail != NULL)
1627                                                         tail->next = entry->next;
1628                                                 else
1629                                                         env->call_head = entry->next;
1630                                                 continue;
1631                                         }
1632                                 }
1633                                 tail = entry;
1634                         }
1635                         env->call_tail = tail;
1636                 }
1637         } while (did_inline);
1638
1639         /* inline other small functions. */
1640         for (i = 0; i < n_irgs; ++i) {
1641                 ir_node *call;
1642                 int phiproj_computed = 0;
1643
1644                 current_ir_graph = get_irp_irg(i);
1645                 env = (inline_irg_env *)get_irg_link(current_ir_graph);
1646
1647                 /* note that the list of possible calls is updated during the process */
1648                 tail = NULL;
1649                 for (entry = env->call_head; entry != NULL; entry = entry->next) {
1650                         ir_graph *callee;
1651
1652                         call   = entry->call;
1653                         callee = entry->callee;
1654
1655                         if (((is_smaller(callee, size) && (env->n_nodes < maxsize)) ||    /* small function */
1656                                 (get_irg_inline_property(callee) >= irg_inline_forced))) {
1657                                 if (!phiproj_computed) {
1658                                         phiproj_computed = 1;
1659                                         collect_phiprojs(current_ir_graph);
1660                                 }
1661                                 if (inline_method(call, callee)) {
1662                                         inline_irg_env *callee_env = (inline_irg_env *)get_irg_link(callee);
1663
1664                                         /* callee was inline. Append it's call list. */
1665                                         env->got_inline = 1;
1666                                         --env->n_call_nodes;
1667                                         append_call_list(&obst, env, callee_env->call_head);
1668                                         env->n_call_nodes += callee_env->n_call_nodes;
1669                                         env->n_nodes += callee_env->n_nodes;
1670                                         --callee_env->n_callers;
1671
1672                                         /* after we have inlined callee, all called methods inside callee
1673                                            are now called once more */
1674                                         for (centry = callee_env->call_head; centry != NULL; centry = centry->next) {
1675                                                 inline_irg_env *penv = get_irg_link(centry->callee);
1676                                                 ++penv->n_callers;
1677                                         }
1678
1679                                         /* remove this call from the list */
1680                                         if (tail != NULL)
1681                                                 tail->next = entry->next;
1682                                         else
1683                                                 env->call_head = entry->next;
1684                                         continue;
1685                                 }
1686                         }
1687                         tail = entry;
1688                 }
1689                 env->call_tail = tail;
1690         }
1691
1692         for (i = 0; i < n_irgs; ++i) {
1693                 irg = get_irp_irg(i);
1694                 env = (inline_irg_env *)get_irg_link(irg);
1695
1696                 if (env->got_inline) {
1697                         /* this irg got calls inlined */
1698                         set_irg_outs_inconsistent(irg);
1699                         set_irg_doms_inconsistent(irg);
1700
1701                         optimize_graph_df(irg);
1702                         optimize_cf(irg);
1703                 }
1704                 if (env->got_inline || (env->n_callers_orig != env->n_callers))
1705                         DB((dbg, SET_LEVEL_1, "Nodes:%3d ->%3d, calls:%3d ->%3d, callers:%3d ->%3d, -- %s\n",
1706                         env->n_nodes_orig, env->n_nodes, env->n_call_nodes_orig, env->n_call_nodes,
1707                         env->n_callers_orig, env->n_callers,
1708                         get_entity_name(get_irg_entity(irg))));
1709         }
1710
1711         obstack_free(&obst, NULL);
1712         current_ir_graph = rem;
1713 }
1714
1715 /*******************************************************************/
1716 /*  Code Placement.  Pins all floating nodes to a block where they */
1717 /*  will be executed only if needed.                               */
1718 /*******************************************************************/
1719
1720 /**
1721  * Returns non-zero, is a block is not reachable from Start.
1722  *
1723  * @param block  the block to test
1724  */
1725 static int
1726 is_Block_unreachable(ir_node *block) {
1727         return is_Block_dead(block) || get_Block_dom_depth(block) < 0;
1728 }
1729
1730 /**
1731  * Find the earliest correct block for node n.  --- Place n into the
1732  * same Block as its dominance-deepest Input.
1733  *
1734  * We have to avoid calls to get_nodes_block() here
1735  * because the graph is floating.
1736  *
1737  * move_out_of_loops() expects that place_floats_early() have placed
1738  * all "living" nodes into a living block. That's why we must
1739  * move nodes in dead block with "live" successors into a valid
1740  * block.
1741  * We move them just into the same block as it's successor (or
1742  * in case of a Phi into the effective use block). For Phi successors,
1743  * this may still be a dead block, but then there is no real use, as
1744  * the control flow will be dead later.
1745  *
1746  * @param n         the node to be placed
1747  * @param worklist  a worklist, predecessors of non-floating nodes are placed here
1748  */
1749 static void
1750 place_floats_early(ir_node *n, waitq *worklist) {
1751         int i, irn_arity;
1752
1753         /* we must not run into an infinite loop */
1754         assert(irn_not_visited(n));
1755         mark_irn_visited(n);
1756
1757         /* Place floating nodes. */
1758         if (get_irn_pinned(n) == op_pin_state_floats) {
1759                 ir_node *curr_block = get_irn_n(n, -1);
1760                 int in_dead_block   = is_Block_unreachable(curr_block);
1761                 int depth           = 0;
1762                 ir_node *b          = NULL;   /* The block to place this node in */
1763
1764                 assert(is_no_Block(n));
1765
1766                 if (is_irn_start_block_placed(n)) {
1767                         /* These nodes will not be placed by the loop below. */
1768                         b = get_irg_start_block(current_ir_graph);
1769                         depth = 1;
1770                 }
1771
1772                 /* find the block for this node. */
1773                 irn_arity = get_irn_arity(n);
1774                 for (i = 0; i < irn_arity; i++) {
1775                         ir_node *pred = get_irn_n(n, i);
1776                         ir_node *pred_block;
1777
1778                         if ((irn_not_visited(pred))
1779                             && (get_irn_pinned(pred) == op_pin_state_floats)) {
1780
1781                                 /*
1782                                  * If the current node is NOT in a dead block, but one of its
1783                                  * predecessors is, we must move the predecessor to a live block.
1784                                  * Such thing can happen, if global CSE chose a node from a dead block.
1785                                  * We move it simply to our block.
1786                                  * Note that neither Phi nor End nodes are floating, so we don't
1787                                  * need to handle them here.
1788                                  */
1789                                 if (! in_dead_block) {
1790                                         if (get_irn_pinned(pred) == op_pin_state_floats &&
1791                                                 is_Block_unreachable(get_irn_n(pred, -1)))
1792                                                 set_nodes_block(pred, curr_block);
1793                                 }
1794                                 place_floats_early(pred, worklist);
1795                         }
1796
1797                         /*
1798                          * A node in the Bad block must stay in the bad block,
1799                          * so don't compute a new block for it.
1800                          */
1801                         if (in_dead_block)
1802                                 continue;
1803
1804                         /* Because all loops contain at least one op_pin_state_pinned node, now all
1805                            our inputs are either op_pin_state_pinned or place_early() has already
1806                            been finished on them.  We do not have any unfinished inputs!  */
1807                         pred_block = get_irn_n(pred, -1);
1808                         if ((!is_Block_dead(pred_block)) &&
1809                                 (get_Block_dom_depth(pred_block) > depth)) {
1810                                 b = pred_block;
1811                                 depth = get_Block_dom_depth(pred_block);
1812                         }
1813                         /* Avoid that the node is placed in the Start block */
1814                         if ((depth == 1) && (get_Block_dom_depth(get_irn_n(n, -1)) > 1)
1815                                 && get_irg_phase_state(current_ir_graph) != phase_backend) {
1816                                 b = get_Block_cfg_out(get_irg_start_block(current_ir_graph), 0);
1817                                 assert(b != get_irg_start_block(current_ir_graph));
1818                                 depth = 2;
1819                         }
1820                 }
1821                 if (b)
1822                         set_nodes_block(n, b);
1823         }
1824
1825         /*
1826          * Add predecessors of non floating nodes and non-floating predecessors
1827          * of floating nodes to worklist and fix their blocks if the are in dead block.
1828          */
1829         irn_arity = get_irn_arity(n);
1830
1831         if (get_irn_op(n) == op_End) {
1832                 /*
1833                  * Simplest case: End node. Predecessors are keep-alives,
1834                  * no need to move out of dead block.
1835                  */
1836                 for (i = -1; i < irn_arity; ++i) {
1837                         ir_node *pred = get_irn_n(n, i);
1838                         if (irn_not_visited(pred))
1839                                 waitq_put(worklist, pred);
1840                 }
1841         } else if (is_Block(n)) {
1842                 /*
1843                  * Blocks: Predecessors are control flow, no need to move
1844                  * them out of dead block.
1845                  */
1846                 for (i = irn_arity - 1; i >= 0; --i) {
1847                         ir_node *pred = get_irn_n(n, i);
1848                         if (irn_not_visited(pred))
1849                                 waitq_put(worklist, pred);
1850                 }
1851         } else if (is_Phi(n)) {
1852                 ir_node *pred;
1853                 ir_node *curr_block = get_irn_n(n, -1);
1854                 int in_dead_block   = is_Block_unreachable(curr_block);
1855
1856                 /*
1857                  * Phi nodes: move nodes from dead blocks into the effective use
1858                  * of the Phi-input if the Phi is not in a bad block.
1859                  */
1860                 pred = get_irn_n(n, -1);
1861                 if (irn_not_visited(pred))
1862                         waitq_put(worklist, pred);
1863
1864                 for (i = irn_arity - 1; i >= 0; --i) {
1865                         ir_node *pred = get_irn_n(n, i);
1866
1867                         if (irn_not_visited(pred)) {
1868                                 if (! in_dead_block &&
1869                                         get_irn_pinned(pred) == op_pin_state_floats &&
1870                                         is_Block_unreachable(get_irn_n(pred, -1))) {
1871                                         set_nodes_block(pred, get_Block_cfgpred_block(curr_block, i));
1872                                 }
1873                                 waitq_put(worklist, pred);
1874                         }
1875                 }
1876         } else {
1877                 ir_node *pred;
1878                 ir_node *curr_block = get_irn_n(n, -1);
1879                 int in_dead_block   = is_Block_unreachable(curr_block);
1880
1881                 /*
1882                  * All other nodes: move nodes from dead blocks into the same block.
1883                  */
1884                 pred = get_irn_n(n, -1);
1885                 if (irn_not_visited(pred))
1886                         waitq_put(worklist, pred);
1887
1888                 for (i = irn_arity - 1; i >= 0; --i) {
1889                         ir_node *pred = get_irn_n(n, i);
1890
1891                         if (irn_not_visited(pred)) {
1892                                 if (! in_dead_block &&
1893                                         get_irn_pinned(pred) == op_pin_state_floats &&
1894                                         is_Block_unreachable(get_irn_n(pred, -1))) {
1895                                         set_nodes_block(pred, curr_block);
1896                                 }
1897                                 waitq_put(worklist, pred);
1898                         }
1899                 }
1900         }
1901 }
1902
1903 /**
1904  * Floating nodes form subgraphs that begin at nodes as Const, Load,
1905  * Start, Call and that end at op_pin_state_pinned nodes as Store, Call.  Place_early
1906  * places all floating nodes reachable from its argument through floating
1907  * nodes and adds all beginnings at op_pin_state_pinned nodes to the worklist.
1908  *
1909  * @param worklist   a worklist, used for the algorithm, empty on in/output
1910  */
1911 static void place_early(waitq *worklist) {
1912         assert(worklist);
1913         inc_irg_visited(current_ir_graph);
1914
1915         /* this inits the worklist */
1916         place_floats_early(get_irg_end(current_ir_graph), worklist);
1917
1918         /* Work the content of the worklist. */
1919         while (!waitq_empty(worklist)) {
1920                 ir_node *n = waitq_get(worklist);
1921                 if (irn_not_visited(n))
1922                         place_floats_early(n, worklist);
1923         }
1924
1925         set_irg_outs_inconsistent(current_ir_graph);
1926         set_irg_pinned(current_ir_graph, op_pin_state_pinned);
1927 }
1928
1929 /**
1930  * Compute the deepest common ancestor of block and dca.
1931  */
1932 static ir_node *calc_dca(ir_node *dca, ir_node *block) {
1933         assert(block);
1934
1935         /* we do not want to place nodes in dead blocks */
1936         if (is_Block_dead(block))
1937                 return dca;
1938
1939         /* We found a first legal placement. */
1940         if (!dca) return block;
1941
1942         /* Find a placement that is dominates both, dca and block. */
1943         while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
1944                 block = get_Block_idom(block);
1945
1946         while (get_Block_dom_depth(dca) > get_Block_dom_depth(block)) {
1947                 dca = get_Block_idom(dca);
1948         }
1949
1950         while (block != dca) {
1951                 block = get_Block_idom(block); dca = get_Block_idom(dca);
1952         }
1953
1954         return dca;
1955 }
1956
1957 /** Deepest common dominance ancestor of DCA and CONSUMER of PRODUCER.
1958  * I.e., DCA is the block where we might place PRODUCER.
1959  * A data flow edge points from producer to consumer.
1960  */
1961 static ir_node *
1962 consumer_dom_dca(ir_node *dca, ir_node *consumer, ir_node *producer) {
1963         ir_node *block = NULL;
1964
1965         /* Compute the latest block into which we can place a node so that it is
1966            before consumer. */
1967         if (get_irn_op(consumer) == op_Phi) {
1968                 /* our consumer is a Phi-node, the effective use is in all those
1969                    blocks through which the Phi-node reaches producer */
1970                 int i, irn_arity;
1971                 ir_node *phi_block = get_nodes_block(consumer);
1972                 irn_arity = get_irn_arity(consumer);
1973
1974                 for (i = 0;  i < irn_arity; i++) {
1975                         if (get_irn_n(consumer, i) == producer) {
1976                                 ir_node *new_block = get_nodes_block(get_Block_cfgpred(phi_block, i));
1977
1978                                 if (! is_Block_unreachable(new_block))
1979                                         block = calc_dca(block, new_block);
1980                         }
1981                 }
1982
1983                 if (! block)
1984                         block = get_irn_n(producer, -1);
1985         } else {
1986                 assert(is_no_Block(consumer));
1987                 block = get_nodes_block(consumer);
1988         }
1989
1990         /* Compute the deepest common ancestor of block and dca. */
1991         return calc_dca(dca, block);
1992 }
1993
1994 /* FIXME: the name clashes here with the function from ana/field_temperature.c
1995  * please rename. */
1996 static INLINE int get_irn_loop_depth(ir_node *n) {
1997         return get_loop_depth(get_irn_loop(n));
1998 }
1999
2000 /**
2001  * Move n to a block with less loop depth than it's current block. The
2002  * new block must be dominated by early.
2003  *
2004  * @param n      the node that should be moved
2005  * @param early  the earliest block we can n move to
2006  */
2007 static void move_out_of_loops(ir_node *n, ir_node *early) {
2008         ir_node *best, *dca;
2009         assert(n && early);
2010
2011
2012         /* Find the region deepest in the dominator tree dominating
2013            dca with the least loop nesting depth, but still dominated
2014            by our early placement. */
2015         dca = get_nodes_block(n);
2016
2017         best = dca;
2018         while (dca != early) {
2019                 dca = get_Block_idom(dca);
2020                 if (!dca || is_Bad(dca)) break; /* may be Bad if not reachable from Start */
2021                 if (get_irn_loop_depth(dca) < get_irn_loop_depth(best)) {
2022                         best = dca;
2023                 }
2024         }
2025         if (best != get_nodes_block(n)) {
2026                 /* debug output
2027                 printf("Moving out of loop: "); DDMN(n);
2028                 printf(" Outermost block: "); DDMN(early);
2029                 printf(" Best block: "); DDMN(best);
2030                 printf(" Innermost block: "); DDMN(get_nodes_block(n));
2031                 */
2032                 set_nodes_block(n, best);
2033         }
2034 }
2035
2036 /* deepest common ancestor in the dominator tree of all nodes'
2037    blocks depending on us; our final placement has to dominate DCA. */
2038 static ir_node *get_deepest_common_ancestor(ir_node *node, ir_node *dca)
2039 {
2040         int i;
2041
2042         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
2043                 ir_node *succ = get_irn_out(node, i);
2044                 ir_node *succ_blk;
2045
2046                 if (is_End(succ)) {
2047                         /*
2048                          * This consumer is the End node, a keep alive edge.
2049                          * This is not a real consumer, so we ignore it
2050                          */
2051                         continue;
2052                 }
2053
2054                 if(is_Proj(succ)) {
2055                         dca = get_deepest_common_ancestor(succ, dca);
2056                 } else {
2057                         /* ignore if succ is in dead code */
2058                         succ_blk = get_irn_n(succ, -1);
2059                         if (is_Block_unreachable(succ_blk))
2060                                 continue;
2061                         dca = consumer_dom_dca(dca, succ, node);
2062                 }
2063         }
2064
2065         return dca;
2066 }
2067
2068 static void set_projs_block(ir_node *node, ir_node *block)
2069 {
2070         int i;
2071
2072         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
2073                 ir_node *succ = get_irn_out(node, i);
2074
2075                 assert(is_Proj(succ));
2076
2077                 if(get_irn_mode(succ) == mode_T) {
2078                         set_projs_block(succ, block);
2079                 }
2080                 set_nodes_block(succ, block);
2081         }
2082 }
2083
2084 /**
2085  * Find the latest legal block for N and place N into the
2086  * `optimal' Block between the latest and earliest legal block.
2087  * The `optimal' block is the dominance-deepest block of those
2088  * with the least loop-nesting-depth.  This places N out of as many
2089  * loops as possible and then makes it as control dependent as
2090  * possible.
2091  *
2092  * @param n         the node to be placed
2093  * @param worklist  a worklist, all successors of non-floating nodes are
2094  *                  placed here
2095  */
2096 static void place_floats_late(ir_node *n, pdeq *worklist) {
2097   int i;
2098         ir_node *early_blk;
2099
2100         assert(irn_not_visited(n)); /* no multiple placement */
2101
2102         mark_irn_visited(n);
2103
2104         /* no need to place block nodes, control nodes are already placed. */
2105         if ((get_irn_op(n) != op_Block) &&
2106             (!is_cfop(n)) &&
2107             (get_irn_mode(n) != mode_X)) {
2108                 /* Remember the early_blk placement of this block to move it
2109                    out of loop no further than the early_blk placement. */
2110                 early_blk = get_irn_n(n, -1);
2111
2112                 /*
2113                  * BEWARE: Here we also get code, that is live, but
2114                  * was in a dead block.  If the node is life, but because
2115                  * of CSE in a dead block, we still might need it.
2116                  */
2117
2118                 /* Assure that our users are all placed, except the Phi-nodes.
2119                 --- Each data flow cycle contains at least one Phi-node.  We
2120                     have to break the `user has to be placed before the
2121                     producer' dependence cycle and the Phi-nodes are the
2122                     place to do so, because we need to base our placement on the
2123                     final region of our users, which is OK with Phi-nodes, as they
2124                     are op_pin_state_pinned, and they never have to be placed after a
2125                     producer of one of their inputs in the same block anyway. */
2126                 for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
2127                         ir_node *succ = get_irn_out(n, i);
2128                         if (irn_not_visited(succ) && (get_irn_op(succ) != op_Phi))
2129                                 place_floats_late(succ, worklist);
2130                 }
2131
2132                 if (! is_Block_dead(early_blk)) {
2133                         /* do only move things that where not dead */
2134                         ir_op *op = get_irn_op(n);
2135
2136                         /* We have to determine the final block of this node... except for
2137                            constants and Projs */
2138                         if ((get_irn_pinned(n) == op_pin_state_floats) &&
2139                             (op != op_Const)    &&
2140                             (op != op_SymConst) &&
2141                             (op != op_Proj))
2142                         {
2143                                 /* deepest common ancestor in the dominator tree of all nodes'
2144                                    blocks depending on us; our final placement has to dominate
2145                                    DCA. */
2146                                 ir_node *dca = get_deepest_common_ancestor(n, NULL);
2147                                 if (dca != NULL) {
2148                                         set_nodes_block(n, dca);
2149                                         move_out_of_loops(n, early_blk);
2150                                         if(get_irn_mode(n) == mode_T) {
2151                                                 set_projs_block(n, get_nodes_block(n));
2152                                         }
2153                                 }
2154                         }
2155                 }
2156         }
2157
2158         /* Add successors of all non-floating nodes on list. (Those of floating
2159            nodes are placed already and therefore are marked.)  */
2160         for (i = 0; i < get_irn_n_outs(n); i++) {
2161                 ir_node *succ = get_irn_out(n, i);
2162                 if (irn_not_visited(get_irn_out(n, i))) {
2163                         pdeq_putr(worklist, succ);
2164                 }
2165         }
2166 }
2167
2168 /**
2169  * Place floating nodes on the given worklist as late as possible using
2170  * the dominance tree.
2171  *
2172  * @param worklist   the worklist containing the nodes to place
2173  */
2174 static void place_late(waitq *worklist) {
2175         assert(worklist);
2176         inc_irg_visited(current_ir_graph);
2177
2178         /* This fills the worklist initially. */
2179         place_floats_late(get_irg_start_block(current_ir_graph), worklist);
2180
2181         /* And now empty the worklist again... */
2182         while (!waitq_empty(worklist)) {
2183                 ir_node *n = waitq_get(worklist);
2184                 if (irn_not_visited(n))
2185                         place_floats_late(n, worklist);
2186         }
2187 }
2188
2189 /* Code Placement. */
2190 void place_code(ir_graph *irg) {
2191         waitq *worklist;
2192         ir_graph *rem = current_ir_graph;
2193
2194         current_ir_graph = irg;
2195
2196         /* Handle graph state */
2197         assert(get_irg_phase_state(irg) != phase_building);
2198         assure_doms(irg);
2199
2200         if (1 || get_irg_loopinfo_state(irg) != loopinfo_consistent) {
2201                 free_loop_information(irg);
2202                 construct_backedges(irg);
2203         }
2204
2205         /* Place all floating nodes as early as possible. This guarantees
2206          a legal code placement. */
2207         worklist = new_waitq();
2208         place_early(worklist);
2209
2210         /* place_early() invalidates the outs, place_late needs them. */
2211         compute_irg_outs(irg);
2212
2213         /* Now move the nodes down in the dominator tree. This reduces the
2214            unnecessary executions of the node. */
2215         place_late(worklist);
2216
2217         set_irg_outs_inconsistent(current_ir_graph);
2218         set_irg_loopinfo_inconsistent(current_ir_graph);
2219         del_waitq(worklist);
2220         current_ir_graph = rem;
2221 }
2222
2223 typedef struct cf_env {
2224         char changed;       /**< flag indicates that the cf graphs has changed. */
2225 } cf_env;
2226
2227 /**
2228  * Called by walker of remove_critical_cf_edges().
2229  *
2230  * Place an empty block to an edge between a blocks of multiple
2231  * predecessors and a block of multiple successors.
2232  *
2233  * @param n   IR node
2234  * @param env Environment of walker.
2235  */
2236 static void walk_critical_cf_edges(ir_node *n, void *env) {
2237         int arity, i;
2238         ir_node *pre, *block, *jmp;
2239         cf_env *cenv = env;
2240         ir_graph *irg = get_irn_irg(n);
2241
2242         /* Block has multiple predecessors */
2243         arity = get_irn_arity(n);
2244         if (arity > 1) {
2245                 if (n == get_irg_end_block(irg))
2246                         return;  /*  No use to add a block here.      */
2247
2248                 for (i = 0; i < arity; ++i) {
2249                         const ir_op *cfop;
2250
2251                         pre = get_irn_n(n, i);
2252                         cfop = get_irn_op(skip_Proj(pre));
2253
2254                         if (is_op_fragile(cfop)) {
2255                                 if (cfop != op_Raise)
2256                                         goto insert;
2257                                 continue;
2258                         }
2259                         if (is_op_forking(cfop)) {
2260                                 /* Predecessor has multiple successors. Insert new control flow edge edges. */
2261 insert:
2262                                 /* set predecessor of new block */
2263                                 block = new_r_Block(irg, 1, &pre);
2264                                 /* insert new jmp node to new block */
2265                                 jmp = new_r_Jmp(irg, block);
2266                                 /* set successor of new block */
2267                                 set_irn_n(n, i, jmp);
2268                                 cenv->changed = 1;
2269                         } /* predecessor has multiple successors */
2270                 } /* for all predecessors */
2271         } /* n is a multi-entry block */
2272 }
2273
2274 void remove_critical_cf_edges(ir_graph *irg) {
2275         cf_env env;
2276
2277         env.changed = 0;
2278
2279         irg_block_walk_graph(irg, NULL, walk_critical_cf_edges, &env);
2280         if (env.changed) {
2281                 /* control flow changed */
2282                 set_irg_outs_inconsistent(irg);
2283                 set_irg_extblk_inconsistent(irg);
2284                 set_irg_doms_inconsistent(irg);
2285                 set_irg_loopinfo_inconsistent(irg);
2286         }
2287 }