53074ca8382bbcd59559f12c55face6d912c5a95
[libfirm] / ir / ana / ircfscc.c
1 /*
2  * Copyright (C) 1995-2011 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 backedge/cfloop
23  *            datastructures. A variation on the Tarjan algorithm. See also
24  *            [Trapp:99], Chapter 5.2.1.2.
25  * @author    Goetz Lindenmaier
26  * @date      7.2002
27  */
28 #include "config.h"
29
30 #include <string.h>
31
32 #include "irloop_t.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "array.h"
36 #include "pmap.h"
37 #include "irgwalk.h"
38 #include "irprog_t.h"
39 #include "irdump.h"
40 #include "ircons_t.h"
41
42 #define NO_CFLOOPS_WITHOUT_HEAD 1
43
44 /** The outermost graph the scc is computed for */
45 static ir_graph *outermost_ir_graph;
46 /** Current cfloop construction is working on. */
47 static ir_loop *current_loop;
48 /** Counts the number of allocated cfloop nodes.
49  * Each cfloop node gets a unique number.
50  * @todo What for? ev. remove.
51  */
52 static int loop_node_cnt = 0;
53 /** Counter to generate depth first numbering of visited nodes. */
54 static int current_dfn = 1;
55
56 static unsigned max_loop_depth = 0;
57
58 void link_to_reg_end(ir_node *n, void *env);
59
60 /**********************************************************************/
61 /* Node attributes                                                   **/
62 /**********************************************************************/
63
64 /**********************************************************************/
65 /* Node attributes needed for the construction.                      **/
66 /**********************************************************************/
67
68 /**
69  * The SCC info. Additional fields for an ir-node needed for the
70  * construction.
71  */
72 typedef struct scc_info {
73         int in_stack;          /**< Marks whether node is on the stack. */
74         int dfn;               /**< Depth first search number. */
75         int uplink;            /**< dfn number of ancestor. */
76 } scc_info;
77
78 /** Allocate a new scc_info on the given obstack */
79 static inline scc_info *new_scc_info(struct obstack *obst)
80 {
81         return OALLOCZ(obst, scc_info);
82 }
83
84 /**
85  * Marks the node n to be on the stack.
86  */
87 static inline void mark_irn_in_stack(ir_node *n)
88 {
89         scc_info *info = (scc_info*) get_irn_link(n);
90         info->in_stack = 1;
91 }
92
93 /**
94  * Marks the node n to be not on the stack.
95  */
96 static inline void mark_irn_not_in_stack(ir_node *n)
97 {
98         scc_info *info = (scc_info*) get_irn_link(n);
99         info->in_stack = 0;
100 }
101
102 /**
103  * Returns whether node n is on the stack.
104  */
105 static inline int irn_is_in_stack(ir_node *n)
106 {
107         scc_info *info = (scc_info*) get_irn_link(n);
108         return info->in_stack;
109 }
110
111 /**
112  * Sets node n uplink value.
113  */
114 static inline void set_irn_uplink(ir_node *n, int uplink)
115 {
116         scc_info *info = (scc_info*) get_irn_link(n);
117         info->uplink = uplink;
118 }
119
120 /**
121  * Return node n uplink value.
122  */
123 static inline int get_irn_uplink(ir_node *n)
124 {
125         scc_info *info = (scc_info*) get_irn_link(n);
126         return info->uplink;
127 }
128
129 /**
130  * Sets node n dfn value.
131  */
132 static inline void set_irn_dfn(ir_node *n, int dfn)
133 {
134         scc_info *info = (scc_info*) get_irn_link(n);
135         info->dfn = dfn;
136 }
137
138 /**
139  * Returns node n dfn value.
140  */
141 static inline int get_irn_dfn(ir_node *n)
142 {
143         scc_info *info = (scc_info*) get_irn_link(n);
144         return info->dfn;
145 }
146
147 /**********************************************************************/
148 /* A stack.                                                          **/
149 /**********************************************************************/
150
151 /** An IR-node stack */
152 static ir_node **stack = NULL;
153 /** The top (index) of the IR-node stack */
154 static size_t    tos = 0;
155
156 /**
157  * Initializes the IR-node stack
158  */
159 static inline void init_stack(void)
160 {
161         if (stack) {
162                 ARR_RESIZE(ir_node *, stack, 1000);
163         } else {
164                 stack = NEW_ARR_F(ir_node *, 1000);
165         }
166         tos = 0;
167 }
168
169 static void finish_stack(void)
170 {
171         DEL_ARR_F(stack);
172         stack = NULL;
173 }
174
175 /**
176  * Push a node n onto the IR-node stack.
177  */
178 static inline void push(ir_node *n)
179 {
180         if (tos == ARR_LEN(stack)) {
181                 size_t nlen = ARR_LEN(stack) * 2;
182                 ARR_RESIZE(ir_node *, stack, nlen);
183         }
184         stack[tos++] = n;
185         mark_irn_in_stack(n);
186 }
187
188 /**
189  * Pop a node from the IR-node stack and return it.
190  */
191 static inline ir_node *pop(void)
192 {
193         ir_node *n = stack[--tos];
194         mark_irn_not_in_stack(n);
195         return n;
196 }
197
198 /**
199  * The nodes from tos up to n belong to the current loop.
200  * Removes them from the stack and adds them to the current loop.
201  */
202 static inline void pop_scc_to_loop(ir_node *n)
203 {
204         ir_node *m;
205
206         do {
207                 m = pop();
208                 loop_node_cnt++;
209                 set_irn_dfn(m, loop_node_cnt);
210                 add_loop_node(current_loop, m);
211                 set_irn_loop(m, current_loop);
212         } while (m != n);
213 }
214
215 /* GL ??? my last son is my grandson???  Removes cfloops with no
216    ir_nodes in them.  Such loops have only another loop as son. (Why
217    can't they have two loops as sons? Does it never get that far? ) */
218 static void close_loop(ir_loop *l)
219 {
220         size_t last = get_loop_n_elements(l) - 1;
221         loop_element lelement = get_loop_element(l, last);
222         ir_loop *last_son = lelement.son;
223
224         if (get_kind(last_son) == k_ir_loop &&
225             get_loop_n_elements(last_son) == 1) {
226                 ir_loop *gson;
227
228                 lelement = get_loop_element(last_son, 0);
229                 gson = lelement.son;
230                 if (get_kind(gson) == k_ir_loop) {
231                         loop_element new_last_son;
232
233                         gson->outer_loop = l;
234                         new_last_son.son = gson;
235                         l->children[last] = new_last_son;
236
237                         /* the loop last_son is dead now, recover at least some memory */
238                         DEL_ARR_F(last_son->children);
239                 }
240         }
241
242         current_loop = l;
243 }
244
245 /**
246  * Removes and unmarks all nodes up to n from the stack.
247  * The nodes must be visited once more to assign them to a scc.
248  */
249 static inline void pop_scc_unmark_visit(ir_node *n)
250 {
251         ir_node *m;
252
253         do {
254                 m = pop();
255                 set_irn_visited(m, 0);
256         } while (m != n);
257 }
258
259 /**********************************************************************/
260 /* The loop datastructure.                                           **/
261 /**********************************************************************/
262
263 /**
264  * Allocates a new loop as son of current_loop.  Sets current_loop
265  * to the new loop and returns its father.
266  * The loop is allocated on the outermost_ir_graphs's obstack.
267  */
268 static ir_loop *new_loop(void)
269 {
270         ir_loop *father = current_loop;
271         ir_loop *son    = alloc_loop(father, get_irg_obstack(outermost_ir_graph));
272
273         if (son->depth > max_loop_depth) max_loop_depth = son->depth;
274         current_loop = son;
275         return father;
276 }
277
278 /**********************************************************************/
279 /* Constructing and destructing the loop/backedge information.       **/
280 /**********************************************************************/
281
282 /* Initialization steps. **********************************************/
283
284 /**
285  * Allocates a scc_info for every Block node n.
286  * Clear the backedges for all nodes.
287  * Called from a walker.
288  */
289 static inline void init_node(ir_node *n, void *env)
290 {
291         struct obstack *obst = (struct obstack*) env;
292         if (is_Block(n))
293                 set_irn_link(n, new_scc_info(obst));
294         clear_backedges(n);
295 }
296
297 /**
298  * Initializes the common global settings for the scc algorithm
299  */
300 static inline void init_scc_common(void)
301 {
302         current_dfn   = 1;
303         loop_node_cnt = 0;
304         init_stack();
305 }
306
307 /**
308  * Initializes the scc algorithm for the intraprocedural case.
309  * Add scc info to every block node.
310  */
311 static inline void init_scc(ir_graph *irg, struct obstack *obst)
312 {
313         init_scc_common();
314         irg_walk_graph(irg, init_node, NULL, obst);
315 }
316
317 static inline void finish_scc(void)
318 {
319         finish_stack();
320 }
321
322 /** Returns non-zero if n is a loop header, i.e., it is a Block node
323  *  and has predecessors within the cfloop and out of the cfloop.
324  *
325  *  @param n     the block node to check
326  *  @param root  only needed for assertion.
327  */
328 static int is_head(ir_node *n, ir_node *root)
329 {
330         int i, arity;
331         int some_outof_loop = 0, some_in_loop = 0;
332         (void) root;
333
334         assert(is_Block(n));
335
336         arity = get_Block_n_cfgpreds(n);
337         for (i = 0; i < arity; i++) {
338                 ir_node *pred = get_Block_cfgpred_block(n, i);
339                 /* ignore Bad control flow: it cannot happen */
340                 if (is_Bad(pred))
341                         continue;
342                 if (is_backedge(n, i))
343                         continue;
344                 if (!irn_is_in_stack(pred)) {
345                         some_outof_loop = 1;
346                 } else {
347                         assert(get_irn_uplink(pred) >= get_irn_uplink(root));
348                         some_in_loop = 1;
349                 }
350         }
351         return some_outof_loop & some_in_loop;
352 }
353
354
355 /**
356  * Returns non-zero if n is possible loop head of an endless loop.
357  * I.e., it is a Block node and has only predecessors
358  * within the loop.
359  *
360  * @param n     the block node to check
361  * @param root  only needed for assertion.
362  */
363 static int is_endless_head(ir_node *n, ir_node *root)
364 {
365         int i, arity;
366         int none_outof_loop = 1, some_in_loop = 0;
367         (void) root;
368
369         assert(is_Block(n));
370         /* Test for legal loop header: Block, Phi, ... */
371         arity = get_Block_n_cfgpreds(n);
372         for (i = 0; i < arity; i++) {
373                 ir_node *pred = get_Block_cfgpred_block(n, i);
374                 /* ignore Bad control flow: it cannot happen */
375                 if (is_Bad(pred))
376                         continue;
377                 if (is_backedge(n, i))
378                         continue;
379                 if (!irn_is_in_stack(pred)) {
380                         none_outof_loop = 0;
381                 } else {
382                         assert(get_irn_uplink(pred) >= get_irn_uplink(root));
383                         some_in_loop = 1;
384                 }
385         }
386         return none_outof_loop && some_in_loop;
387 }
388
389 /**
390  * Returns index of the predecessor with the smallest dfn number
391  * greater-equal than limit.
392  */
393 static int smallest_dfn_pred(ir_node *n, int limit)
394 {
395         int i, index = -2, min = -1;
396
397         int arity = get_Block_n_cfgpreds(n);
398         for (i = 0; i < arity; i++) {
399                 ir_node *pred = get_Block_cfgpred_block(n, i);
400                 /* ignore Bad control flow: it cannot happen */
401                 if (is_Bad(pred))
402                         continue;
403                 if (is_backedge(n, i) || !irn_is_in_stack(pred))
404                         continue;
405                 if (get_irn_dfn(pred) >= limit && (min == -1 || get_irn_dfn(pred) < min)) {
406                         index = i;
407                         min = get_irn_dfn(pred);
408                 }
409         }
410         return index;
411 }
412
413 /**
414  * Returns index of the predecessor with the largest dfn number.
415  */
416 static int largest_dfn_pred(ir_node *n)
417 {
418         int i, index = -2, max = -1;
419
420         int arity = get_Block_n_cfgpreds(n);
421         for (i = 0; i < arity; i++) {
422                 ir_node *pred = get_Block_cfgpred_block(n, i);
423                 /* ignore Bad control flow: it cannot happen */
424                 if (is_Bad(pred))
425                         continue;
426                 if (is_backedge(n, i) || !irn_is_in_stack(pred))
427                         continue;
428                 if (get_irn_dfn(pred) > max) {
429                         index = i;
430                         max = get_irn_dfn(pred);
431                 }
432         }
433         return index;
434 }
435
436 /**
437  * Searches the stack for possible loop heads.  Tests these for backedges.
438  * If it finds a head with an unmarked backedge it marks this edge and
439  * returns the tail of the loop.
440  * If it finds no backedge returns NULL.
441  */
442 static ir_node *find_tail(ir_node *n)
443 {
444         ir_node *m;
445         int      res_index = -2;
446         size_t   i;
447
448         m = stack[tos - 1];  /* tos = top of stack */
449         if (is_head(m, n)) {
450                 res_index = smallest_dfn_pred(m, 0);
451                 if ((res_index == -2) &&  /* no smallest dfn pred found. */
452                         (n ==  m))
453                         return NULL;
454         } else {
455                 if (m == n)
456                         return NULL;
457                 for (i = tos - 1; i != 0;) {
458                         m = stack[--i];
459                         if (is_head(m, n)) {
460                                 res_index = smallest_dfn_pred(m, get_irn_dfn(m) + 1);
461                                 if (res_index == -2)  /* no smallest dfn pred found. */
462                                         res_index = largest_dfn_pred(m);
463
464                                 if ((m == n) && (res_index == -2)) {
465                                         i = (size_t)-1;
466                                 }
467                                 break;
468                         }
469
470
471                         /* We should not walk past our selves on the stack:  The upcoming nodes
472                            are not in this loop. We assume a loop not reachable from Start. */
473                         if (m == n) {
474                                 i = (size_t)-1;
475                                 break;
476                         }
477                 }
478
479                 if (i == (size_t)-1) {
480                         /* A dead loop not reachable from Start. */
481                         for (i = tos - 1; i != 0;) {
482                                 m = stack[--i];
483                                 if (is_endless_head(m, n)) {
484                                         res_index = smallest_dfn_pred (m, get_irn_dfn(m) + 1);
485                                         if (res_index == -2)  /* no smallest dfn pred found. */
486                                                 res_index = largest_dfn_pred(m);
487                                         break;
488                                 }
489                                 if (m == n) break;   /* It's not an unreachable loop, either. */
490                         }
491                         //assert(0 && "no head found on stack");
492                 }
493         }
494         assert(res_index > -2);
495
496         set_backedge(m, res_index);
497         return get_Block_cfgpred_block(m, res_index);
498 }
499
500 /**
501  * returns non.zero if l is the outermost loop.
502  */
503 inline static int is_outermost_loop(ir_loop *l)
504 {
505         return l == get_loop_outer_loop(l);
506 }
507
508 /*-----------------------------------------------------------*
509  *                   The core algorithm.                     *
510  *-----------------------------------------------------------*/
511
512 /**
513  * Walks over all blocks of a graph
514  */
515 static void cfscc(ir_node *n)
516 {
517         int arity;
518         int i;
519
520         assert(is_Block(n));
521
522         if (irn_visited_else_mark(n)) return;
523
524         /* Initialize the node */
525         set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
526         set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
527         set_irn_loop(n, NULL);
528         ++current_dfn;
529         push(n);
530
531         arity = get_Block_n_cfgpreds(n);
532
533         for (i = 0; i < arity; i++) {
534                 ir_node *m;
535
536                 if (is_backedge(n, i))
537                         continue;
538                 m = get_Block_cfgpred_block(n, i);
539                 /* ignore Bad control flow: it cannot happen */
540                 if (is_Bad(m))
541                         continue;
542
543                 cfscc(m);
544                 if (irn_is_in_stack(m)) {
545                         /* Uplink of m is smaller if n->m is a backedge.
546                            Propagate the uplink to mark the cfloop. */
547                         if (get_irn_uplink(m) < get_irn_uplink(n))
548                                 set_irn_uplink(n, get_irn_uplink(m));
549                 }
550         }
551
552         if (get_irn_dfn(n) == get_irn_uplink(n)) {
553                 /* This condition holds for
554                    1) the node with the incoming backedge.
555                       That is: We found a cfloop!
556                    2) Straight line code, because no uplink has been propagated, so the
557                       uplink still is the same as the dfn.
558
559                    But n might not be a proper cfloop head for the analysis. Proper cfloop
560                    heads are Block and Phi nodes. find_tail searches the stack for
561                    Block's and Phi's and takes those nodes as cfloop heads for the current
562                    cfloop instead and marks the incoming edge as backedge. */
563
564                 ir_node *tail = find_tail(n);
565                 if (tail) {
566                         /* We have a cfloop, that is no straight line code,
567                            because we found a cfloop head!
568                            Next actions: Open a new cfloop on the cfloop tree and
569                            try to find inner cfloops */
570
571 #if NO_CFLOOPS_WITHOUT_HEAD
572
573                         /* This is an adaption of the algorithm from fiasco / optscc to
574                          * avoid cfloops without Block or Phi as first node.  This should
575                          * severely reduce the number of evaluations of nodes to detect
576                          * a fixpoint in the heap analysis.
577                          * Further it avoids cfloops without firm nodes that cause errors
578                          * in the heap analyses. */
579
580                         ir_loop *l;
581                         int close;
582                         if ((get_loop_n_elements(current_loop) > 0) || (is_outermost_loop(current_loop))) {
583                                 l = new_loop();
584                                 close = 1;
585                         } else {
586                                 l = current_loop;
587                                 close = 0;
588                         }
589
590 #else
591
592                         ir_loop *l = new_loop();
593
594 #endif
595
596                         /* Remove the cfloop from the stack ... */
597                         pop_scc_unmark_visit(n);
598
599                         /* The current backedge has been marked, that is temporarily eliminated,
600                            by find tail. Start the scc algorithm
601                            anew on the subgraph thats left (the current cfloop without the backedge)
602                            in order to find more inner cfloops. */
603
604                         cfscc(tail);
605
606                         assert(irn_visited(n));
607 #if NO_CFLOOPS_WITHOUT_HEAD
608                         if (close)
609 #endif
610                                 close_loop(l);
611                 } else {
612                         /* AS: No cfloop head was found, that is we have straight line code.
613                                Pop all nodes from the stack to the current cfloop. */
614                         pop_scc_to_loop(n);
615                 }
616         }
617 }
618
619 int construct_cf_backedges(ir_graph *irg)
620 {
621         ir_loop *head_rem;
622         ir_node *end = get_irg_end(irg);
623         struct obstack temp;
624         int i;
625
626         max_loop_depth = 0;
627
628         outermost_ir_graph = irg;
629
630         obstack_init(&temp);
631         init_scc(irg, &temp);
632
633         current_loop = NULL;
634         new_loop();  /* sets current_loop */
635         head_rem = current_loop; /* Just for assertion */
636
637         inc_irg_visited(irg);
638
639         /* walk over all blocks of the graph, including keep alives */
640         cfscc(get_irg_end_block(irg));
641         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
642                 ir_node *el = get_End_keepalive(end, i);
643                 if (is_Block(el))
644                         cfscc(el);
645         }
646         finish_scc();
647         obstack_free(&temp, NULL);
648
649         assert(head_rem == current_loop);
650         mature_loops(current_loop, get_irg_obstack(irg));
651         set_irg_loop(irg, current_loop);
652         add_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
653
654         return max_loop_depth;
655 }
656
657 void assure_loopinfo(ir_graph *irg)
658 {
659         if (irg_has_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO))
660                 return;
661         construct_cf_backedges(irg);
662 }