becopyilp: Inline struct size_red_t into struct ilp_env_t.
[libfirm] / ir / ana / irscc.c
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5
6 /**
7  * @file
8  * @brief    Compute the strongly connected regions and build
9  *              backedge/loop datastructures.
10  *              A variation on the Tarjan algorithm. See also [Trapp:99],
11  *              Chapter 5.2.1.2.
12  * @author   Goetz Lindenmaier
13  * @date     7.2002
14  */
15 #include "config.h"
16
17 #include <string.h>
18 #include <stdlib.h>
19
20 #include "irloop_t.h"
21
22 #include "irprog_t.h"
23 #include "irgraph_t.h"
24 #include "irnode_t.h"
25 #include "irgwalk.h"
26 #include "irdump.h"
27 #include "array.h"
28 #include "pmap.h"
29 #include "ircons.h"
30
31 /** The outermost graph the scc is computed for. */
32 static ir_graph *outermost_ir_graph;
33 /** Current loop construction is working on. */
34 static ir_loop *current_loop;
35 /** Counts the number of allocated loop nodes.
36  *  Each loop node gets a unique number.
37  *  @todo What for? ev. remove.
38  */
39 static int loop_node_cnt = 0;
40 /** Counter to generate depth first numbering of visited nodes. */
41 static int current_dfn = 1;
42
43 /**********************************************************************/
44 /* Node attributes needed for the construction.                      **/
45 /**********************************************************************/
46
47 typedef struct scc_info {
48         int in_stack;          /**< Marks whether node is on the stack. */
49         int dfn;               /**< Depth first search number. */
50         int uplink;            /**< dfn number of ancestor. */
51 } scc_info;
52
53 /**
54  * Allocates a new SCC info on the given obstack.
55  */
56 static inline scc_info *new_scc_info(struct obstack *obst)
57 {
58         return OALLOCZ(obst, scc_info);
59 }
60
61 /**
62  * Mark node n being on the SCC stack.
63  */
64 static inline void mark_irn_in_stack(ir_node *n)
65 {
66         scc_info *scc = (scc_info*) get_irn_link(n);
67         assert(scc);
68         scc->in_stack = 1;
69 }
70
71 /**
72 * Mark node n NOT being on the SCC stack.
73 */
74 static inline void mark_irn_not_in_stack(ir_node *n)
75 {
76         scc_info *scc = (scc_info*) get_irn_link(n);
77         assert(scc);
78         scc->in_stack = 0;
79 }
80
81 /**
82  * Checks if a node is on the SCC stack.
83  */
84 static inline int irn_is_in_stack(ir_node *n)
85 {
86         scc_info *scc = (scc_info*) get_irn_link(n);
87         assert(scc);
88         return scc->in_stack;
89 }
90
91 /**
92  * Sets the uplink number for a node.
93  */
94 static inline void set_irn_uplink(ir_node *n, int uplink)
95 {
96         scc_info *scc = (scc_info*) get_irn_link(n);
97         assert(scc);
98         scc->uplink = uplink;
99 }
100
101 /**
102  * Returns the uplink number for a node.
103  */
104 static int get_irn_uplink(ir_node *n)
105 {
106         scc_info *scc = (scc_info*) get_irn_link(n);
107         assert(scc);
108         return scc->uplink;
109 }
110
111 /**
112  * Sets the depth-first-search number for a node.
113  */
114 static inline void set_irn_dfn(ir_node *n, int dfn)
115 {
116         scc_info *scc = (scc_info*) get_irn_link(n);
117         assert(scc);
118         scc->dfn = dfn;
119 }
120
121 /**
122  * Returns the depth-first-search number of a node.
123  */
124 static int get_irn_dfn(ir_node *n)
125 {
126         scc_info *scc = (scc_info*) get_irn_link(n);
127         assert(scc);
128         return scc->dfn;
129 }
130
131 /**********************************************************************/
132 /* A stack.                                                          **/
133 /**********************************************************************/
134
135 static ir_node **stack = NULL;
136 static size_t tos = 0;                /* top of stack */
137
138 /**
139  * initializes the stack
140  */
141 static inline void init_stack(void)
142 {
143         if (stack) {
144                 ARR_RESIZE(ir_node *, stack, 1000);
145         } else {
146                 stack = NEW_ARR_F(ir_node *, 1000);
147         }
148         tos = 0;
149 }
150
151 /**
152  * Frees the stack.
153  */
154 static void finish_stack(void)
155 {
156         DEL_ARR_F(stack);
157         stack = NULL;
158 }
159
160 /**
161  * push a node onto the stack
162  *
163  * @param n  The node to push
164  */
165 static inline void push(ir_node *n)
166 {
167         if (tos == ARR_LEN(stack)) {
168                 size_t nlen = ARR_LEN(stack) * 2;
169                 ARR_RESIZE(ir_node *, stack, nlen);
170         }
171         stack[tos++] = n;
172         mark_irn_in_stack(n);
173 }
174
175 /**
176  * pop a node from the stack
177  *
178  * @return  The topmost node
179  */
180 static inline ir_node *pop(void)
181 {
182         ir_node *n;
183
184         assert(tos > 0);
185         n = stack[--tos];
186         mark_irn_not_in_stack(n);
187         return n;
188 }
189
190 /**
191  * The nodes up to n belong to the current loop.
192  * Removes them from the stack and adds them to the current loop.
193  */
194 static inline void pop_scc_to_loop(ir_node *n)
195 {
196         ir_node *m;
197
198         do {
199                 m = pop();
200
201                 loop_node_cnt++;
202                 set_irn_dfn(m, loop_node_cnt);
203                 add_loop_node(current_loop, m);
204                 set_irn_loop(m, current_loop);
205         } while (m != n);
206 }
207
208 /* GL ??? my last son is my grandson???  Removes loops with no
209    ir_nodes in them.  Such loops have only another loop as son. (Why
210    can't they have two loops as sons? Does it never get that far? ) */
211 static void close_loop(ir_loop *l)
212 {
213         size_t last = get_loop_n_elements(l) - 1;
214         loop_element lelement = get_loop_element(l, last);
215         ir_loop *last_son = lelement.son;
216
217         if (get_kind(last_son) == k_ir_loop &&
218                 get_loop_n_elements(last_son) == 1) {
219                         ir_loop *gson;
220
221                         lelement = get_loop_element(last_son, 0);
222                         gson = lelement.son;
223
224                         if (get_kind(gson) == k_ir_loop) {
225                                 loop_element new_last_son;
226
227                                 gson->outer_loop = l;
228                                 new_last_son.son = gson;
229                                 l->children[last] = new_last_son;
230                         }
231         }
232
233         current_loop = l;
234 }
235
236 /* Removes and unmarks all nodes up to n from the stack.
237    The nodes must be visited once more to assign them to a scc. */
238 static inline void pop_scc_unmark_visit(ir_node *n)
239 {
240         ir_node *m = NULL;
241
242         while (m != n) {
243                 m = pop();
244                 set_irn_visited(m, 0);
245         }
246 }
247
248 /**********************************************************************/
249 /* The loop datastructure.                                           **/
250 /**********************************************************************/
251
252 /* Allocates a new loop as son of current_loop.  Sets current_loop
253    to the new loop and returns the father. */
254 static ir_loop *new_loop(void)
255 {
256         ir_loop *father = current_loop;
257         ir_loop *son    = alloc_loop(father, get_irg_obstack(outermost_ir_graph));
258
259         current_loop = son;
260         return father;
261 }
262
263 /**********************************************************************/
264 /* Constructing and destructing the loop/backedge information.       **/
265 /**********************************************************************/
266
267 /* Initialization steps. **********************************************/
268
269 static inline void init_node(ir_node *n, void *env)
270 {
271         struct obstack *obst = (struct obstack*) env;
272         set_irn_link(n, new_scc_info(obst));
273         clear_backedges(n);
274 }
275
276 static inline void init_scc_common(void)
277 {
278         current_dfn = 1;
279         loop_node_cnt = 0;
280         init_stack();
281 }
282
283 static inline void init_scc(ir_graph *irg, struct obstack *obst)
284 {
285         init_scc_common();
286         irg_walk_graph(irg, init_node, NULL, obst);
287 }
288
289 static inline void finish_scc(void)
290 {
291         finish_stack();
292 }
293
294 /**
295  * Check whether a given node represents the outermost Start
296  * block. In intra-procedural view this is the start block of the
297  * current graph, in interprocedural view it is the start block
298  * of the outer most graph.
299  *
300  * @param n  the node to check
301  *
302  * This is the condition for breaking the scc recursion.
303  */
304 static int is_outermost_Start(ir_node *n)
305 {
306         /* Test whether this is the outermost Start node. */
307         if (is_Block(n) && get_Block_n_cfgpreds(n) == 1) {
308                 ir_node *pred = skip_Proj(get_Block_cfgpred(n, 0));
309             if (is_Start(pred) && get_nodes_block(pred) == n)
310                         return 1;
311         }
312         return 0;
313 }
314
315 /* When to walk from nodes to blocks. Only for Control flow operations? */
316 static inline int get_start_index(ir_node *n)
317 {
318         /* This version assures, that all nodes are ordered absolutely.  This allows
319            to undef all nodes in the heap analysis if the block is false, which
320            means not reachable.
321            I.e., with this code, the order on the loop tree is correct. But a
322            (single) test showed the loop tree is deeper. */
323         if (is_Phi(n)   ||
324             is_Block(n) ||
325             (get_irg_pinned(get_irn_irg(n)) == op_pin_state_floats &&
326               get_irn_pinned(n)              == op_pin_state_floats))
327                 // Here we could test for backedge at -1 which is illegal
328                 return 0;
329         else
330                 return -1;
331 }
332
333 /**
334  * Return non-zero if the given node is a legal loop header:
335  * Block, Phi
336  *
337  * @param n  the node to check
338  */
339 static inline int is_possible_loop_head(ir_node *n)
340 {
341         return is_Block(n) || is_Phi(n);
342 }
343
344 /**
345  * Returns non-zero if n is a loop header, i.e., it is a Block or Phi
346  * node and has predecessors within the loop and out of the loop.
347  *
348  * @param n    the node to check
349  * @param root only needed for assertion.
350  */
351 static int is_head(ir_node *n, ir_node *root)
352 {
353         int i, arity;
354         int some_outof_loop = 0, some_in_loop = 0;
355
356         /* Test for legal loop header: Block, Phi, ... */
357         if (!is_possible_loop_head(n))
358                 return 0;
359
360         if (!is_outermost_Start(n)) {
361 #ifndef NDEBUG
362                 int uplink = get_irn_uplink(root);
363 #else
364                 (void) root;
365 #endif
366                 arity = get_irn_arity(n);
367                 for (i = get_start_index(n); i < arity; i++) {
368                         ir_node *pred;
369                         if (is_backedge(n, i))
370                                 continue;
371                         pred = get_irn_n(n, i);
372                         if (! irn_is_in_stack(pred)) {
373                                 some_outof_loop = 1;
374                         } else {
375                                 assert(get_irn_uplink(pred) >= uplink);
376                                 some_in_loop = 1;
377                         }
378                 }
379         }
380         return some_outof_loop & some_in_loop;
381 }
382
383 /**
384  * Returns non-zero if n is possible loop head of an endless loop.
385  * I.e., it is a Block or Phi node and has only predecessors
386  * within the loop.
387  *
388  * @param n    the node to check
389  * @param root only needed for assertion.
390  */
391 static int is_endless_head(ir_node *n, ir_node *root)
392 {
393         int i, arity;
394         int none_outof_loop = 1, some_in_loop = 0;
395
396         /* Test for legal loop header: Block, Phi, ... */
397         if (!is_possible_loop_head(n))
398                 return 0;
399
400         if (!is_outermost_Start(n)) {
401 #ifndef NDEBUG
402                 int uplink = get_irn_uplink(root);
403 #else
404                 (void) root;
405 #endif
406                 arity = get_irn_arity(n);
407                 for (i = get_start_index(n); i < arity; i++) {
408                         ir_node *pred;
409                         if (is_backedge(n, i))
410                                 continue;
411                         pred = get_irn_n(n, i);
412                         if (!irn_is_in_stack(pred)) {
413                                 none_outof_loop = 0;
414                         } else {
415                                 assert(get_irn_uplink(pred) >= uplink);
416                                 some_in_loop = 1;
417                         }
418                 }
419         }
420         return none_outof_loop & some_in_loop;
421 }
422
423 /** Returns index of the predecessor with the smallest dfn number
424     greater-equal than limit. */
425 static int smallest_dfn_pred(ir_node *n, int limit)
426 {
427         int i, index = -2, min = -1;
428
429         if (!is_outermost_Start(n)) {
430                 int arity = get_irn_arity(n);
431                 for (i = get_start_index(n); i < arity; i++) {
432                         ir_node *pred = get_irn_n(n, i);
433                         if (is_backedge(n, i) || !irn_is_in_stack(pred))
434                                 continue;
435                         if (get_irn_dfn(pred) >= limit && (min == -1 || get_irn_dfn(pred) < min)) {
436                                 index = i;
437                                 min = get_irn_dfn(pred);
438                         }
439                 }
440         }
441         return index;
442 }
443
444 /**
445  * Returns index of the predecessor with the largest dfn number.
446  */
447 static int largest_dfn_pred(ir_node *n)
448 {
449         int i, index = -2, max = -1;
450
451         if (!is_outermost_Start(n)) {
452                 int arity = get_irn_arity(n);
453                 for (i = get_start_index(n); i < arity; i++) {
454                         ir_node *pred = get_irn_n(n, i);
455                         if (is_backedge (n, i) || !irn_is_in_stack(pred))
456                                 continue;
457                         if (get_irn_dfn(pred) > max) {
458                                 index = i;
459                                 max = get_irn_dfn(pred);
460                         }
461                 }
462         }
463         return index;
464 }
465
466 /**
467  * Searches the stack for possible loop heads.  Tests these for backedges.
468  * If it finds a head with an unmarked backedge it marks this edge and
469  * returns the tail of the loop.
470  * If it finds no backedge returns NULL.
471  * ("disable_backedge" in fiasco)
472  *
473  * @param n  A node where uplink == dfn.
474  */
475 static ir_node *find_tail(ir_node *n)
476 {
477         ir_node *m;
478         int i, res_index = -2;
479
480         m = stack[tos-1];  /* tos = top of stack */
481         if (is_head(m, n)) {
482                 res_index = smallest_dfn_pred(m, 0);
483                 if ((res_index == -2) &&  /* no smallest dfn pred found. */
484                         (n ==  m))
485                         return NULL;
486         } else {
487                 if (m == n) return NULL;    // Is this to catch Phi - self loops?
488                 for (i = tos-2; i >= 0; --i) {
489                         m = stack[i];
490
491                         if (is_head(m, n)) {
492                                 res_index = smallest_dfn_pred(m, get_irn_dfn(m) + 1);
493                                 if (res_index == -2)  /* no smallest dfn pred found. */
494                                         res_index = largest_dfn_pred(m);
495
496                                 if ((m == n) && (res_index == -2)) {  /* don't walk past loop head. */
497                                         i = -1;
498                                 }
499                                 break;
500                         }
501
502                         /* We should not walk past our selves on the stack:  The upcoming nodes
503                            are not in this loop. We assume a loop not reachable from Start. */
504                         if (m == n) {
505                                 i = -1;
506                                 break;
507                         }
508                 }
509
510                 if (i < 0) {
511                         /* A dead loop not reachable from Start. */
512                         for (i = tos-2; i >= 0; --i) {
513                                 m = stack[i];
514                                 if (is_endless_head(m, n)) {
515                                         res_index = smallest_dfn_pred(m, get_irn_dfn(m) + 1);
516                                         if (res_index == -2)  /* no smallest dfn pred found. */
517                                                 res_index = largest_dfn_pred (m);
518                                         break;
519                                 }
520                                 /* It's not an unreachable loop, either. */
521                                 if (m == n)
522                                         break;
523                         }
524                         //assert(0 && "no head found on stack");
525                 }
526
527         }
528         if (res_index <= -2) {
529                 /* It's a completely bad loop: without Phi/Block nodes that can
530                    be a head. I.e., the code is "dying".  We break the loop by
531                    setting Bad nodes. */
532                 ir_graph *irg   = get_irn_irg(n);
533                 ir_mode  *mode  = get_irn_mode(n);
534                 ir_node  *bad   = new_r_Bad(irg, mode);
535                 int       arity = get_irn_arity(n);
536                 for (i = -1; i < arity; ++i) {
537                         set_irn_n(n, i, bad);
538                 }
539                 return NULL;
540         }
541         assert(res_index > -2);
542
543         set_backedge(m, res_index);
544         return is_outermost_Start(n) ? NULL : get_irn_n(m, res_index);
545 }
546
547 static inline int is_outermost_loop(ir_loop *l)
548 {
549         return l == get_loop_outer_loop(l);
550 }
551
552 /*-----------------------------------------------------------*
553  *                   The core algorithm.                     *
554  *-----------------------------------------------------------*/
555
556 /**
557  * The core algorithm: Find strongly coupled components.
558  *
559  * @param n  node to start
560  */
561 static void scc(ir_node *n)
562 {
563         if (irn_visited_else_mark(n))
564                 return;
565
566         /* Initialize the node */
567         set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
568         set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
569         set_irn_loop(n, NULL);
570         ++current_dfn;
571         push(n);
572
573         /* AS: get_start_index might return -1 for Control Flow Nodes, and thus a negative
574            array index would be passed to is_backedge(). But CFG Nodes dont't have a backedge array,
575            so is_backedge does not access array[-1] but correctly returns false! */
576
577         if (!is_outermost_Start(n)) {
578                 int i, arity = get_irn_arity(n);
579
580                 for (i = get_start_index(n); i < arity; ++i) {
581                         ir_node *m;
582                         if (is_backedge(n, i))
583                                 continue;
584                         m = get_irn_n(n, i);
585                         scc(m);
586                         if (irn_is_in_stack(m)) {
587                                 /* Uplink of m is smaller if n->m is a backedge.
588                                    Propagate the uplink to mark the loop. */
589                                 if (get_irn_uplink(m) < get_irn_uplink(n))
590                                         set_irn_uplink(n, get_irn_uplink(m));
591                         }
592                 }
593         }
594
595         if (get_irn_dfn(n) == get_irn_uplink(n)) {
596                 /* This condition holds for
597                    1) the node with the incoming backedge.
598                       That is: We found a loop!
599                    2) Straight line code, because no uplink has been propagated, so the
600                       uplink still is the same as the dfn.
601
602                    But n might not be a proper loop head for the analysis. Proper loop
603                    heads are Block and Phi nodes. find_tail() searches the stack for
604                    Block's and Phi's and takes those nodes as loop heads for the current
605                    loop instead and marks the incoming edge as backedge. */
606
607                 ir_node *tail = find_tail(n);
608                 if (tail != NULL) {
609                         /* We have a loop, that is no straight line code,
610                            because we found a loop head!
611                            Next actions: Open a new loop on the loop tree and
612                                          try to find inner loops */
613
614                         /* This is an adaption of the algorithm from fiasco / optscc to
615                          * avoid loops without Block or Phi as first node.  This should
616                          * severely reduce the number of evaluations of nodes to detect
617                          * a fixpoint in the heap analysis.
618                          * Further it avoids loops without firm nodes that cause errors
619                          * in the heap analyses.
620                          * But attention:  don't do it for the outermost loop:  This loop
621                          * is not iterated.  A first block can be a loop head in case of
622                          * an endless recursion. */
623
624                         ir_loop *l;
625                         int close;
626                         if ((get_loop_n_elements(current_loop) > 0) || (is_outermost_loop(current_loop))) {
627                                 l = new_loop();
628                                 close = 1;
629                         } else {
630                                 l = current_loop;
631                                 close = 0;
632                         }
633
634                         /* Remove the loop from the stack ... */
635                         pop_scc_unmark_visit(n);
636
637                         /* The current backedge has been marked, that is temporarily eliminated,
638                            by find tail. Start the scc algorithm
639                            again on the subgraph that is left (the current loop without the backedge)
640                            in order to find more inner loops. */
641                         scc(tail);
642
643                         assert(irn_visited(n));
644                         if (close)
645                                 close_loop(l);
646                 } else {
647                         /* No loop head was found, that is we have straight line code.
648                            Pop all nodes from the stack to the current loop. */
649                         pop_scc_to_loop(n);
650                 }
651         }
652 }
653
654 void construct_backedges(ir_graph *irg)
655 {
656         ir_graph *rem = current_ir_graph;
657         ir_loop *head_rem;
658         struct obstack temp;
659
660         current_ir_graph   = irg;
661         outermost_ir_graph = irg;
662
663         obstack_init(&temp);
664         init_scc(irg, &temp);
665
666         current_loop = NULL;
667         new_loop();  /* sets current_loop */
668         head_rem = current_loop; /* Just for assertion */
669
670         inc_irg_visited(irg);
671
672         scc(get_irg_end(irg));
673
674         finish_scc();
675         obstack_free(&temp, NULL);
676
677         assert(head_rem == current_loop);
678         mature_loops(current_loop, get_irg_obstack(irg));
679         set_irg_loop(irg, current_loop);
680         add_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
681         assert(get_irg_loop(irg)->kind == k_ir_loop);
682         current_ir_graph = rem;
683 }
684
685 static void reset_backedges(ir_node *n)
686 {
687         if (is_possible_loop_head(n)) {
688                 clear_backedges(n);
689         }
690 }
691
692 static void loop_reset_node(ir_node *n, void *env)
693 {
694         (void) env;
695         set_irn_loop(n, NULL);
696         reset_backedges(n);
697 }
698
699 void free_loop_information(ir_graph *irg)
700 {
701         irg_walk_graph(irg, loop_reset_node, NULL, NULL);
702         set_irg_loop(irg, NULL);
703         clear_irg_properties(current_ir_graph, IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
704         /* We cannot free the loop nodes, they are on the obstack. */
705 }
706
707 void free_all_loop_information(void)
708 {
709         size_t i;
710         for (i = 0; i < get_irp_n_irgs(); i++) {
711                 free_loop_information(get_irp_irg(i));
712         }
713 }
714
715 /* ------------------------------------------------------------------- */
716 /* Simple analyses based on the loop information                       */
717 /* ------------------------------------------------------------------- */
718
719 static int is_loop_variant(ir_loop *l, ir_loop *b)
720 {
721         size_t i, n_elems;
722
723         if (l == b) return 1;
724
725         n_elems = get_loop_n_elements(l);
726         for (i = 0; i < n_elems; ++i) {
727                 loop_element e = get_loop_element(l, i);
728                 if (is_ir_loop(e.kind))
729                         if (is_loop_variant(e.son, b))
730                                 return 1;
731         }
732
733         return 0;
734 }
735
736 int is_loop_invariant(const ir_node *n, const ir_node *block)
737 {
738         ir_loop *l = get_irn_loop(block);
739         const ir_node *b = is_Block(n) ? n : get_nodes_block(n);
740         return !is_loop_variant(l, get_irn_loop(b));
741 }