bugfix
[libfirm] / ir / ana / irscc.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ana/irscc.c
4  * Purpose:     Compute the strongly connected regions and build
5  *              backedge/loop datastructures.
6  *              A variation on the Tarjan algorithm. See also [Trapp:99],
7  *              Chapter 5.2.1.2.
8  * Author:      Goetz Lindenmaier
9  * Modified by:
10  * Created:     7.2002
11  * CVS-ID:      $Id$
12  * Copyright:   (c) 2002-2003 Universität Karlsruhe
13  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
14  */
15
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
19
20 #include <string.h>
21
22 #include "irloop_t.h"
23 #include "irnode_t.h"
24 #include "irgraph_t.h"
25 #include "array.h"
26 #include "pmap.h"
27 #include "irgwalk.h"
28 #include "irprog_t.h"
29 #include "irdump.h"
30
31 #undef INLINE
32 #define INLINE
33
34 ir_graph *outermost_ir_graph;      /* The outermost graph the scc is computed
35                                       for */
36 static ir_loop *current_loop;      /* Current loop construction is working
37                                       on. */
38 static int loop_node_cnt = 0;      /* Counts the number of allocated loop nodes.
39                                       Each loop node gets a unique number.
40                                       What for? ev. remove. @@@ */
41 static int current_dfn = 1;        /* Counter to generate depth first numbering
42                                       of visited nodes.  */
43
44 /**********************************************************************/
45 /* Node attributes                                                   **/
46 /**********************************************************************/
47
48 /* A map to get from irnodes to loop nodes. */
49 static pmap *node_loop_map = NULL;
50
51 /**********************************************************************/
52 /* Node attributes needed for the construction.                      **/
53 /**********************************************************************/
54
55 typedef struct scc_info {
56   bool in_stack;         /* Marks whether node is on the stack. */
57   int dfn;               /* Depth first search number. */
58   int uplink;            /* dfn number of ancestor. */
59   //  ir_loop *loop;         /* Refers to the containing loop. */
60   /*
61       struct section *section;
62       xset def;
63       xset use;
64   */
65 } scc_info;
66
67 static INLINE scc_info* new_scc_info(void) {
68   scc_info *info = obstack_alloc (outermost_ir_graph->obst, sizeof (scc_info));
69   memset (info, 0, sizeof (scc_info));
70   return info;
71 }
72
73 static INLINE void
74 mark_irn_in_stack (ir_node *n) {
75   assert(get_irn_link(n));
76   // to slow
77   //((scc_info *)get_irn_link(n))->in_stack = true;
78   ((scc_info *)n->link)->in_stack = true;
79 }
80
81 static INLINE void
82 mark_irn_not_in_stack (ir_node *n) {
83   assert(get_irn_link(n));
84   // to slow
85   //((scc_info *)get_irn_link(n))->in_stack = false;
86   ((scc_info *)n->link)->in_stack = false;
87 }
88
89 static INLINE bool
90 irn_is_in_stack (ir_node *n) {
91   assert(get_irn_link(n));
92   // to slow
93   //return ((scc_info *)get_irn_link(n))->in_stack;
94   return ((scc_info *)n->link)->in_stack;
95 }
96
97 static INLINE void
98 set_irn_uplink (ir_node *n, int uplink) {
99   assert(get_irn_link(n));
100   // to slow
101   //((scc_info *)get_irn_link(n))->uplink = uplink;
102   ((scc_info *)n->link)->uplink = uplink;
103 }
104
105 static INLINE int
106 get_irn_uplink (ir_node *n) {
107   assert(get_irn_link(n));
108   // to slow
109   //return ((scc_info *)get_irn_link(n))->uplink;
110   return ((scc_info *)n->link)->uplink;
111 }
112
113 static INLINE void
114 set_irn_dfn (ir_node *n, int dfn) {
115   assert(get_irn_link(n));
116   // to slow
117   //((scc_info *)get_irn_link(n))->dfn = dfn;
118   ((scc_info *)n->link)->dfn = dfn;
119 }
120
121 static INLINE int
122 get_irn_dfn (ir_node *n) {
123   assert(get_irn_link(n));
124   // to slow
125   //return ((scc_info *)get_irn_link(n))->dfn;
126   return ((scc_info *)n->link)->dfn;
127 }
128
129 #if 0
130 /* Replaced node loop map by real field as hash access dominates runtime
131  * of the algorithm. ! */
132 /* Uses temporary information to set the loop */
133 static INLINE void
134 set_irn_loop (ir_node *n, ir_loop* loop) {
135   assert(node_loop_map && "not initialized!");
136   pmap_insert(node_loop_map, (void *)n, (void *)loop);
137 }
138
139 /* Uses temporary information to get the loop */
140 INLINE ir_loop *
141 get_irn_loop (ir_node *n) {
142   ir_loop *res = NULL;
143   if (!node_loop_map) return NULL;
144
145   if (pmap_contains(node_loop_map, (void *)n))
146     res = (ir_loop *) pmap_get(node_loop_map, (void *)n);
147
148   return res;
149 }
150 #else
151 static INLINE void
152 set_irn_loop (ir_node *n, ir_loop* loop) {
153   n->loop = loop;
154 }
155
156 /* Uses temporary information to get the loop */
157 INLINE ir_loop *
158 get_irn_loop (ir_node *n) {
159   return n->loop;
160 }
161 #endif
162
163
164 #if 0
165 static ir_loop *find_nodes_loop (ir_node *n, ir_loop *l) {
166   int i;
167   ir_loop *res = NULL;
168
169   /* Test whether n is contained in this loop. */
170   for (i = 0; i < get_loop_n_nodes(l); i++)
171     if (n == get_loop_node(l, i)) return l;
172
173   /* Is this a leave in the loop tree? If so loop not found. */
174   if (get_loop_n_sons(l) == 0) return NULL;
175
176   /* Else descend in the loop tree. */
177   for (i = 0; i < get_loop_n_sons(l); i++) {
178     res = find_nodes_loop(n, get_loop_son(l, i));
179     if (res) break;
180   }
181   return res;
182 }
183
184 /* @@@ temporary implementation, costly!!! */
185 ir_loop * get_irn_loop(ir_node *n) {
186   ir_loop *l = get_irg_loop(current_ir_graph);
187   l = find_nodes_loop(n, l);
188   return l;
189 }
190 #endif
191
192 /**********************************************************************/
193 /* A stack.                                                          **/
194 /**********************************************************************/
195
196 static ir_node **stack = NULL;
197 static int tos = 0;                /* top of stack */
198
199 static INLINE void init_stack(void) {
200   if (stack) {
201     ARR_RESIZE (ir_node *, stack, 1000);
202   } else {
203     stack = NEW_ARR_F (ir_node *, 1000);
204   }
205   tos = 0;
206 }
207
208 #if 0
209 static INLINE void free_stack(void) {
210   DEL_ARR_F(stack);
211   stack = NULL;
212   tos = 0;
213 }
214 #endif
215
216 static INLINE void
217 push (ir_node *n)
218 {
219   /*DDMN(n);*/
220
221   if (tos == ARR_LEN (stack)) {
222     int nlen = ARR_LEN (stack) * 2;
223     ARR_RESIZE (ir_node *, stack, nlen);
224   }
225   stack [tos++] = n;
226   mark_irn_in_stack(n);
227 }
228
229 static INLINE ir_node *
230 pop (void)
231 {
232   ir_node *n = stack[--tos];
233   mark_irn_not_in_stack(n);
234   return n;
235 }
236
237 /* The nodes up to n belong to the current loop.
238    Removes them from the stack and adds them to the current loop. */
239 static INLINE void
240 pop_scc_to_loop (ir_node *n)
241 {
242   ir_node *m;
243   int i = 0;
244
245   /*for (;;) {*/
246   do
247     {
248     m = pop();
249     loop_node_cnt++;
250     set_irn_dfn(m, loop_node_cnt);
251     add_loop_node(current_loop, m);
252     set_irn_loop(m, current_loop);
253     i++;
254     /*    if (m==n) break;*/
255     } while(m != n);
256
257   if(i > 1)
258     printf("Mehr als eine Iteration!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
259 }
260
261 /* GL ??? my last son is my grandson???  Removes loops with no
262    ir_nodes in them.  Such loops have only another loop as son. (Why
263    can't they have two loops as sons? Does it never get that far? ) */
264 void close_loop (ir_loop *l)
265 {
266   int last = get_loop_n_elements(l) - 1;
267   loop_element lelement = get_loop_element(l, last);
268   ir_loop *last_son = lelement.son;
269
270   if (get_kind(last_son) == k_ir_loop &&
271       get_loop_n_elements(last_son) == 1)
272     {
273       ir_loop *gson;
274
275       lelement = get_loop_element(last_son, 0);
276       gson = lelement.son;
277       if(get_kind(gson) == k_ir_loop)
278         {
279           loop_element new_last_son;
280
281           gson -> outer_loop = l;
282           new_last_son.son = gson;
283           l -> children[last] = new_last_son;
284         }
285     }
286
287   current_loop = l;
288 }
289
290 /* Removes and unmarks all nodes up to n from the stack.
291    The nodes must be visited once more to assign them to a scc. */
292 static INLINE void
293 pop_scc_unmark_visit (ir_node *n)
294 {
295   ir_node *m = NULL;
296
297   while (m != n) {
298     m = pop();
299     set_irn_visited(m, 0);
300   }
301 }
302
303 /**********************************************************************/
304 /* The loop datastructure.                                           **/
305 /**********************************************************************/
306
307 /* Allocates a new loop as son of current_loop.  Sets current_loop
308    to the new loop and returns the father. */
309 static ir_loop *new_loop (void) {
310   ir_loop *father, *son;
311
312   father = current_loop;
313
314   son = (ir_loop *) obstack_alloc (outermost_ir_graph->obst, sizeof (ir_loop));
315   memset (son, 0, sizeof (ir_loop));
316   son->kind = k_ir_loop;
317   son->children = NEW_ARR_F (loop_element, 0);
318   son->n_nodes = 0;
319   son->n_sons=0;
320   if (father) {
321     son->outer_loop = father;
322     add_loop_son(father, son);
323     son->depth = father->depth+1;
324   } else {  /* The root loop */
325     son->outer_loop = son;
326     son->depth = 0;
327   }
328
329 #ifdef DEBUG_libfirm
330   son->loop_nr = get_irp_new_node_nr();
331   son->link = NULL;
332 #endif
333
334   current_loop = son;
335   return father;
336 }
337
338 #if 0
339 /* Finishes the datastructures, copies the arrays to the obstack
340    of current_ir_graph.
341    A. Schoesser: Caution: loop -> sons is gone. */
342 static void mature_loop (ir_loop *loop) {
343   ir_loop **new_sons;
344
345   new_sons = NEW_ARR_D (ir_loop *, current_ir_graph->obst, ARR_LEN(loop->sons));
346   memcpy (new_sons, loop->sons, sizeof (ir_loop *) * ARR_LEN(loop->sons));
347   DEL_ARR_F(loop->sons);
348   loop->sons = new_sons;
349 }
350 #endif
351
352 /* Returns outer loop, itself if outermost. */
353 ir_loop *get_loop_outer_loop (ir_loop *loop) {
354   assert(loop && loop->kind == k_ir_loop);
355   return loop->outer_loop;
356 }
357
358 /* Returns nesting depth of this loop */
359 int get_loop_depth (ir_loop *loop) {
360   assert(loop); assert(loop->kind == k_ir_loop);
361   return loop->depth;
362 }
363
364 /* Returns the number of inner loops */
365 int      get_loop_n_sons (ir_loop *loop) {
366   assert(loop && loop->kind == k_ir_loop);
367   return(loop -> n_sons);
368 }
369
370 /* Returns the pos`th loop_node-child              *
371  * TODO: This method isn`t very efficient !        *
372  * Returns NULL if there isnt`t a pos`th loop_node */
373 ir_loop *get_loop_son (ir_loop *loop, int pos) {
374   int child_nr = 0, loop_nr = -1;
375
376   assert(loop && loop->kind == k_ir_loop);
377   while(child_nr < ARR_LEN(loop->children))
378    {
379     if(*(loop -> children[child_nr].kind) == k_ir_loop)
380       loop_nr++;
381     if(loop_nr == pos)
382       return(loop -> children[child_nr].son);
383     child_nr++;
384    }
385   return NULL;
386 }
387
388 /* Use EXCLUSIVELY this function to add sons, otherwise the loop->n_sons
389    is invalid! */
390
391 static INLINE void
392 add_loop_son(ir_loop *loop, ir_loop *son) {
393   loop_element lson;
394   lson.son = son;
395   assert(loop && loop->kind == k_ir_loop);
396   assert(get_kind(son) == k_ir_loop);
397   ARR_APP1 (loop_element, loop->children, lson);
398   loop -> n_sons++;
399 }
400
401 /* Returns the number of nodes in the loop */
402 int      get_loop_n_nodes (ir_loop *loop) {
403   assert(loop); assert(loop->kind == k_ir_loop);
404   return loop -> n_nodes;
405 /*  return ARR_LEN(loop->nodes); */
406 }
407
408 /* Returns the pos`th ir_node-child                *
409  * TODO: This method isn`t very efficient !        *
410  * Returns NULL if there isnt`t a pos`th ir_node   */
411 ir_node *get_loop_node (ir_loop *loop, int pos) {
412   int child_nr, node_nr = -1;
413
414   assert(loop && loop->kind == k_ir_loop);
415   assert(pos < get_loop_n_nodes(loop));
416
417   for (child_nr = 0; child_nr < ARR_LEN(loop->children); child_nr++) {
418     if(*(loop -> children[child_nr].kind) == k_ir_node)
419       node_nr++;
420     if(node_nr == pos)
421       return(loop -> children[child_nr].node);
422   }
423   assert(0 && "no child at pos found");
424   return NULL;
425 }
426
427 /* Use EXCLUSIVELY this function to add nodes, otherwise the loop->n_nodes
428    is invalid! */
429
430 static INLINE void
431 add_loop_node(ir_loop *loop, ir_node *n) {
432   loop_element ln;
433   ln.node = n;
434   assert(loop && loop->kind == k_ir_loop);
435   assert(get_kind(n) == k_ir_node);
436   ARR_APP1 (loop_element, loop->children, ln);
437   loop->n_nodes++;
438 }
439
440 /** Returns the number of elements contained in loop.  */
441 int get_loop_n_elements (ir_loop *loop) {
442   assert(loop && loop->kind == k_ir_loop);
443   return(ARR_LEN(loop->children));
444 }
445
446 /*
447  Returns the pos`th loop element.
448  This may be a loop_node or a ir_node. The caller of this function has
449  to check the *(loop_element.kind) field for "k_ir_node" or "k_ir_loop"
450  and then select the apropriate "loop_element.node" or "loop_element.son".
451 */
452
453 loop_element get_loop_element (ir_loop *loop, int pos) {
454   assert(loop && loop->kind == k_ir_loop && pos < ARR_LEN(loop->children));
455
456   return(loop -> children[pos]);
457 }
458
459 int get_loop_element_pos(ir_loop *loop, void *le) {
460   int i;
461   assert(loop && loop->kind == k_ir_loop);
462
463   for (i = 0; i < get_loop_n_elements(loop); i++)
464     if (get_loop_element(loop, i).node == le) return i;
465   return -1;
466 }
467
468 int get_loop_loop_nr(ir_loop *loop) {
469   assert(loop && loop->kind == k_ir_loop);
470 #ifdef DEBUG_libfirm
471   return loop->loop_nr;
472 #else
473   return (int)loop;
474 #endif
475 }
476
477
478 /** A field to connect additional information to a loop.  Only valid
479     if libfirm_debug is set. */
480 void  set_loop_link (ir_loop *loop, void *link) {
481   assert(loop && loop->kind == k_ir_loop);
482 #ifdef DEBUG_libfirm
483   loop->link = link;
484 #endif
485 }
486 void *get_loop_link (const ir_loop *loop) {
487   assert(loop && loop->kind == k_ir_loop);
488 #ifdef DEBUG_libfirm
489   return loop->link;
490 #else
491   return NULL;
492 #endif
493 }
494
495 /* The outermost loop is remarked in the surrounding graph. */
496 void     set_irg_loop(ir_graph *irg, ir_loop *loop) {
497   assert(irg);
498   irg->loop = loop;
499 }
500 ir_loop *get_irg_loop(ir_graph *irg) {
501   assert(irg);
502   return irg->loop;
503 }
504
505
506 /**********************************************************************/
507 /* Constructing and destructing the loop/backedge information.       **/
508 /**********************************************************************/
509
510 /* Initialization steps. **********************************************/
511
512 static INLINE void
513 init_node (ir_node *n, void *env) {
514   set_irn_link (n, new_scc_info());
515   clear_backedges(n);
516 #if 0
517   /* Also init nodes not visible in intraproc_view. */
518     /* @@@ init_node is called for too many nodes -- this wastes memory!.
519        The mem is not lost as its on the obstack. */
520   if (get_irn_op(n) == op_Filter) {
521     for (i = 0; i < get_Filter_n_cg_preds(n); i++)
522       init_node(get_Filter_cg_pred(n, i), NULL);
523   }
524   if (get_irn_op(n) == op_Block) {
525     for (i = 0; i < get_Block_cg_n_cfgpreds(n); i++) {
526       init_node(get_Block_cg_cfgpred(n, i), NULL);
527     }
528   }
529   /* The following pattern matches only after a call from above pattern. */
530   if ((get_irn_op(n) == op_Proj) /*&& (get_Proj_proj(n) == 0)*/) {
531     /* @@@ init_node is called for every proj -- this wastes memory!.
532        The mem is not lost as its on the obstack. */
533     ir_node *cb = get_Proj_pred(n);
534     if ((get_irn_op(cb) == op_CallBegin) ||
535         (get_irn_op(cb) == op_EndReg) ||
536         (get_irn_op(cb) == op_EndExcept)) {
537       init_node(cb, NULL);
538       init_node(get_nodes_Block(cb), NULL);
539     }
540   }
541 #endif
542 }
543
544 static INLINE void
545 init_scc_common (void) {
546   current_dfn = 1;
547   loop_node_cnt = 0;
548   if (!node_loop_map) node_loop_map = pmap_create();
549   init_stack();
550 }
551
552 static INLINE void
553 init_scc (ir_graph *irg) {
554   init_scc_common();
555   irg_walk_graph (irg, init_node, NULL, NULL);
556   /*
557   irg_walk (irg, link_to_reg_end, NULL, NULL);
558   */
559 }
560
561 static INLINE void
562 init_ip_scc (void) {
563   init_scc_common();
564   cg_walk (init_node, NULL, NULL);
565 }
566
567 /* Condition for breaking the recursion. */
568 static bool is_outermost_Start(ir_node *n) {
569   /* Test whether this is the outermost Start node.  If so
570      recursion must end. */
571   if ((get_irn_op(n) == op_Block)     &&
572       (get_Block_n_cfgpreds(n) == 1)  &&
573       (get_irn_op(skip_Proj(get_Block_cfgpred(n, 0))) == op_Start) &&
574       (get_nodes_Block(skip_Proj(get_Block_cfgpred(n, 0))) == n)) {
575     return true;
576   }
577 #if 0
578   /*  @@@ Bad condition:
579       not possible in interprocedural view as outermost_graph is
580       not necessarily the only with a dead-end start block.
581       Besides current_ir_graph is not set properly. */
582   if ((get_irn_op(n) == op_Block) &&
583       (n == get_irg_start_block(current_ir_graph))) {
584     if ((!interprocedural_view)  ||
585         (current_ir_graph == outermost_ir_graph))
586       return true;
587   }
588 #endif
589   return false;
590 }
591
592 /* Don't walk from nodes to blocks except for Control flow operations. */
593 static INLINE int
594 get_start_index(ir_node *n) {
595   if (is_cfop(n) || is_fragile_op(n) || get_irn_op(n) == op_Start)
596     return -1;
597   else
598     return 0;
599 }
600 #if 0
601 /* Returns current_ir_graph and set it to the irg of predecessor index
602    of node n. */
603 static INLINE ir_graph *
604 switch_irg (ir_node *n, int index) {
605   ir_graph *old_current = current_ir_graph;
606
607   if (interprocedural_view) {
608     /* Only Filter and Block nodes can have predecessors in other graphs. */
609     if (get_irn_op(n) == op_Filter)
610       n = get_nodes_Block(n);
611     if (get_irn_op(n) == op_Block) {
612       ir_node *cfop = skip_Proj(get_Block_cfgpred(n, index));
613       if (is_ip_cfop(cfop)) {
614         current_ir_graph = get_irn_irg(cfop);
615         set_irg_visited(current_ir_graph, get_max_irg_visited());
616       }
617     }
618   }
619
620   return old_current;
621 }
622
623 /* Walks up the stack passing n and then finding the node
624    where we walked into the irg n is contained in.
625    Here we switch the irg. */
626 static ir_graph *
627 find_irg_on_stack (ir_node *n) {
628   ir_node *m;
629   ir_graph *old_current = current_ir_graph;
630   int i;
631
632   if (interprocedural_view) {
633     for (i = tos; i >= 0; i--) {
634       if (stack[i] == n) break;
635     }
636     if (i < 0) i = tos;
637
638     assert (i >= 0);
639     for (; i >= 0; i--) {
640       m = stack[i];
641       /*printf(" Visiting %d ", i); DDMN(m);*/
642       if (is_ip_cfop(m)) {
643         current_ir_graph = get_irn_irg(m);
644         break;
645       }
646       if (get_irn_op(m) == op_Filter) {
647         /* Find the corresponding ip_cfop */
648         ir_node *pred = stack[i+1];
649         int j;
650         for (j = 0; j < get_Filter_n_cg_preds(m); j++)
651           if (get_Filter_cg_pred(m, j) == pred) break;
652         if (j >= get_Filter_n_cg_preds(m))
653           /* It is a filter we didn't pass as the predecessors are marked. */
654           continue;
655         assert(get_Filter_cg_pred(m, j) == pred);
656         switch_irg(m, j);
657         break;
658       }
659     }
660   }
661
662   return old_current;
663 }
664 #endif
665
666 #if 0
667 static void test(ir_node *pred, ir_node *root, ir_node *this) {
668   int i;
669   if (get_irn_uplink(pred) >= get_irn_uplink(root)) return;
670
671   printf("this: %d ", get_irn_uplink(this)); DDMN(this);
672   printf("pred: %d ", get_irn_uplink(pred)); DDMN(pred);
673   printf("root: %d ", get_irn_uplink(root)); DDMN(root);
674
675   printf("tos: %d\n", tos);
676
677   for (i = tos; i >= 0; i--) {
678     ir_node *n = stack[i];
679     if (!n) continue;
680     printf(" uplink: %d, pos: %d ", get_irn_uplink(n), i); DDMN(n);
681   }
682 }
683 #endif
684
685 /* Test for legal loop header: Block, Phi, ... */
686 INLINE static bool is_possible_loop_head(ir_node *n) {
687   ir_op *op = get_irn_op(n);
688   return ((op == op_Block) ||
689           (op == op_Phi) ||
690           ((op == op_Filter) && interprocedural_view));
691 }
692
693 /* Returns true if n is a loop header, i.e., it is a Block, Phi
694    or Filter node and has predecessors within the loop and out
695    of the loop.
696    @arg root: only needed for assertion. */
697 static bool
698 is_head (ir_node *n, ir_node *root)
699 {
700   int i, arity;
701   int some_outof_loop = 0, some_in_loop = 0;
702
703   /* Test for legal loop header: Block, Phi, ... */
704   if (!is_possible_loop_head(n))
705     return false;
706
707   if (!is_outermost_Start(n)) {
708     arity = get_irn_arity(n);
709     for (i = get_start_index(n); i < arity; i++) {
710       ir_node *pred = get_irn_n(n, i);
711       assert(pred);
712       if (is_backedge(n, i)) continue;
713       if (!irn_is_in_stack(pred)) {
714         some_outof_loop = 1;
715       } else {
716         assert(get_irn_uplink(pred) >= get_irn_uplink(root));
717         some_in_loop = 1;
718       }
719     }
720   }
721   return some_outof_loop && some_in_loop;
722 }
723
724 /* Returns index of the predecessor with the smallest dfn number
725    greater-equal than limit. */
726 static int
727 smallest_dfn_pred (ir_node *n, int limit)
728 {
729   int i, index = -2, min = -1;
730
731   if (!is_outermost_Start(n)) {
732     int arity = get_irn_arity(n);
733     for (i = get_start_index(n); i < arity; i++) {
734       ir_node *pred = get_irn_n(n, i);
735       assert(pred);
736       if (is_backedge(n, i) || !irn_is_in_stack(pred)) continue;
737       if (get_irn_dfn(pred) >= limit && (min == -1 || get_irn_dfn(pred) < min)) {
738         index = i;
739         min = get_irn_dfn(pred);
740       }
741     }
742   }
743   return index;
744 }
745
746 /* Returns index of the predecessor with the largest dfn number. */
747 static int
748 largest_dfn_pred (ir_node *n)
749 {
750   int i, index = -2, max = -1;
751
752   if (!is_outermost_Start(n)) {
753     int arity = get_irn_arity(n);
754     for (i = get_start_index(n); i < arity; i++) {
755       ir_node *pred = get_irn_n(n, i);
756       if (is_backedge (n, i) || !irn_is_in_stack(pred)) continue;
757       if (get_irn_dfn(pred) > max) {
758         index = i;
759         max = get_irn_dfn(pred);
760       }
761     }
762   }
763   return index;
764 }
765
766 /* Searches the stack for possible loop heads.  Tests these for backedges.
767    If it finds a head with an unmarked backedge it marks this edge and
768    returns the tail of the loop.
769    If it finds no backedge returns NULL.
770    ("disable_backedge" in fiasco) */
771
772 static ir_node *
773 find_tail (ir_node *n) {
774   ir_node *m;
775   int i, res_index = -2;
776
777   /*
778     if (!icfg && rm_cyclic_phis && remove_cyclic_phis (n)) return NULL;
779   */
780
781   m = stack[tos-1];  /* tos = top of stack */
782   if (is_head (m, n)) {
783     res_index = smallest_dfn_pred(m, 0);
784     if ((res_index == -2) &&  /* no smallest dfn pred found. */
785         (n == m))
786       return NULL;
787   } else {
788     if (m == n) return NULL;
789     for (i = tos-2; ; --i) {
790       m = stack[i];
791       if (is_head (m, n)) {
792         res_index = smallest_dfn_pred (m, get_irn_dfn(m) + 1);
793         if (res_index == -2)  /* no smallest dfn pred found. */
794           res_index = largest_dfn_pred (m);
795         break;
796       }
797     }
798   }
799   assert (res_index > -2);
800
801   set_backedge (m, res_index);
802   return is_outermost_Start(n) ? NULL : get_irn_n(m, res_index);
803 }
804
805
806 /* The core algorithm. *****************************************/
807
808 static void scc (ir_node *n) {
809   int i;
810
811   if (irn_visited(n)) return;
812   mark_irn_visited(n);
813
814   /* Initialize the node */
815   set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
816   set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
817   set_irn_loop(n, NULL);
818   current_dfn ++;
819   push(n);
820
821   /* AS: get_start_index might return -1 for Control Flow Nodes, and thus a negative
822      array index would be passed to is_backedge(). But CFG Nodes dont't have a backedge array,
823      so is_backedge does not access array[-1] but correctly returns false! */
824
825   if (!is_outermost_Start(n)) {
826     int arity = get_irn_arity(n);
827     for (i = get_start_index(n); i < arity; i++) {
828       ir_node *m;
829       if (is_backedge(n, i)) continue;
830
831       m = get_irn_n(n, i); /* get_irn_ip_pred(n, i); */
832       //if ((!m) || (get_irn_op(m) == op_Unknown)) continue;
833       scc (m);
834       if (irn_is_in_stack(m)) {
835         /* Uplink of m is smaller if n->m is a backedge.
836            Propagate the uplink to mark the loop. */
837         if (get_irn_uplink(m) < get_irn_uplink(n))
838           set_irn_uplink(n, get_irn_uplink(m));
839       }
840     }
841   }
842
843   if (get_irn_dfn(n) == get_irn_uplink(n)) {
844     /* This condition holds for the node with the incoming backedge.
845        AS: That is: For the loop head. */
846     ir_node *tail = find_tail(n);
847     if (tail) {
848       /* We found a new inner loop! */
849
850       /* This is an adaption of the algorithm from fiasco / optscc to
851        * avoid loops without Block or Phi as first node.  This should
852        * severely reduce the number of evaluations of nodes to detect
853        * a fixpoint in the heap analyses.
854        * Further it avoids loops without firm nodes that cause errors
855        * in the heap analyses. */
856 #define NO_LOOPS_WITHOUT_HEAD 1
857 #if NO_LOOPS_WITHOUT_HEAD
858       ir_loop *l;
859       int close;
860       if (get_loop_n_elements(current_loop) > 0) {
861         l = new_loop();
862         close = 1;
863       } else {
864         l = current_loop;
865         close = 0;
866       }
867 #else
868       ir_loop *l = new_loop();
869 #endif
870
871       /* Remove the loop from the stack ... */
872       pop_scc_unmark_visit (n);
873       /* and recompute it in a better order; and so that it goes into
874          the new loop. */
875       // GL @@@ remove experimental stuff rem = find_irg_on_stack(tail);
876
877       scc (tail);
878       // GL @@@ remove experimental stuff current_ir_graph = rem;
879
880       assert (irn_visited(n));
881 #if NO_LOOPS_WITHOUT_HEAD
882       if (close)
883 #endif
884       close_loop(l);
885     } else {
886       /* AS: No inner loop was found. Pop all nodes from the stack
887          to the current loop. */
888       pop_scc_to_loop(n);
889     }
890   }
891 }
892
893 /* Constructs backedge information for irg. In interprocedural view constructs
894    backedges for all methods called by irg, too. */
895 void construct_backedges(ir_graph *irg) {
896   ir_graph *rem = current_ir_graph;
897   ir_loop *head_rem;
898
899   assert(!interprocedural_view &&
900          "not implemented, use construct_ip_backedges");
901
902   current_ir_graph = irg;
903   outermost_ir_graph = irg;
904
905   init_scc(current_ir_graph);
906
907   current_loop = NULL;
908   new_loop();  /* sets current_loop */
909   head_rem = current_loop; /* Just for assertion */
910
911   if (interprocedural_view) {
912     set_irg_visited(current_ir_graph, inc_max_irg_visited());
913     init_ip_walk ();
914   } else {
915     inc_irg_visited(current_ir_graph);
916   }
917
918   scc(get_irg_end(current_ir_graph));
919
920   if (interprocedural_view) finish_ip_walk();
921
922   assert(head_rem == current_loop);
923   set_irg_loop(current_ir_graph, current_loop);
924   set_irg_loopinfo_state(current_ir_graph, loopinfo_consistent);
925   assert(get_irg_loop(current_ir_graph)->kind == k_ir_loop);
926   /*
927   irg->loops = current_loop;
928   if (icfg == 1) {
929     int count = 0;
930     int depth = 0;
931     count_loop (the_loop, &count, &depth);
932     }
933   }
934   */
935   current_ir_graph = rem;
936 }
937
938
939 #if 0
940 void construct_ip_backedges (void) {
941   ir_graph *rem = current_ir_graph;
942   int rem_ipv = interprocedural_view;
943   int i, j;
944
945   outermost_ir_graph = get_irp_main_irg();
946
947   init_ip_scc();
948
949   current_loop = NULL;
950   new_loop();  /* sets current_loop */
951   interprocedural_view = 1;
952
953   inc_max_irg_visited();
954   for (i = 0; i < get_irp_n_irgs(); i++)
955     set_irg_visited(get_irp_irg(i), get_max_irg_visited());
956
957   for (i = 0; i < get_irp_n_irgs(); i++) {
958     ir_node *sb;
959     current_ir_graph = get_irp_irg(i);
960     /* Find real entry points */
961     sb = get_irg_start_block(current_ir_graph);
962     if ((get_Block_n_cfgpreds(sb) > 1) ||
963         (get_nodes_Block(get_Block_cfgpred(sb, 0)) != sb)) continue;
964     /* Compute scc for this graph */
965     outermost_ir_graph = current_ir_graph;
966     set_irg_visited(outermost_ir_graph, get_max_irg_visited());
967     scc(get_irg_end(current_ir_graph));
968     for (j = 0; j < get_End_n_keepalives(get_irg_end(outermost_ir_graph)); j++)
969       scc(get_End_keepalive(get_irg_end(outermost_ir_graph), j));
970   }
971
972   set_irg_loop(outermost_ir_graph, current_loop);
973   set_irg_loopinfo_state(current_ir_graph, loopinfo_ip_consistent);
974   assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
975
976   current_ir_graph = rem;
977   interprocedural_view = rem_ipv;
978 }
979 #else
980 void construct_ip_backedges (void) {
981   ir_graph *rem = current_ir_graph;
982   int rem_ipv = interprocedural_view;
983   int i;
984
985   outermost_ir_graph = get_irp_main_irg();
986
987   init_ip_scc();
988
989   current_loop = NULL;
990   new_loop();  /* sets current_loop */
991   interprocedural_view = 1;
992
993   inc_max_irg_visited();
994   for (i = 0; i < get_irp_n_irgs(); i++)
995     set_irg_visited(get_irp_irg(i), get_max_irg_visited());
996
997   /** We have to start the walk at the same nodes as cg_walk. **/
998   /* Walk starting at unreachable procedures. Only these
999    * have End blocks visible in interprocedural view. */
1000   for (i = 0; i < get_irp_n_irgs(); i++) {
1001     ir_node *sb;
1002     current_ir_graph = get_irp_irg(i);
1003
1004     sb = get_irg_start_block(current_ir_graph);
1005
1006     if ((get_Block_n_cfgpreds(sb) > 1) ||
1007         (get_nodes_block(get_Block_cfgpred(sb, 0)) != sb)) continue;
1008
1009     scc(get_irg_end(current_ir_graph));
1010   }
1011
1012   /* Check whether we walked all procedures: there could be procedures
1013      with cyclic calls but no call from the outside. */
1014   for (i = 0; i < get_irp_n_irgs(); i++) {
1015     ir_node *sb;
1016     current_ir_graph = get_irp_irg(i);
1017
1018     /* Test start block: if inner procedure end and end block are not
1019      * visible and therefore not marked. */
1020     sb = get_irg_start_block(current_ir_graph);
1021     if (get_irn_visited(sb) < get_irg_visited(current_ir_graph)) scc(sb);
1022   }
1023
1024   /* Walk all endless loops in inner procedures.
1025    * We recognize an inner procedure if the End node is not visited. */
1026   for (i = 0; i < get_irp_n_irgs(); i++) {
1027     ir_node *e;
1028     current_ir_graph = get_irp_irg(i);
1029
1030     e = get_irg_end(current_ir_graph);
1031     if (get_irn_visited(e) < get_irg_visited(current_ir_graph)) {
1032       int j;
1033       /* Don't visit the End node. */
1034       for (j = 0; j < get_End_n_keepalives(e); j++) scc(get_End_keepalive(e, j));
1035     }
1036   }
1037
1038   set_irg_loop(outermost_ir_graph, current_loop);
1039   set_irg_loopinfo_state(current_ir_graph, loopinfo_ip_consistent);
1040   assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
1041
1042   current_ir_graph = rem;
1043   interprocedural_view = rem_ipv;
1044 }
1045 #endif
1046
1047 static void reset_backedges(ir_node *n) {
1048   if (is_possible_loop_head(n)) {
1049     int rem = interprocedural_view;
1050     interprocedural_view = 1;
1051     clear_backedges(n);
1052     interprocedural_view = 0;
1053     clear_backedges(n);
1054     interprocedural_view = rem;
1055   }
1056 }
1057
1058 static void loop_reset_backedges(ir_loop *l) {
1059   int i;
1060   reset_backedges(get_loop_node(l, 0));
1061   for (i = 0; i < get_loop_n_nodes(l); ++i)
1062     set_irn_loop(get_loop_node(l, i), NULL);
1063   for (i = 0; i < get_loop_n_sons(l); ++i) {
1064     loop_reset_backedges(get_loop_son(l, i));
1065   }
1066 }
1067
1068 /** Removes all loop information.
1069     Resets all backedges */
1070 void free_loop_information(ir_graph *irg) {
1071   if (get_irg_loop(irg))
1072     loop_reset_backedges(get_irg_loop(irg));
1073   set_irg_loop(irg, NULL);
1074   set_irg_loopinfo_state(current_ir_graph, loopinfo_none);
1075   /* We cannot free the loop nodes, they are on the obstack. */
1076 }
1077
1078
1079 void free_all_loop_information (void) {
1080   int i;
1081   int rem = interprocedural_view;
1082   interprocedural_view = 1;  /* To visit all filter nodes */
1083   for (i = 0; i < get_irp_n_irgs(); i++) {
1084     free_loop_information(get_irp_irg(i));
1085   }
1086   pmap_destroy(node_loop_map);
1087   node_loop_map = NULL;
1088   interprocedural_view = rem;
1089 }
1090
1091
1092
1093
1094
1095 /* Debug stuff *************************************************/
1096
1097 static int test_loop_node(ir_loop *l) {
1098   int i, has_node = 0, found_problem = 0;
1099   loop_element le;
1100
1101   assert(l && l->kind == k_ir_loop);
1102
1103   if (get_loop_n_elements(l) == 0) {
1104     printf(" Loop completely empty! "); DDML(l);
1105     found_problem = 1;
1106     dump_loop(l, "-ha");
1107   }
1108
1109   le = get_loop_element(l, 0);
1110   if (*(le.kind) != k_ir_node) {
1111     assert(le.kind && *(le.kind) == k_ir_loop);
1112     printf(" First loop element is not a node! "); DDML(l);
1113     printf("                                   "); DDML(le.son);
1114
1115     found_problem = 1;
1116     dump_loop(l, "-ha");
1117   }
1118
1119   if ((*(le.kind) == k_ir_node) && !is_possible_loop_head(le.node)) {
1120     printf(" Wrong node as head! "); DDML(l);
1121     printf("                     "); DDMN(le.node);
1122     found_problem = 1;
1123     dump_loop(l, "-ha");
1124   }
1125
1126   if ((get_loop_depth(l) != 0) &&
1127       (*(le.kind) == k_ir_node) && !has_backedges(le.node)) {
1128     printf(" Loop head has no backedges! "); DDML(l);
1129     printf("                             "); DDMN(le.node);
1130     found_problem = 1;
1131     dump_loop(l, "-ha");
1132   }
1133
1134   /* Recur */
1135   has_node = 0;
1136   for (i = 0; i < get_loop_n_elements(l); ++i) {
1137     le = get_loop_element(l, i);
1138     if (*(le.kind) == k_ir_node)
1139       has_node++;
1140     else
1141       if (test_loop_node(le.son)) found_problem = 1;
1142   }
1143
1144   if (has_node == 0) {
1145     printf(" Loop has no firm node! "); DDML(l);
1146     found_problem = 1;
1147     dump_loop(l, "-ha");
1148   }
1149
1150   if (get_loop_loop_nr(l) == 11819)
1151     dump_loop(l, "-ha-debug");
1152
1153   return found_problem;
1154 }
1155
1156 /** Prints all loop nodes that
1157  *  - do not have any firm nodes, only loop sons
1158  *  - the header is not a Phi, Block or Filter.
1159  */
1160 void find_strange_loop_nodes(ir_loop *l) {
1161   int found_problem = 0;
1162   printf("\nTesting loop "); DDML(l);
1163   found_problem = test_loop_node(l);
1164   printf("Finished Test\n\n");
1165   if (found_problem) exit(0);
1166
1167 }