remove #ifdef HAVE_CONFIG_Hs
[libfirm] / ir / ana / irscc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    Compute the strongly connected regions and build
23  *              backedge/loop datastructures.
24  *              A variation on the Tarjan algorithm. See also [Trapp:99],
25  *              Chapter 5.2.1.2.
26  * @author   Goetz Lindenmaier
27  * @date     7.2002
28  * @version  $Id$
29  */
30 #include "config.h"
31
32 #ifdef HAVE_STRING_H
33 # include <string.h>
34 #endif
35 #ifdef HAVE_STDLIB_H
36 # include <stdlib.h>
37 #endif
38
39 #include "irloop_t.h"
40
41 #include "irprog_t.h"
42 #include "irgraph_t.h"
43 #include "irnode_t.h"
44 #include "irgwalk.h"
45 #include "irdump.h"
46 #include "array.h"
47 #include "pmap.h"
48
49 /* A variant of the loop tree that avoids loops without head.
50    This reduces the depth of the loop tree. */
51 #define NO_LOOPS_WITHOUT_HEAD 1
52
53 /** The outermost graph the scc is computed for. */
54 static ir_graph *outermost_ir_graph;
55 /** Current loop construction is working on. */
56 static ir_loop *current_loop;
57 /** Counts the number of allocated loop nodes.
58  *  Each loop node gets a unique number.
59  *  @todo What for? ev. remove.
60  */
61 static int loop_node_cnt = 0;
62 /** Counter to generate depth first numbering of visited nodes. */
63 static int current_dfn = 1;
64
65 static int max_loop_depth = 0;
66
67 void link_to_reg_end(ir_node *n, void *env);
68 void set_projx_link(ir_node *cb_projx, ir_node *end_projx);
69 ir_node *get_projx_link(ir_node *cb_projx);
70
71 /**********************************************************************/
72 /* Node attributes                                                   **/
73 /**********************************************************************/
74
75 /**********************************************************************/
76 /* Node attributes needed for the construction.                      **/
77 /**********************************************************************/
78
79 typedef struct scc_info {
80         int in_stack;          /**< Marks whether node is on the stack. */
81         int dfn;               /**< Depth first search number. */
82         int uplink;            /**< dfn number of ancestor. */
83         /*  ir_loop *loop;         *//* Refers to the containing loop. */
84         /*
85             struct section *section;
86             xset def;
87             xset use;
88         */
89 } scc_info;
90
91 /**
92  * Allocates a new SCC info on the given obstack.
93  */
94 static INLINE scc_info *new_scc_info(struct obstack *obst) {
95         scc_info *info = obstack_alloc(obst, sizeof(*info));
96         memset(info, 0, sizeof(*info));
97         return info;
98 }
99
100 /**
101  * Mark node n being on the SCC stack.
102  */
103 static INLINE void mark_irn_in_stack(ir_node *n) {
104         scc_info *scc = get_irn_link(n);
105         assert(scc);
106         scc->in_stack = 1;
107 }
108
109 /**
110 * Mark node n NOT being on the SCC stack.
111 */
112 static INLINE void mark_irn_not_in_stack(ir_node *n) {
113         scc_info *scc = get_irn_link(n);
114         assert(scc);
115         scc->in_stack = 0;
116 }
117
118 /**
119  * Checks if a node is on the SCC stack.
120  */
121 static INLINE int irn_is_in_stack(ir_node *n) {
122         scc_info *scc = get_irn_link(n);
123         assert(scc);
124         return scc->in_stack;
125 }
126
127 /**
128  * Sets the uplink number for a node.
129  */
130 static INLINE void set_irn_uplink(ir_node *n, int uplink) {
131         scc_info *scc = get_irn_link(n);
132         assert(scc);
133         scc->uplink = uplink;
134 }
135
136 /**
137  * Returns the uplink number for a node.
138  */
139 static int get_irn_uplink(ir_node *n) {
140         scc_info *scc = get_irn_link(n);
141         assert(scc);
142         return scc->uplink;
143 }
144
145 /**
146  * Sets the depth-first-search number for a node.
147  */
148 static INLINE void set_irn_dfn(ir_node *n, int dfn) {
149         scc_info *scc = get_irn_link(n);
150         assert(scc);
151         scc->dfn = dfn;
152 }
153
154 /**
155  * Returns the depth-first-search number of a node.
156  */
157 static int get_irn_dfn(ir_node *n) {
158         scc_info *scc = get_irn_link(n);
159         assert(scc);
160         return scc->dfn;
161 }
162
163 #if 0
164 static ir_loop *find_nodes_loop(ir_node *n, ir_loop *l) {
165         int i;
166         ir_loop *res = NULL;
167
168         /* Test whether n is contained in this loop. */
169         for (i = 0; i < get_loop_n_nodes(l); i++)
170                 if (n == get_loop_node(l, i)) return l;
171
172         /* Is this a leave in the loop tree? If so loop not found. */
173         if (get_loop_n_sons(l) == 0) return NULL;
174
175         /* Else descend in the loop tree. */
176         for (i = 0; i < get_loop_n_sons(l); i++) {
177                 res = find_nodes_loop(n, get_loop_son(l, i));
178                 if (res) break;
179         }
180         return res;
181 }
182
183 /* @@@ temporary implementation, costly!!! */
184 ir_loop * get_irn_loop(ir_node *n) {
185         ir_loop *l = get_irg_loop(current_ir_graph);
186         l = find_nodes_loop(n, l);
187         return l;
188 }
189 #endif
190
191 /**********************************************************************/
192 /* A stack.                                                          **/
193 /**********************************************************************/
194
195 static ir_node **stack = NULL;
196 static int tos = 0;                /* top of stack */
197
198 /**
199  * initializes the stack
200  */
201 static INLINE void init_stack(void) {
202         if (stack) {
203                 ARR_RESIZE(ir_node *, stack, 1000);
204         } else {
205                 stack = NEW_ARR_F(ir_node *, 1000);
206         }
207         tos = 0;
208 }
209
210 /**
211  * Frees the stack.
212  */
213 static void finish_stack(void) {
214         DEL_ARR_F(stack);
215         stack = NULL;
216 }
217
218 /**
219  * push a node onto the stack
220  *
221  * @param n  The node to push
222  */
223 static INLINE void push(ir_node *n) {
224         if (tos == ARR_LEN(stack)) {
225                 int nlen = ARR_LEN(stack) * 2;
226                 ARR_RESIZE(ir_node *, stack, nlen);
227         }
228         stack [tos++] = n;
229         mark_irn_in_stack(n);
230 }
231
232 /**
233  * pop a node from the stack
234  *
235  * @return  The topmost node
236  */
237 static INLINE ir_node *pop(void) {
238         ir_node *n = stack[--tos];
239         mark_irn_not_in_stack(n);
240         return n;
241 }
242
243 /**
244  * The nodes up to n belong to the current loop.
245  * Removes them from the stack and adds them to the current loop.
246  */
247 static INLINE void pop_scc_to_loop(ir_node *n) {
248         ir_node *m;
249         int i = 0;
250
251         do {
252                 m = pop();
253
254                 loop_node_cnt++;
255                 set_irn_dfn(m, loop_node_cnt);
256                 add_loop_node(current_loop, m);
257                 set_irn_loop(m, current_loop);
258                 ++i;
259         } while (m != n);
260
261         /* i might be bigger than 1 for dead (and that's why bad) loops */
262         /* if(i > 1)
263                 printf("Mehr als eine Iteration!!!!!!!!!!!!!!!!!!!!!!!!!!!!11111\n");
264          */
265 }
266
267 /* GL ??? my last son is my grandson???  Removes loops with no
268    ir_nodes in them.  Such loops have only another loop as son. (Why
269    can't they have two loops as sons? Does it never get that far? ) */
270 static void close_loop(ir_loop *l) {
271         int last = get_loop_n_elements(l) - 1;
272         loop_element lelement = get_loop_element(l, last);
273         ir_loop *last_son = lelement.son;
274
275         if (get_kind(last_son) == k_ir_loop &&
276                 get_loop_n_elements(last_son) == 1) {
277                         ir_loop *gson;
278
279                         lelement = get_loop_element(last_son, 0);
280                         gson = lelement.son;
281
282                         if (get_kind(gson) == k_ir_loop) {
283                                 loop_element new_last_son;
284
285                                 gson->outer_loop = l;
286                                 new_last_son.son = gson;
287                                 l->children[last] = new_last_son;
288                         }
289         }
290
291         current_loop = l;
292 }
293
294 /* Removes and unmarks all nodes up to n from the stack.
295    The nodes must be visited once more to assign them to a scc. */
296 static INLINE void pop_scc_unmark_visit(ir_node *n) {
297         ir_node *m = NULL;
298
299         while (m != n) {
300                 m = pop();
301                 set_irn_visited(m, 0);
302         }
303 }
304
305 /**********************************************************************/
306 /* The loop datastructure.                                           **/
307 /**********************************************************************/
308
309 /* Allocates a new loop as son of current_loop.  Sets current_loop
310    to the new loop and returns the father. */
311 static ir_loop *new_loop(void) {
312         ir_loop *father = current_loop;
313         ir_loop *son    = alloc_loop(father, outermost_ir_graph->obst);
314
315         if (son->depth > max_loop_depth) max_loop_depth = son->depth;
316         current_loop = son;
317         return father;
318 }
319
320 /**********************************************************************/
321 /* Constructing and destructing the loop/backedge information.       **/
322 /**********************************************************************/
323
324 /* Initialization steps. **********************************************/
325
326 static INLINE void init_node(ir_node *n, void *env) {
327         struct obstack *obst = env;
328         set_irn_link(n, new_scc_info(obst));
329         clear_backedges(n);
330 }
331
332 static INLINE void init_scc_common(void) {
333         current_dfn = 1;
334         loop_node_cnt = 0;
335         init_stack();
336 }
337
338 static INLINE void init_scc(ir_graph *irg, struct obstack *obst) {
339         init_scc_common();
340         irg_walk_graph(irg, init_node, NULL, obst);
341         /*
342         irg_walk (irg, link_to_reg_end, NULL, NULL);
343         */
344 }
345
346 static INLINE void finish_scc(void)
347 {
348         finish_stack();
349 }
350
351 #ifdef INTERPROCEDURAL_VIEW
352 static INLINE void init_ip_scc(struct obstack *obst) {
353         init_scc_common();
354         cg_walk(init_node, NULL, obst);
355
356 #if EXPERIMENTAL_LOOP_TREE
357         cg_walk(link_to_reg_end, NULL, NULL);
358 #endif
359 }
360 #endif
361
362 /**
363  * Check weather a given node represents the outer most Start
364  * block. In intra-procedural view this is the start block of the
365  * current graph, in interprocedural view it is the start block
366  * of the outer most graph.
367  *
368  * @param n  the node to check
369  *
370  * This is the condition for breaking the scc recursion.
371  */
372 static int is_outermost_Start(ir_node *n) {
373         /* Test whether this is the outermost Start node. */
374         if (is_Block(n) && get_Block_n_cfgpreds(n) == 1) {
375                 ir_node *pred = skip_Proj(get_Block_cfgpred(n, 0));
376             if (is_Start(pred) && get_nodes_block(pred) == n)
377                         return 1;
378         }
379         return 0;
380 }
381
382 /* When to walk from nodes to blocks. Only for Control flow operations? */
383 static INLINE int get_start_index(ir_node *n) {
384 #undef BLOCK_BEFORE_NODE
385 #define BLOCK_BEFORE_NODE 1
386
387 #if BLOCK_BEFORE_NODE
388
389         /* This version assures, that all nodes are ordered absolutely.  This allows
390            to undef all nodes in the heap analysis if the block is false, which means
391            not reachable.
392            I.e., with this code, the order on the loop tree is correct. But a (single)
393            test showed the loop tree is deeper.   */
394         if (get_irn_op(n) == op_Phi                      ||
395             is_Block(n)                                  ||
396             (is_Filter(n) && get_interprocedural_view()) || (
397               get_irg_pinned(get_irn_irg(n)) == op_pin_state_floats &&
398               get_irn_pinned(n)              == op_pin_state_floats
399             ))
400                 // Here we could test for backedge at -1 which is illegal
401                 return 0;
402         else
403                 return -1;
404
405 #else
406
407         /* This version causes deeper loop trees (at least we verified this
408            for Polymor).
409            But it guarantees that Blocks are analysed before nodes contained in the
410            block.  If so, we can set the value to undef if the block is not \
411            executed. */
412         if (is_cfop(n) || is_fragile_op(n) || is_Start(n))
413                 return -1;
414         else
415                 return 0;
416
417 #endif
418 }
419
420 /**
421  * Return non-zero if the given node is a legal loop header:
422  * Block, Phi, Filter.
423  *
424  * @param n  the node to check
425  */
426 static INLINE int is_possible_loop_head(ir_node *n) {
427         ir_op *op = get_irn_op(n);
428         return ((op == op_Block) ||
429                 (op == op_Phi) ||
430                 ((op == op_Filter) && get_interprocedural_view()));
431 }
432
433 /**
434  * Returns non-zero if n is a loop header, i.e., it is a Block, Phi
435  * or Filter node and has predecessors within the loop and out
436  * of the loop.
437  *
438  * @param n    the node to check
439  * @param root only needed for assertion.
440  */
441 static int is_head(ir_node *n, ir_node *root) {
442         int i, arity;
443         int some_outof_loop = 0, some_in_loop = 0;
444
445         /* Test for legal loop header: Block, Phi, ... */
446         if (!is_possible_loop_head(n))
447                 return 0;
448
449         if (!is_outermost_Start(n)) {
450 #ifndef NDEBUG
451                 int uplink = get_irn_uplink(root);
452 #else
453                 (void) root;
454 #endif
455                 arity = get_irn_arity(n);
456                 for (i = get_start_index(n); i < arity; i++) {
457                         ir_node *pred;
458                         if (is_backedge(n, i))
459                                 continue;
460                         pred = get_irn_n(n, i);
461                         if (! irn_is_in_stack(pred)) {
462                                 some_outof_loop = 1;
463                         } else {
464                                 assert(get_irn_uplink(pred) >= uplink);
465                                 some_in_loop = 1;
466                         }
467                 }
468         }
469         return some_outof_loop & some_in_loop;
470 }
471
472 /**
473  * Returns non-zero if n is possible loop head of an endless loop.
474  * I.e., it is a Block, Phi or Filter node and has only predecessors
475  * within the loop.
476  *
477  * @param n    the node to check
478  * @param root only needed for assertion.
479  */
480 static int is_endless_head(ir_node *n, ir_node *root) {
481         int i, arity;
482         int none_outof_loop = 1, some_in_loop = 0;
483
484         /* Test for legal loop header: Block, Phi, ... */
485         if (!is_possible_loop_head(n))
486                 return 0;
487
488         if (!is_outermost_Start(n)) {
489 #ifndef NDEBUG
490                 int uplink = get_irn_uplink(root);
491 #else
492                 (void) root;
493 #endif
494                 arity = get_irn_arity(n);
495                 for (i = get_start_index(n); i < arity; i++) {
496                         ir_node *pred;
497                         if (is_backedge(n, i))
498                                 continue;
499                         pred = get_irn_n(n, i);
500                         if (!irn_is_in_stack(pred)) {
501                                 none_outof_loop = 0;
502                         } else {
503                                 assert(get_irn_uplink(pred) >= uplink);
504                                 some_in_loop = 1;
505                         }
506                 }
507         }
508         return none_outof_loop & some_in_loop;
509 }
510
511 /** Returns index of the predecessor with the smallest dfn number
512     greater-equal than limit. */
513 static int smallest_dfn_pred(ir_node *n, int limit) {
514         int i, index = -2, min = -1;
515
516         if (!is_outermost_Start(n)) {
517                 int arity = get_irn_arity(n);
518                 for (i = get_start_index(n); i < arity; i++) {
519                         ir_node *pred = get_irn_n(n, i);
520                         if (is_backedge(n, i) || !irn_is_in_stack(pred))
521                                 continue;
522                         if (get_irn_dfn(pred) >= limit && (min == -1 || get_irn_dfn(pred) < min)) {
523                                 index = i;
524                                 min = get_irn_dfn(pred);
525                         }
526                 }
527         }
528         return index;
529 }
530
531 /**
532  * Returns index of the predecessor with the largest dfn number.
533  */
534 static int largest_dfn_pred(ir_node *n) {
535         int i, index = -2, max = -1;
536
537         if (!is_outermost_Start(n)) {
538                 int arity = get_irn_arity(n);
539                 for (i = get_start_index(n); i < arity; i++) {
540                         ir_node *pred = get_irn_n(n, i);
541                         if (is_backedge (n, i) || !irn_is_in_stack(pred))
542                                 continue;
543                         if (get_irn_dfn(pred) > max) {
544                                 index = i;
545                                 max = get_irn_dfn(pred);
546                         }
547                 }
548         }
549         return index;
550 }
551
552 /**
553  * Searches the stack for possible loop heads.  Tests these for backedges.
554  * If it finds a head with an unmarked backedge it marks this edge and
555  * returns the tail of the loop.
556  * If it finds no backedge returns NULL.
557  * ("disable_backedge" in fiasco)
558  *
559  * @param n  A node where uplink == dfn.
560  */
561 static ir_node *find_tail(ir_node *n) {
562         ir_node *m;
563         int i, res_index = -2;
564
565         /*
566         if (!icfg && rm_cyclic_phis && remove_cyclic_phis (n)) return NULL;
567          */
568         m = stack[tos-1];  /* tos = top of stack */
569         if (is_head(m, n)) {
570                 res_index = smallest_dfn_pred(m, 0);
571                 if ((res_index == -2) &&  /* no smallest dfn pred found. */
572                         (n ==  m))
573                         return NULL;
574         } else {
575                 if (m == n) return NULL;    // Is this to catch Phi - self loops?
576                 for (i = tos-2; i >= 0; --i) {
577                         m = stack[i];
578
579                         if (is_head(m, n)) {
580                                 res_index = smallest_dfn_pred(m, get_irn_dfn(m) + 1);
581                                 if (res_index == -2)  /* no smallest dfn pred found. */
582                                         res_index = largest_dfn_pred(m);
583
584                                 if ((m == n) && (res_index == -2)) {  /* don't walk past loop head. */
585                                         i = -1;
586                                 }
587                                 break;
588                         }
589
590                         /* We should not walk past our selves on the stack:  The upcoming nodes
591                            are not in this loop. We assume a loop not reachable from Start. */
592                         if (m == n) {
593                                 i = -1;
594                                 break;
595                         }
596                 }
597
598                 if (i < 0) {
599                         /* A dead loop not reachable from Start. */
600                         for (i = tos-2; i >= 0; --i) {
601                                 m = stack[i];
602                                 if (is_endless_head(m, n)) {
603                                         res_index = smallest_dfn_pred(m, get_irn_dfn(m) + 1);
604                                         if (res_index == -2)  /* no smallest dfn pred found. */
605                                                 res_index = largest_dfn_pred (m);
606                                         break;
607                                 }
608                                 if (m == n) { break; }  /* It's not an unreachable loop, either. */
609                         }
610                         //assert(0 && "no head found on stack");
611                 }
612
613         }
614         if (res_index <= -2) {
615                 /* It's a completely bad loop: without Phi/Block nodes that can
616                    be a head. I.e., the code is "dying".  We break the loop by
617                    setting Bad nodes. */
618                 int arity = get_irn_arity(n);
619                 ir_node *bad = get_irg_bad(get_irn_irg(n));
620                 for (i = -1; i < arity; ++i) {
621                         set_irn_n(n, i, bad);
622                 }
623                 return NULL;
624         }
625         assert(res_index > -2);
626
627         set_backedge(m, res_index);
628         return is_outermost_Start(n) ? NULL : get_irn_n(m, res_index);
629 }
630
631
632 #if EXPERIMENTAL_LOOP_TREE
633
634 /*  ----------------------------------------------------------------
635     AS:  This is experimental code to build loop trees suitable for
636     the heap analysis. Does not work correctly right now... :-(
637
638
639     Search in stack for the corresponding first Call-End-ProjX that
640     corresponds to one of the control flow predecessors of the given
641     block, that is the possible callers.
642     returns: the control predecessor to chose\
643     or       -1 if no corresponding Call-End-Node could be found
644              on the stack.
645     - -------------------------------------------------------------- */
646
647 int search_endproj_in_stack(ir_node *start_block) {
648         int i, j;
649         assert(is_Block(start_block));
650         for(i = tos - 1; i >= 0; --i)
651         {
652                 if(get_irn_op(stack[i]) == op_Proj && get_irn_mode(stack[i]) == mode_X &&
653                         get_irn_op(get_irn_n(stack[i], 0)) == op_EndReg)
654                 {
655                         printf("FOUND PROJ!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
656                         ir_node *end_projx = stack[i];
657
658                         int arity = get_irn_arity(start_block);
659                         for(j = 0; j < arity; j++)
660                         {
661                                 ir_node *begin_projx = get_Block_cfgpred(get_irg_start_block(get_irn_irg(end_projx)),
662                                         get_Proj_proj(end_projx));
663                                 if(get_irn_n(start_block, j) == begin_projx)
664                                 {
665                                         printf("FOUND IT!!!!!!!!!!!!!!!!!!\n");
666                                         return(j);
667                                 }
668                         }
669                 }
670         }
671         return(-1);
672 }
673
674
675 static pmap *projx_link = NULL;
676
677 void link_to_reg_end (ir_node *n, void *env) {
678         if(get_irn_op(n) == op_Proj &&
679                 get_irn_mode(n) == mode_X &&
680                 get_irn_op(get_irn_n(n, 0)) == op_EndReg) {
681                         /* Reg End Projx -> Find the CallBegin Projx and hash it */
682                         ir_node *end_projx = n;
683                         ir_node *begin_projx = get_Block_cfgpred(get_irg_start_block(get_irn_irg(end_projx)),
684                                 get_Proj_proj(end_projx));
685                         set_projx_link(begin_projx, end_projx);
686         }
687 }
688
689 void set_projx_link(ir_node *cb_projx, ir_node *end_projx) {
690         if(projx_link == NULL)
691                 projx_link = pmap_create();
692         pmap_insert(projx_link, (void *)cb_projx, (void *)end_projx);
693 }
694
695 ir_node *get_projx_link(ir_node *cb_projx) {
696         return((ir_node *) pmap_get(projx_link, (void *)cb_projx));
697 }
698
699 #endif
700
701 static INLINE int is_outermost_loop(ir_loop *l) {
702         return l == get_loop_outer_loop(l);
703 }
704
705
706 /*-----------------------------------------------------------*
707  *                   The core algorithm.                     *
708  *-----------------------------------------------------------*/
709
710 /**
711  * The core algorithm: Find strongly coupled components.
712  *
713  * @param n  node to start
714  */
715 static void scc(ir_node *n) {
716         if (irn_visited_else_mark(n))
717                 return;
718
719         /* Initialize the node */
720         set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
721         set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
722         set_irn_loop(n, NULL);
723         ++current_dfn;
724         push(n);
725
726         /* AS: get_start_index might return -1 for Control Flow Nodes, and thus a negative
727            array index would be passed to is_backedge(). But CFG Nodes dont't have a backedge array,
728            so is_backedge does not access array[-1] but correctly returns false! */
729
730         if (!is_outermost_Start(n)) {
731                 int i, arity = get_irn_arity(n);
732
733                 for (i = get_start_index(n); i < arity; ++i) {
734                         ir_node *m;
735                         if (is_backedge(n, i))
736                                 continue;
737                         m = get_irn_n(n, i);
738                         scc(m);
739                         if (irn_is_in_stack(m)) {
740                                 /* Uplink of m is smaller if n->m is a backedge.
741                                    Propagate the uplink to mark the loop. */
742                                 if (get_irn_uplink(m) < get_irn_uplink(n))
743                                         set_irn_uplink(n, get_irn_uplink(m));
744                         }
745                 }
746         }
747
748         if (get_irn_dfn(n) == get_irn_uplink(n)) {
749                 /* This condition holds for
750                    1) the node with the incoming backedge.
751                       That is: We found a loop!
752                    2) Straight line code, because no uplink has been propagated, so the
753                       uplink still is the same as the dfn.
754
755                    But n might not be a proper loop head for the analysis. Proper loop
756                    heads are Block and Phi nodes. find_tail() searches the stack for
757                    Block's and Phi's and takes those nodes as loop heads for the current
758                    loop instead and marks the incoming edge as backedge. */
759
760                 ir_node *tail = find_tail(n);
761                 if (tail != NULL) {
762                         /* We have a loop, that is no straight line code,
763                            because we found a loop head!
764                            Next actions: Open a new loop on the loop tree and
765                                          try to find inner loops */
766
767 #if NO_LOOPS_WITHOUT_HEAD
768                         /* This is an adaption of the algorithm from fiasco / optscc to
769                          * avoid loops without Block or Phi as first node.  This should
770                          * severely reduce the number of evaluations of nodes to detect
771                          * a fixpoint in the heap analysis.
772                          * Further it avoids loops without firm nodes that cause errors
773                          * in the heap analyses.
774                          * But attention:  don't do it for the outermost loop:  This loop
775                          * is not iterated.  A first block can be a loop head in case of
776                          * an endless recursion. */
777
778                         ir_loop *l;
779                         int close;
780                         if ((get_loop_n_elements(current_loop) > 0) || (is_outermost_loop(current_loop))) {
781                                 l = new_loop();
782                                 close = 1;
783                         } else {
784                                 l = current_loop;
785                                 close = 0;
786                         }
787 #else
788                         ir_loop *l = new_loop();
789 #endif
790
791                         /* Remove the loop from the stack ... */
792                         pop_scc_unmark_visit(n);
793
794                         /* The current backedge has been marked, that is temporarily eliminated,
795                            by find tail. Start the scc algorithm
796                            again on the subgraph that is left (the current loop without the backedge)
797                            in order to find more inner loops. */
798                         scc(tail);
799
800                         assert(irn_visited(n));
801 #if NO_LOOPS_WITHOUT_HEAD
802                         if (close)
803 #endif
804                                 close_loop(l);
805                 } else {
806                         /* No loop head was found, that is we have straight line code.
807                            Pop all nodes from the stack to the current loop. */
808                         pop_scc_to_loop(n);
809                 }
810         }
811 }
812
813 #ifdef INTERPROCEDURAL_VIEW
814 static void my_scc(ir_node *n) {
815         int i;
816         if (irn_visited_else_mark(n))
817                 return;
818
819         /* Initialize the node */
820         set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
821         set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
822         set_irn_loop(n, NULL);
823         current_dfn ++;
824         push(n);
825
826         /* AS: get_start_index might return -1 for Control Flow Nodes, and thus a negative
827            array index would be passed to is_backedge(). But CFG Nodes dont't have a backedge array,
828            so is_backedge does not access array[-1] but correctly returns false! */
829
830         if (!is_outermost_Start(n)) {
831                 int arity = get_irn_arity(n);
832
833                 for (i = get_start_index(n); i < arity; i++) {
834                         ir_node *m;
835                         if (is_backedge(n, i)) continue;
836                         m = get_irn_n(n, i); /* get_irn_ip_pred(n, i); */
837                         /* if (!m || is_Unknown(m)) continue; */
838                         my_scc(m);
839                         if (irn_is_in_stack(m)) {
840                                 /* Uplink of m is smaller if n->m is a backedge.
841                                    Propagate the uplink to mark the loop. */
842                                 if (get_irn_uplink(m) < get_irn_uplink(n))
843                                         set_irn_uplink(n, get_irn_uplink(m));
844                         }
845                 }
846         }
847
848         if (get_irn_dfn(n) == get_irn_uplink(n)) {
849                 /* This condition holds for
850                    1) the node with the incoming backedge.
851                       That is: We found a loop!
852                    2) Straight line code, because no uplink has been propagated, so the
853                       uplink still is the same as the dfn.
854
855                    But n might not be a proper loop head for the analysis. Proper loop
856                    heads are Block and Phi nodes. find_tail searches the stack for
857                    Block's and Phi's and takes those nodes as loop heads for the current
858                    loop instead and marks the incoming edge as backedge. */
859
860                 ir_node *tail = find_tail(n);
861                 if (tail) {
862                         /* We have a loop, that is no straight line code,
863                            because we found a loop head!
864                            Next actions: Open a new loop on the loop tree and
865                                          try to find inner loops */
866
867 #if NO_LOOPS_WITHOUT_HEAD
868                         /* This is an adaption of the algorithm from fiasco / optscc to
869                          * avoid loops without Block or Phi as first node.  This should
870                          * severely reduce the number of evaluations of nodes to detect
871                          * a fixpoint in the heap analysis.
872                          * Further it avoids loops without firm nodes that cause errors
873                          * in the heap analyses. */
874
875                         ir_loop *l;
876                         int close;
877                         if ((get_loop_n_elements(current_loop) > 0) || (is_outermost_loop(current_loop))) {
878                                 l = new_loop();
879                                 close = 1;
880                         } else {
881                                 l = current_loop;
882                                 close = 0;
883                         }
884 #else
885                         ir_loop *l = new_loop();
886 #endif
887
888                         /* Remove the loop from the stack ... */
889                         pop_scc_unmark_visit(n);
890
891                         /* The current backedge has been marked, that is temporarily eliminated,
892                            by find tail. Start the scc algorithm
893                            anew on the subgraph that is left (the current loop without the backedge)
894                            in order to find more inner loops. */
895                         my_scc(tail);
896
897                         assert(irn_visited(n));
898 #if NO_LOOPS_WITHOUT_HEAD
899                         if (close)
900 #endif
901                                 close_loop(l);
902                 } else {
903                         /* No loop head was found, that is we have straightline code.
904                            Pop all nodes from the stack to the current loop. */
905                         pop_scc_to_loop(n);
906                 }
907         }
908 }
909 #endif /* INTERPROCEDURAL_VIEW */
910
911 /* Constructs backedge information for irg. In interprocedural view constructs
912    backedges for all methods called by irg, too. */
913 int construct_backedges(ir_graph *irg) {
914         ir_graph *rem = current_ir_graph;
915         ir_loop *head_rem;
916         struct obstack temp;
917
918         assert(!get_interprocedural_view() &&
919                "not implemented, use construct_ip_backedges()");
920
921         max_loop_depth = 0;
922         current_ir_graph   = irg;
923         outermost_ir_graph = irg;
924
925         obstack_init(&temp);
926         init_scc(irg, &temp);
927
928         current_loop = NULL;
929         new_loop();  /* sets current_loop */
930         head_rem = current_loop; /* Just for assertion */
931
932         inc_irg_visited(irg);
933
934         scc(get_irg_end(irg));
935
936         finish_scc();
937         obstack_free(&temp, NULL);
938
939         assert(head_rem == current_loop);
940         mature_loops(current_loop, irg->obst);
941         set_irg_loop(irg, current_loop);
942         set_irg_loopinfo_state(irg, loopinfo_consistent);
943         assert(get_irg_loop(irg)->kind == k_ir_loop);
944         current_ir_graph = rem;
945         return max_loop_depth;
946 }
947
948
949 #ifdef INTERPROCEDURAL_VIEW
950 int construct_ip_backedges(void) {
951         ir_graph *rem = current_ir_graph;
952         int rem_ipv = get_interprocedural_view();
953         int i;
954         strcut obstack temp;
955
956         max_loop_depth = 0;
957         assert(get_irp_ip_view_state() == ip_view_valid);
958
959         outermost_ir_graph = get_irp_main_irg();
960
961         obstack_init(&temp);
962         init_ip_scc(&temp);
963
964         current_loop = NULL;
965         new_loop();  /* sets current_loop */
966         set_interprocedural_view(1);
967
968         inc_max_irg_visited();
969         for (i = 0; i < get_irp_n_irgs(); i++)
970                 set_irg_visited(get_irp_irg(i), get_max_irg_visited());
971
972         /** We have to start the walk at the same nodes as cg_walk. **/
973         /* Walk starting at unreachable procedures. Only these
974          * have End blocks visible in interprocedural view. */
975         for (i = 0; i < get_irp_n_irgs(); i++) {
976                 ir_node *sb;
977                 current_ir_graph = get_irp_irg(i);
978
979                 sb = get_irg_start_block(current_ir_graph);
980
981                 if ((get_Block_n_cfgpreds(sb) > 1) ||
982                     (get_nodes_block(get_Block_cfgpred(sb, 0)) != sb))
983                         continue;
984
985                 scc(get_irg_end(current_ir_graph));
986         }
987
988         /* Check whether we walked all procedures: there could be procedures
989            with cyclic calls but no call from the outside. */
990         for (i = 0; i < get_irp_n_irgs(); i++) {
991                 ir_node *sb;
992                 current_ir_graph = get_irp_irg(i);
993
994                 /* Test start block: if inner procedure end and end block are not
995                  * visible and therefore not marked. */
996                 sb = get_irg_start_block(current_ir_graph);
997                 if (get_irn_visited(sb) < get_irg_visited(current_ir_graph)) scc(sb);
998         }
999
1000         /* Walk all endless loops in inner procedures.
1001          * We recognize an inner procedure if the End node is not visited. */
1002         for (i = 0; i < get_irp_n_irgs(); i++) {
1003                 ir_node *e;
1004                 current_ir_graph = get_irp_irg(i);
1005
1006                 e = get_irg_end(current_ir_graph);
1007                 if (get_irn_visited(e) < get_irg_visited(current_ir_graph)) {
1008                         int j;
1009                         /* Don't visit the End node. */
1010                         for (j = 0; j < get_End_n_keepalives(e); j++)
1011                                 scc(get_End_keepalive(e, j));
1012                 }
1013         }
1014
1015         set_irg_loop(outermost_ir_graph, current_loop);
1016         set_irg_loopinfo_state(current_ir_graph, loopinfo_ip_consistent);
1017         assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
1018
1019         obstack_free(&temp, NULL);
1020         current_ir_graph = rem;
1021         set_interprocedural_view(rem_ipv);
1022         return max_loop_depth;
1023 }
1024
1025 void my_construct_ip_backedges(void) {
1026         ir_graph *rem = current_ir_graph;
1027         int rem_ipv = get_interprocedural_view();
1028         int i;
1029
1030         assert(get_irp_ip_view_state() == ip_view_valid);
1031
1032         outermost_ir_graph = get_irp_main_irg();
1033
1034         init_ip_scc();
1035
1036         current_loop = NULL;
1037         new_loop();  /* sets current_loop */
1038         set_interprocedural_view(1);
1039
1040         inc_max_irg_visited();
1041         for (i = 0; i < get_irp_n_irgs(); i++)
1042                 set_irg_visited(get_irp_irg(i), get_max_irg_visited());
1043
1044         /** We have to start the walk at the same nodes as cg_walk. **/
1045         /* Walk starting at unreachable procedures. Only these
1046          * have End blocks visible in interprocedural view. */
1047         for (i = 0; i < get_irp_n_irgs(); i++) {
1048                 ir_node *sb;
1049                 current_ir_graph = get_irp_irg(i);
1050
1051                 sb = get_irg_start_block(current_ir_graph);
1052
1053                 if ((get_Block_n_cfgpreds(sb) > 1) ||
1054                     (get_nodes_block(get_Block_cfgpred(sb, 0)) != sb)) continue;
1055
1056                 my_scc(get_irg_end(current_ir_graph));
1057         }
1058
1059         /* Check whether we walked all procedures: there could be procedures
1060            with cyclic calls but no call from the outside. */
1061         for (i = 0; i < get_irp_n_irgs(); i++) {
1062                 ir_node *sb;
1063                 current_ir_graph = get_irp_irg(i);
1064
1065                 /* Test start block: if inner procedure end and end block are not
1066                  * visible and therefore not marked. */
1067                 sb = get_irg_start_block(current_ir_graph);
1068                 if (get_irn_visited(sb) < get_irg_visited(current_ir_graph))
1069                         scc(sb);
1070         }
1071
1072         /* Walk all endless loops in inner procedures.
1073          * We recognize an inner procedure if the End node is not visited. */
1074         for (i = 0; i < get_irp_n_irgs(); i++) {
1075                 ir_node *e;
1076                 current_ir_graph = get_irp_irg(i);
1077
1078                 e = get_irg_end(current_ir_graph);
1079                 if (get_irn_visited(e) < get_irg_visited(current_ir_graph)) {
1080                         int j;
1081                         /* Don't visit the End node. */
1082                         for (j = 0; j < get_End_n_keepalives(e); j++) scc(get_End_keepalive(e, j));
1083                 }
1084         }
1085
1086         set_irg_loop(outermost_ir_graph, current_loop);
1087         set_irg_loopinfo_state(current_ir_graph, loopinfo_ip_consistent);
1088         assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
1089
1090         current_ir_graph = rem;
1091         set_interprocedural_view(rem_ipv);
1092 }
1093 #endif
1094
1095 static void reset_backedges(ir_node *n) {
1096         if (is_possible_loop_head(n)) {
1097 #ifdef INTERPROCEDURAL_VIEW
1098                 int rem = get_interprocedural_view();
1099
1100                 set_interprocedural_view(1);
1101                 clear_backedges(n);
1102                 set_interprocedural_view(1);
1103                 clear_backedges(n);
1104                 set_interprocedural_view(rem);
1105 #else
1106                 clear_backedges(n);
1107 #endif
1108         }
1109 }
1110
1111
1112 /*
1113 static void loop_reset_backedges(ir_loop *l) {
1114         int i;
1115         reset_backedges(get_loop_node(l, 0));
1116         for (i = 0; i < get_loop_n_nodes(l); ++i)
1117                 set_irn_loop(get_loop_node(l, i), NULL);
1118         for (i = 0; i < get_loop_n_sons(l); ++i) {
1119                 loop_reset_backedges(get_loop_son(l, i));
1120         }
1121 }
1122 */
1123
1124 static void loop_reset_node(ir_node *n, void *env) {
1125         (void) env;
1126         set_irn_loop(n, NULL);
1127         reset_backedges(n);
1128 }
1129
1130
1131 /** Removes all loop information.
1132     Resets all backedges */
1133 void free_loop_information(ir_graph *irg) {
1134         /* We can not use this recursion, as the loop might contain
1135            illegal nodes by now.  Why else would we throw away the
1136            representation?
1137         if (get_irg_loop(irg)) loop_reset_backedges(get_irg_loop(irg));
1138         */
1139         irg_walk_graph(irg, loop_reset_node, NULL, NULL);
1140         set_irg_loop(irg, NULL);
1141         set_irg_loopinfo_state(current_ir_graph, loopinfo_none);
1142         /* We cannot free the loop nodes, they are on the obstack. */
1143 }
1144
1145
1146 void free_all_loop_information(void) {
1147         int i;
1148 #ifdef INTERPROCEDURAL_VIEW
1149         int rem = get_interprocedural_view();
1150         set_interprocedural_view(1);  /* To visit all filter nodes */
1151 #endif
1152         for (i = 0; i < get_irp_n_irgs(); i++) {
1153                 free_loop_information(get_irp_irg(i));
1154         }
1155 #ifdef INTERPROCEDURAL_VIEW
1156         set_interprocedural_view(rem);
1157 #endif
1158 }
1159
1160
1161
1162
1163
1164 /* Debug stuff *************************************************/
1165
1166 static int test_loop_node(ir_loop *l) {
1167         int i, has_node = 0, found_problem = 0;
1168         loop_element le;
1169
1170         assert(l && l->kind == k_ir_loop);
1171
1172         if (get_loop_n_elements(l) == 0) {
1173                 found_problem = 1;
1174                 dump_loop(l, "-ha");
1175         }
1176
1177         le = get_loop_element(l, 0);
1178         if (*(le.kind) != k_ir_node) {
1179                 assert(le.kind && *(le.kind) == k_ir_loop);
1180
1181                 found_problem = 1;
1182                 dump_loop(l, "-ha");
1183         }
1184
1185         if ((*(le.kind) == k_ir_node) && !is_possible_loop_head(le.node)) {
1186                 found_problem = 1;
1187                 dump_loop(l, "-ha");
1188         }
1189
1190         if ((get_loop_depth(l) != 0) &&
1191                 (*(le.kind) == k_ir_node) && !has_backedges(le.node)) {
1192                         found_problem = 1;
1193                         dump_loop(l, "-ha");
1194         }
1195
1196         /* Recur */
1197         has_node = 0;
1198         for (i = 0; i < get_loop_n_elements(l); ++i) {
1199                 le = get_loop_element(l, i);
1200                 if (*(le.kind) == k_ir_node)
1201                         has_node++;
1202                 else
1203                         if (test_loop_node(le.son)) found_problem = 1;
1204         }
1205
1206         if (has_node == 0) {
1207                 found_problem = 1;
1208                 dump_loop(l, "-ha");
1209         }
1210
1211         return found_problem;
1212 }
1213
1214 /** Prints all loop nodes that
1215  *  - do not have any firm nodes, only loop sons
1216  *  - the header is not a Phi, Block or Filter.
1217  */
1218 void find_strange_loop_nodes(ir_loop *l) {
1219         int found_problem = 0;
1220         found_problem = test_loop_node(l);
1221         printf("Finished Test\n\n");
1222         if (found_problem) exit(0);
1223
1224 }
1225
1226 /* ------------------------------------------------------------------- */
1227 /* Simple analyses based on the loop information                       */
1228 /* ------------------------------------------------------------------- */
1229
1230 int is_loop_variant(ir_loop *l, ir_loop *b) {
1231         int i, n_elems;
1232
1233         if (l == b) return 1;
1234
1235         n_elems = get_loop_n_elements(l);
1236         for (i = 0; i < n_elems; ++i) {
1237                 loop_element e = get_loop_element(l, i);
1238                 if (is_ir_loop(e.kind))
1239                         if (is_loop_variant(e.son, b))
1240                                 return 1;
1241         }
1242
1243         return 0;
1244 }
1245
1246 /* Test whether a value is loop invariant.
1247  *
1248  * @param n      The node to be tested.
1249  * @param block  A block node.  We pass the block, not the loop as we must
1250  *               start off with a block loop to find all proper uses.
1251  *
1252  * Returns non-zero, if the node n is not changed in the loop block
1253  * belongs to or in inner loops of this blocks loop. */
1254 int is_loop_invariant(const ir_node *n, const ir_node *block) {
1255         ir_loop *l = get_irn_loop(block);
1256         const ir_node *b = is_Block(n) ? n : get_nodes_block(n);
1257         return !is_loop_variant(l, get_irn_loop(b));
1258 }