Merge Fix: Spills have ProjMs now
[libfirm] / ir / ana / structure.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    Structure Analysis
23  * @author   Michael Beck
24  * @date     5.4.2007
25  * @version  $Id$
26  */
27 #include "config.h"
28
29 #include <stdbool.h>
30
31 #include "firm_common.h"
32 #include "irnode_t.h"
33 #include "structure.h"
34 #include "irdom.h"
35 #include "irouts.h"
36 #include "irtools.h"
37 #include "irgwalk.h"
38 #include "array.h"
39 #include "irdump.h"
40
41 #include "debug.h"
42
43 typedef union ir_reg_or_blk ir_reg_or_blk;
44
45 /* The structure tree. */
46 struct ir_reg_tree {
47         struct obstack obst;   /**< The obstack where the data is allocated. */
48         ir_region *top;        /**< The top region. */
49         ir_graph *irg;         /**< Associated graph. */
50 };
51
52 /* A region. */
53 struct ir_region {
54         firm_kind      kind;      /**< Must be k_ir_region. */
55         ir_region_kind type;      /**< The type of this region. */
56         ir_region      *parent;   /**< points to the parent. */
57         ir_reg_or_blk  *parts;    /**< The list of all region parts. */
58         ir_region      **pred;    /**< The predecessor (control flow) regions of this region. */
59         ir_region      **succ;    /**< The successor (control flow) regions of this region. */
60         size_t         prenum;    /**< DFS pre-oder number */
61         size_t         postnum;   /**< DFS post-oder number */
62         void           *link;     /**< A link field. */
63         unsigned long  nr;        /**< for debugging */
64         unsigned       visited:1; /**< The visited flag. */
65         unsigned       exit:1;    /**< If set, the parent region can be left by this node. */
66         unsigned       enter:1;   /**< If set, the parent region can be entered by this node. */
67 };
68
69 /* A helper type for unioning blocks and regions. */
70 union ir_reg_or_blk {
71         firm_kind *kind;    /**< For easier check. */
72         ir_node   *blk;     /**< A node */
73         ir_region *region;  /**< A region. */
74 };
75
76 /* The debug handle. */
77 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
78
79 /**
80  * Returns the link of a region.
81  */
82 void *get_region_link(const ir_region *reg)
83 {
84         return reg->link;
85 }
86
87 /**
88  * Sets the link of a region.
89  */
90 void set_region_link(ir_region *reg, void *data)
91 {
92         reg->link = data;
93 }
94
95 /**
96  * Get the immediate region of a block.
97  */
98 ir_region *get_block_region(const ir_node *block)
99 {
100         assert(is_Block(block));
101         return block->attr.block.region;
102 }
103
104 /**
105  * Sets the immediate region of a block.
106  */
107 void set_block_region(ir_node *block, ir_region *reg)
108 {
109         assert(is_Block(block));
110         block->attr.block.region = reg;
111 }
112
113 /**
114  * Get the immediate region of a node.
115  */
116 ir_region *get_irn_region(ir_node *n)
117 {
118         if (!is_Block(n))
119                 n = get_nodes_block(n);
120         return get_block_region(n);
121 }
122
123 /**
124  * Return non-zero if a given firm thing is a region.
125  */
126 int is_region(const void *thing)
127 {
128         const firm_kind *kind = (const firm_kind*) thing;
129         return *kind == k_ir_region;
130 }
131
132 /**
133  * Return the number of predecessors of a region.
134  */
135 size_t get_region_n_preds(const ir_region *reg)
136 {
137         return ARR_LEN(reg->pred);
138 }
139
140 /**
141  * Return the predecessor region at position pos.
142  */
143 ir_region *get_region_pred(const ir_region *reg, size_t pos)
144 {
145         assert(pos <= get_region_n_preds(reg));
146         return reg->pred[pos];
147 }
148
149 /**
150  * Set the predecessor region at position pos.
151  */
152 void set_region_pred(ir_region *reg, size_t pos, ir_region *n)
153 {
154         assert(pos <= get_region_n_preds(reg));
155         reg->pred[pos] = n;
156 }
157
158 /**
159  * Return the number of successors in a region.
160  */
161 size_t get_region_n_succs(const ir_region *reg)
162 {
163         return ARR_LEN(reg->succ);
164 }
165
166 /**
167  * Return the successor region at position pos.
168  */
169 ir_region *get_region_succ(const ir_region *reg, size_t pos)
170 {
171         assert(pos <= get_region_n_succs(reg));
172         return reg->succ[pos];
173 }
174
175 /**
176  * Set the successor region at position pos.
177  */
178 void set_region_succ(ir_region *reg, size_t pos, ir_region *n)
179 {
180         assert(pos <= get_region_n_succs(reg));
181         reg->succ[pos] = n;
182 }
183
184 /* ----------------------- construction -------------------------- */
185
186 /** Walker environment. */
187 typedef struct walk_env {
188         struct obstack *obst;  /**< An obstack to allocate from. */
189         ir_region **post;      /**< The list of all currently existent top regions. */
190         size_t l_post;         /**< The length of the allocated regions array. */
191         size_t premax;         /**< maximum pre counter */
192         size_t postmax;        /**< maximum post counter */
193         ir_node *start_block;  /**< The start block of the graph. */
194         ir_node *end_block;    /**< The end block of the graph. */
195 } walk_env;
196
197 /**
198  * Do a DFS search on the initial regions, assign a prenum and a postnum to every
199  * node and store the region nodes into the post array.
200  */
201 static void dfs_walk2(ir_region *reg, walk_env *env)
202 {
203         size_t i, n;
204
205         if (reg->visited == 0) {
206                 reg->visited = 1;
207
208                 reg->prenum = env->premax++;
209                 for (i = 0, n = get_region_n_succs(reg); i < n; ++i) {
210                         /* recursion */
211                         ir_region *succ = get_region_succ(reg, i);
212                         dfs_walk2(succ, env);
213                 }
214
215                 env->post[env->postmax] = reg;
216                 reg->postnum = env->postmax++;
217         }
218 }
219
220 /**
221  * Do a DFS search on the initial regions, assign a prenum and a postnum to every
222  * node and store the region nodes into the post array.
223  */
224 static void dfs_walk(ir_graph *irg, walk_env *env)
225 {
226         ir_graph *rem = current_ir_graph;
227         ir_region *reg;
228
229         current_ir_graph = irg;
230         reg              = (ir_region*) get_irn_link(get_irg_start_block(irg));
231
232         env->premax  = 0;
233         env->postmax = 0;
234         dfs_walk2(reg, env);
235         current_ir_graph = rem;
236 }
237
238 /**
239  * Post-walker: wrap all blocks with a BasicBlock region
240  * and count them
241  */
242 static void wrap_BasicBlocks(ir_node *block, void *ctx)
243 {
244         walk_env *env = (walk_env*) ctx;
245         ir_region *reg;
246
247         /* Allocate a Block wrapper */
248         reg          = OALLOC(env->obst, ir_region);
249         reg->kind    = k_ir_region;
250         reg->type    = ir_rk_BasicBlock;
251         reg->parent  = NULL;
252         reg->prenum  = 0;
253         reg->postnum = 0;
254         reg->visited = 0;
255         reg->exit    = 0;
256         reg->enter   = 0;
257         reg->link    = NULL;
258         reg->nr      = get_irn_node_nr(block);
259         reg->parts   = NEW_ARR_D(ir_reg_or_blk, env->obst, 1);
260
261         reg->parts[0].blk = block;
262         set_irn_link(block, reg);
263
264         ++env->l_post;
265 }  /* wrap_BasicBlocks */
266
267 /**
268  * Post-walker: Create the pred and succ edges for Block wrapper.
269  * Kill edges to the Start and End blocks.
270  */
271 static void update_BasicBlock_regions(ir_node *blk, void *ctx)
272 {
273         walk_env *env = (walk_env*) ctx;
274         ir_region *reg = (ir_region*) get_irn_link(blk);
275         int i, len;
276         size_t j;
277
278         if (blk == env->start_block) {
279                 /* handle Firm's self loop: Start block has no predecessors */
280                 reg->pred = NEW_ARR_D(ir_region *, env->obst, 0);
281         } else {
282                 len = get_Block_n_cfgpreds(blk);
283                 reg->pred = NEW_ARR_D(ir_region *, env->obst, len);
284                 for (j = i = 0; i < len; ++i) {
285                         ir_node *pred = get_Block_cfgpred_block(blk, i);
286                         reg->pred[j++] = (ir_region*) get_irn_link(pred);
287                 }
288                 ARR_SHRINKLEN(reg->pred, j);
289         }
290
291         len = get_Block_n_cfg_outs(blk);
292         reg->succ = NEW_ARR_D(ir_region *, env->obst, len);
293         for (j = i = 0; i < len; ++i) {
294                 ir_node *succ = get_Block_cfg_out(blk, i);
295                 reg->succ[j++] = (ir_region*) get_irn_link(succ);
296         }
297         ARR_SHRINKLEN(reg->succ, j);
298 }  /* update_BasicBlock_regions */
299
300 /** Allocate a new region on an obstack */
301 static ir_region *alloc_region(struct obstack *obst, ir_region_kind type)
302 {
303         ir_region *reg = OALLOC(obst, ir_region);
304         reg->kind    = k_ir_region;
305         reg->type    = type;
306         reg->parent  = NULL;
307         reg->prenum  = 0;
308         reg->postnum = 0;
309         reg->visited = 0;
310         reg->exit    = 0;
311         reg->enter   = 0;
312         reg->link    = NULL;
313
314         return reg;
315 }  /* alloc_region */
316
317 /**
318  * Creates a new Sequence region.
319  */
320 static ir_region *new_Sequence(struct obstack *obst, ir_region *nset, size_t nset_len)
321 {
322         ir_region *reg  = alloc_region(obst, ir_rk_Sequence);
323         ir_region *next;
324         size_t    i;
325
326         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, nset_len);
327
328         /* beware: list is in reverse order, reverse */
329         next = nset;
330         for (i = nset_len; i > 0;) {
331                 --i;
332                 nset = next;
333                 reg->parts[i].region = nset;
334                 nset->parent = reg;
335                 next = (ir_region*) nset->link;
336                 nset->link = NULL;
337         }
338
339         reg->nr   = reg->parts[0].region->nr;
340         reg->pred = DUP_ARR_D(ir_region *, obst, reg->parts[0].region->pred);
341         reg->succ = DUP_ARR_D(ir_region *, obst, reg->parts[nset_len - 1].region->succ);
342
343         DEBUG_ONLY(
344                 DB((dbg, LEVEL_2, " Created Sequence "));
345                 for (i = 0; i < nset_len; ++i) {
346                         DB((dbg, LEVEL_2, "(%lu)", reg->parts[i].region->nr));
347                 }
348                 DB((dbg, LEVEL_2, "\n"));
349         )
350         return reg;
351 }  /* new_Sequence */
352
353 /**
354  * Create a new IfThenElse region.
355  */
356 static ir_region *new_IfThenElse(struct obstack *obst, ir_region *if_b, ir_region *then_b, ir_region *else_b)
357 {
358         ir_region *reg = alloc_region(obst, ir_rk_IfThenElse);
359
360         reg->nr    = if_b->nr;
361         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 3);
362
363         reg->parts[0].region = if_b;   if_b->parent   = reg;
364         reg->parts[1].region = then_b; then_b->parent = reg;
365         reg->parts[2].region = else_b; else_b->parent = reg;
366
367         reg->pred = DUP_ARR_D(ir_region *, obst, if_b->pred);
368         reg->succ = DUP_ARR_D(ir_region *, obst, then_b->succ);
369
370         DB((dbg, LEVEL_2, " Created If(%lu)Then(%lu)Else(%lu)\n", reg->nr, then_b->nr, else_b->nr));
371
372         return reg;
373 }  /* new_IfThenElse */
374
375 /**
376  * Create a new IfThen region.
377  */
378 static ir_region *new_IfThen(struct obstack *obst, ir_region *if_b, ir_region *then_b)
379 {
380         ir_region *reg = alloc_region(obst, ir_rk_IfThen);
381
382         reg->nr    = if_b->nr;
383         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 2);
384
385         reg->parts[0].region = if_b;   if_b->parent   = reg;
386         reg->parts[1].region = then_b; then_b->parent = reg;
387
388         reg->pred = DUP_ARR_D(ir_region *, obst, if_b->pred);
389         reg->succ = DUP_ARR_D(ir_region *, obst, then_b->succ);
390
391         DB((dbg, LEVEL_2, " Created If(%lu)Then(%lu)\n", reg->nr, then_b->nr));
392
393         return reg;
394 }  /* new_IfThenElse */
395
396 /**
397  * Create a new Switch/case region.
398  */
399 static ir_region *new_SwitchCase(struct obstack *obst, ir_region_kind type, ir_region *head, ir_region *exit,
400                                  ir_region *cases, size_t cases_len)
401 {
402         ir_region *reg = alloc_region(obst, type);
403         ir_region *c, *n;
404         int       add = 1;
405         size_t    i;
406
407         /* check, if the exit block is in the list */
408         for (c = cases; c != NULL; c = (ir_region*) c->link) {
409                 if (c == exit) {
410                         add = 0;
411                         break;
412                 }
413         }
414
415         reg->nr    = head->nr;
416         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, cases_len + add);
417
418         reg->parts[0].region = head; head->parent = reg;
419         i = 1;
420         for (c = cases; c != NULL; c = n) {
421                 n = (ir_region*) c->link;
422                 if (c != exit) {
423                         reg->parts[i++].region = c;
424                         c->parent = reg;
425                 }
426                 c->link = NULL;
427         }
428
429         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
430         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
431         reg->succ[0] = exit;
432
433         DEBUG_ONLY({
434                 DB((dbg, LEVEL_2, " Created %s(%u)\n", reg->type == ir_rk_Switch ? "Switch" : "Case", reg->nr));
435                 for (i = 1; i < ARR_LEN(reg->parts); ++i) {
436                         DB((dbg, LEVEL_2, "  Case(%lu)\n", reg->parts[i].region->nr));
437                 }
438                 DB((dbg, LEVEL_2, "  Exit(%lu)\n", exit->nr));
439         })
440         return reg;
441 }  /* new_SwitchCase */
442
443 /**
444  * Create a new SelfLoop region.
445  */
446 static ir_region *new_SelfLoop(struct obstack *obst, ir_region *head)
447 {
448         ir_region *reg = alloc_region(obst, ir_rk_SelfLoop);
449         ir_region *succ;
450         size_t i, j, len;
451
452         reg->nr    = head->nr;
453         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 1);
454
455         reg->parts[0].region = head; head->parent = reg;
456
457         len = ARR_LEN(head->pred);
458         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
459         for (i = j = 0; i < len; ++i) {
460                 ir_region *pred = get_region_pred(head, i);
461                 if (pred != head)
462                         reg->pred[j++] = pred;
463         }
464         assert(j == len - 1);
465
466         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
467         assert(ARR_LEN(head->succ) == 2);
468
469         succ = get_region_succ(head, 0);
470         if (succ != head)
471                 reg->succ[0] = succ;
472         else
473                 reg->succ[0] = get_region_succ(head, 1);
474
475         DB((dbg, LEVEL_2, " Created SelfLoop(%lu)\n", reg->nr));
476
477         return reg;
478 }  /* new_SelfLoop */
479
480 /**
481  * Create a new RepeatLoop region.
482  */
483 static ir_region *new_RepeatLoop(struct obstack *obst, ir_region *head, ir_region *body)
484 {
485         ir_region *reg = alloc_region(obst, ir_rk_RepeatLoop);
486         ir_region *succ;
487
488         reg->nr    = head->nr;
489         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 2);
490
491         reg->parts[0].region = head; head->parent = reg;
492         reg->parts[1].region = body; body->parent = reg;
493
494         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
495         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
496         assert(ARR_LEN(body->succ) == 2);
497
498         succ = get_region_succ(body, 0);
499         if (succ != head)
500                 reg->succ[0] = succ;
501         else
502                 reg->succ[0] = get_region_succ(body, 1);
503
504         DB((dbg, LEVEL_2, " Created RepeatLoop(%lu)Body(%lu)\n", reg->nr, body->nr));
505
506         return reg;
507 }  /* new_RepeatLoop */
508
509 /**
510  * Create a new WhileLoop region.
511  */
512 static ir_region *new_WhileLoop(struct obstack *obst, ir_region *head)
513 {
514         ir_region *reg  = alloc_region(obst, ir_rk_WhileLoop);
515         ir_region *body = (ir_region*) head->link;
516         ir_region *succ;
517         size_t i, j, len;
518
519         head->link = NULL;
520
521         reg->nr    = head->nr;
522         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 2);
523
524         reg->parts[0].region = head; head->parent = reg;
525         reg->parts[1].region = body; body->parent = reg;
526
527         len = ARR_LEN(head->pred);
528         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
529         for (i = j = 0; i < len; ++i) {
530                 ir_region *pred = get_region_pred(head, i);
531                 if (pred != body)
532                         reg->pred[j++] = pred;
533         }
534         assert(j == len - 1);
535
536         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
537         assert(ARR_LEN(head->succ) == 2);
538
539         succ = get_region_succ(head, 0);
540         if (succ != body)
541                 reg->succ[0] = succ;
542         else
543                 reg->succ[0] = get_region_succ(head, 1);
544
545         DB((dbg, LEVEL_2, " Created WhileLoop(%lu)Body(%lu)\n", reg->nr, body->nr));
546
547         return reg;
548 }  /* new_WhileLoop */
549
550 /**
551  * Create a new new_NaturalLoop region.
552  */
553 static ir_region *new_NaturalLoop(struct obstack *obst, ir_region *head)
554 {
555         ir_region *reg = alloc_region(obst, ir_rk_WhileLoop);
556         ir_region *c, *n;
557         size_t i, j, k, len, n_pred, n_succ;
558
559         /* count number of parts */
560         for (len = 0, c = head; c != NULL; c = (ir_region*) c->link)
561                 ++len;
562
563         reg->nr    = head->nr;
564         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, len);
565
566         /* enter all parts */
567         for (i = 0, c = head; c != NULL; c = n) {
568                 reg->parts[i++].region = c;
569                 c->parent = reg;
570                 n = (ir_region*) c->link;
571                 c->link = NULL;
572         }
573
574         /* count number of preds */
575         n_pred = 0;
576         for (i = get_region_n_preds(head); i > 0;) {
577                 ir_region *pred = get_region_pred(head, --i);
578                 if (pred->parent != reg)
579                         ++n_pred;
580         }
581         reg->pred = NEW_ARR_D(ir_region *, obst, n_pred);
582         for (j = 0, i = get_region_n_preds(head); i > 0;) {
583                 ir_region *pred = get_region_pred(head, --i);
584                 if (pred->parent != reg)
585                         reg->pred[j++] = pred;
586         }
587
588         /* count number of succs */
589         n_succ = 0;
590         for (j = 0; j < len; ++j) {
591                 ir_region *pc = reg->parts[j].region;
592                 for (i = get_region_n_succs(pc); i > 0;) {
593                         ir_region *succ = get_region_succ(pc, --i);
594                         if (succ->parent != reg)
595                                 ++n_succ;
596                 }
597         }
598         reg->succ = NEW_ARR_D(ir_region *, obst, n_succ);
599         k = 0;
600         for (j = 0; j < len; ++j) {
601                 ir_region *pc = reg->parts[j].region;
602                 for (i = get_region_n_succs(pc); i > 0;) {
603                         ir_region *succ = get_region_succ(pc, --i);
604                         if (succ->parent != reg)
605                                 reg->succ[k++] = succ;
606                 }
607         }
608
609         DEBUG_ONLY(
610                 DB((dbg, LEVEL_2, " Created NaturalLoop(%u)Head(%u)\n", reg->nr, head->nr));
611                 for (i = 1; i < len; ++i) {
612                         ir_region *p = reg->parts[i].region;
613                         DB((dbg, LEVEL_2, "  Body(%u)\n", p->nr));
614                 }
615         )
616         return reg;
617 }  /* new_NaturalLoop */
618
619 /**
620  * Return true if region a is an ancestor of region b in DFS search.
621  */
622 static int is_ancestor(const ir_region *a, const ir_region *b)
623 {
624         return (a->prenum <= b->prenum && a->postnum > b->postnum);
625 }
626
627 /**
628  * Return true if region pred is a predecessor of region n.
629  */
630 static bool pred_of(const ir_region *pred, const ir_region *n)
631 {
632         size_t i, n_preds;
633         for (i = 0, n_preds = get_region_n_preds(n); i < n_preds; ++i) {
634                 if (get_region_pred(n, i) == pred)
635                         return true;
636         }
637         return false;
638 }
639
640 /**
641  * Return true if region succ is a successor of region n.
642  */
643 static bool succ_of(const ir_region *succ, const ir_region *n)
644 {
645         size_t i, n_succs;
646         for (i = 0, n_succs = get_region_n_succs(n); i < n_succs; ++i) {
647                 if (get_region_succ(n, i) == succ)
648                         return true;
649         }
650         return false;
651 }
652
653 /**
654  * Reverse a linked list of regions.
655  */
656 static struct ir_region *reverse_list(ir_region *n)
657 {
658         ir_region *prev = NULL, *next;
659
660         for (; n; n = next) {
661                 next = (ir_region*) n->link;
662                 n->link = prev;
663                 prev = n;
664         }
665         return prev;
666 }
667
668 /**
669  * Find the cyclic region in the subgraph entered by node.
670  */
671 static ir_region *find_cyclic_region(ir_region *node)
672 {
673         size_t i;
674         ir_region *last = node;
675         int improper = 0;
676
677         for (i = get_region_n_preds(node); i > 0;) {
678                 ir_region *pred = get_region_pred(node, --i);
679
680                 /* search backedges */
681                 if (!pred->link && pred != last && is_ancestor(node, pred)) {
682                         ir_region *rem = last;
683                         size_t j;
684
685                         last->link = pred;
686                         last       = pred;
687                         for (j = get_region_n_preds(pred); j > 0;) {
688                                 ir_region *p = get_region_pred(pred, --j);
689
690                                 /* Search regions we didn't visited yet and
691                                    link them into the list. */
692                                 if (!p->link && p != last) {
693                                         if (is_ancestor(node, p)) {
694                                                 last->link = p;
695                                                 last       = p;
696                                         } else {
697                                                 improper = 1;
698                                         }
699                                 }
700                         }
701                         /* reverse the list. */
702                         last = (ir_region*) rem->link;
703                         rem->link = reverse_list(last);
704                 }
705         }
706
707         if (node->link && improper) {
708                 /* found an improper region, do minimization */
709
710         }
711         return node;
712 }
713
714 /**
715  * Detect a cyclic region.
716  */
717 static ir_region *cyclic_region_type(struct obstack *obst, ir_region *node)
718 {
719         ir_region *list, *next;
720
721         /* simple cases first */
722         if (succ_of(node, node)) {
723                 return new_SelfLoop(obst, node);
724         }
725         if (get_region_n_succs(node) == 1) {
726                 ir_region *succ = get_region_succ(node, 0);
727                 if (get_region_n_preds(succ) == 1 && succ_of(node, succ)) {
728                         return new_RepeatLoop(obst, node, succ);
729                 }
730         }
731         list = find_cyclic_region(node);
732
733         next = (ir_region*) list->link;
734         if (next) {
735                 if (!next->link && get_region_n_succs(next) == 1) {
736                         /* only one body block with only one successor (the head) */
737                         return new_WhileLoop(obst, list);
738                 }
739                 /* A Loop with one head */
740                 return new_NaturalLoop(obst, list);
741         }
742
743         return NULL;
744 }
745
746 /**
747  * Clear all links on a list. Needed, because we expect cleared links.
748  */
749 static void clear_list(ir_region *list)
750 {
751         ir_region *next;
752
753         for (next = list; next; list = next) {
754                 next = (ir_region*) list->link;
755                 list->link = NULL;
756         }
757 }
758
759 #define ADD_LIST(list, n) do { n->link = list; list = n; ++list##_len; } while (0)
760
761 /**
762  * Detect an acyclic region.
763  */
764 static ir_region *acyclic_region_type(struct obstack *obst, ir_region *node)
765 {
766         ir_region *n, *m;
767         bool p, s;
768         size_t k;
769         ir_region *nset = NULL;
770         size_t nset_len = 0;
771         ir_region *res;
772
773         /* check for a block containing node */
774         n = node;
775         p = get_region_n_preds(n) == 1;
776         s = true;
777         while (p & s) {
778                 n = get_region_pred(n, 0);
779                 p = get_region_n_preds(n) == 1;
780                 s = get_region_n_succs(n) == 1;
781         }
782         p = true;
783         s = get_region_n_succs(n) == 1;
784         while (p & s) {
785                 ADD_LIST(nset, n);
786                 n = get_region_succ(n, 0);
787                 p = get_region_n_preds(n) == 1;
788                 s = get_region_n_succs(n) == 1;
789         }
790         if (p) {
791                 ADD_LIST(nset, n);
792         }
793         if (nset_len > 1) {
794                 /* node --> .. --> .. */
795                 res = new_Sequence(obst, nset, nset_len);
796                 return res;
797         }
798         node = n;
799
800         /* check for IfThenElse */
801         k = get_region_n_succs(node);
802         if (k == 2) {
803                 size_t n_succs, m_succs, n_preds, m_preds;
804
805                 n = get_region_succ(node, 0);
806                 m = get_region_succ(node, 1);
807
808                 n_succs = get_region_n_succs(n);
809                 m_succs = get_region_n_succs(m);
810                 n_preds = get_region_n_preds(n);
811                 m_preds = get_region_n_preds(m);
812                 if (n_succs == 1 && n_succs == m_succs && n_preds == m_preds &&
813                     get_region_succ(n, 0) == get_region_succ(m, 0)) {
814                         /*
815                          *    /-->n---\
816                          * node      ...
817                          *    \-->m---/
818                          */
819                         return new_IfThenElse(obst, node, n, m);
820                 }
821                 if (n_succs == 1 &&
822                     get_region_succ(n, 0) == m &&
823                     pred_of(node, m)) {
824                         /*
825                          * node -->n-->m
826                          *    \-------/
827                          */
828                         return new_IfThen(obst, node, n);
829                 }
830                 if (m_succs == 1 &&
831                     get_region_succ(m, 0) == m &&
832                     pred_of(node, n)) {
833                         /*
834                          * node -->m-->n
835                          *    \-------/
836                          */
837                         return new_IfThen(obst, node, m);
838                 }
839         }
840         /* check for Switch, case */
841         if (k > 0) {
842                 ir_region *rexit = NULL;
843                 size_t i, pos = 0;
844                 nset = NULL; nset_len = 0;
845                 for (i = k; i > 0;) {
846                         n = get_region_succ(node, i--);
847                         ADD_LIST(nset, n);
848                         if (get_region_n_succs(n) != 1) {
849                                 /* must be the exit */
850                                 rexit = n;
851                                 ++pos;
852                                 if (pos > 1)
853                                         break;
854                         }
855                 }
856                 if (pos <= 1) {
857                         ir_region_kind kind = ir_rk_Case;
858                         ir_region *pos_exit_1 = NULL;
859                         ir_region *pos_exit_2 = NULL;
860
861                         /* find the exit */
862                         for (m = nset; m != NULL; m = (ir_region*) m->link) {
863                                 if (get_region_n_succs(m) != 1) {
864                                         /* must be the exit block */
865                                         if (rexit == NULL) {
866                                                 rexit = m;
867                                         } else if (rexit != m) {
868                                                 /* two exits */
869                                                 rexit = NULL;
870                                                 break;
871                                         }
872                                 } else {
873                                         ir_region *succ = get_region_succ(m, 0);
874
875                                         if (succ->link == NULL) {
876                                                 if (rexit == NULL) {
877                                                         if (succ == pos_exit_1)
878                                                                 rexit = succ;
879                                                         else if (succ == pos_exit_2)
880                                                                 rexit = succ;
881                                                         else if (pos_exit_1 == NULL)
882                                                                 pos_exit_1 = succ;
883                                                         else if (pos_exit_2 == NULL)
884                                                                 pos_exit_2 = succ;
885                                                         else {
886                                                                 /* more than two possible exits */
887                                                                 break;
888                                                         }
889                                                 } else if (rexit != succ) {
890                                                         /* two exits */
891                                                         rexit = NULL;
892                                                         break;
893                                                 }
894                                         }
895                                 }
896                         }
897                         if (rexit != NULL) {
898                                 /* do the checks */
899                                 for (n = nset; n != NULL; n = (ir_region*) n->link) {
900                                         ir_region *succ;
901                                         if (n == rexit) {
902                                                 /* good, default fall through */
903                                                 continue;
904                                         }
905                                         succ = get_region_succ(n, 0);
906                                         if (succ == rexit) {
907                                                 /* good, switch to exit */
908                                                 continue;
909                                         }
910                                         if (succ->link == NULL) {
911                                                 /* another exit */
912                                                 break;
913                                         } else {
914                                                 /* a fall through */
915                                                 kind = ir_rk_Switch;
916                                         }
917                                 }
918
919                                 if (n == NULL) {
920                                         /* detected */
921                                         return new_SwitchCase(obst, kind, node, rexit, nset, nset_len);
922                                 }
923                         }
924                 }
925                 clear_list(nset);
926         }
927         return NULL;
928 }
929
930 /**
931  * replace all pred edges from region pred that points to any of the set set
932  * to ONE edge to reg.
933  */
934 static void replace_pred(ir_region *succ, ir_region *reg)
935 {
936         int    have_one = 0;
937         size_t len      = get_region_n_preds(succ);
938         size_t i;
939
940         for (i = 0; i < len; ++i) {
941                 ir_region *pred = get_region_pred(succ, i);
942
943                 if (pred->parent == reg) {
944                         ir_region *r;
945
946                         if (have_one) {
947                                 /* kill it */
948                                 r = get_region_pred(succ, --len);
949                         } else {
950                                 /* replace it */
951                                 have_one = 1;
952                                 r = reg;
953                         }
954                         set_region_pred(succ, i, r);
955                 } else {
956                         /* the current region can be entered by this node */
957                         pred->enter = 1;
958                 }
959         }
960         ARR_SHRINKLEN(succ->pred, len);
961 }
962
963 /**
964  * replace all succ edges from region pred that points to any of the set set
965  * to ONE edge to reg.
966  */
967 static void replace_succ(ir_region *pred, ir_region *reg)
968 {
969         int    have_one = 0;
970         size_t len      = get_region_n_succs(pred);
971         size_t i;
972
973         for (i = 0; i < len; ++i) {
974                 ir_region *succ = get_region_succ(pred, i);
975
976                 if (succ->parent == reg) {
977                         ir_region *r;
978
979                         if (have_one) {
980                                 /* kill it */
981                                 r = get_region_succ(pred, --len);
982                         } else {
983                                 /* replace it */
984                                 have_one = 1;
985                                 r = reg;
986                         }
987                         set_region_succ(pred, i, r);
988                 } else {
989                         /* current region can be left by this node */
990                         succ->exit = 1;
991                 }
992         }
993         ARR_SHRINKLEN(pred->succ, len);
994 }
995
996 /**
997  * Reduce the graph by the node reg.
998  */
999 static void reduce(walk_env *env, ir_region *reg)
1000 {
1001         size_t i;
1002         ir_region *head = reg->parts[0].region;
1003         size_t maxorder = head->postnum;
1004         size_t minorder = head->prenum;
1005
1006         /* second step: replace all preds in successors */
1007         for (i = get_region_n_succs(reg); i > 0;) {
1008                 ir_region *succ = get_region_succ(reg, --i);
1009
1010                 replace_pred(succ, reg);
1011         }
1012
1013         /* third step: replace all succs in predessors */
1014         for (i = get_region_n_preds(reg); i > 0;) {
1015                 ir_region *pred = get_region_pred(reg, --i);
1016
1017                 replace_succ(pred, reg);
1018         }
1019
1020         reg->prenum  = minorder;
1021         reg->postnum = maxorder;
1022         env->post[maxorder] = reg;
1023 }
1024
1025 /**
1026  * Construct the region tree of a graph by doing
1027  * structural analysis.
1028  *
1029  * Uses link fields of nodes.
1030  *
1031  * @param irg  the graph
1032  */
1033 ir_reg_tree *construct_region_tree(ir_graph *irg)
1034 {
1035         walk_env env;
1036         ir_graph *rem = current_ir_graph;
1037         ir_reg_tree *res = XMALLOC(ir_reg_tree);
1038
1039         obstack_init(&res->obst);
1040
1041         current_ir_graph = irg;
1042
1043         FIRM_DBG_REGISTER(dbg, "firm.ana.structure");
1044         firm_dbg_set_mask(dbg, SET_LEVEL_5);
1045
1046         DB((dbg, LEVEL_1, "Structural analysis on %+F started ...\n", irg));
1047
1048         /* we need dominance info */
1049         assure_doms(irg);
1050         /* and out edges */
1051         assure_irg_outs(irg);
1052
1053         env.start_block = get_irg_start_block(irg);
1054         env.end_block   = get_irg_end_block(irg);
1055
1056         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1057
1058         /* create the Block wrapper and count them */
1059         env.l_post = 0;
1060         env.obst   = &res->obst;
1061         irg_block_walk_graph(irg, NULL, wrap_BasicBlocks, &env);
1062         irg_block_walk_graph(irg, NULL, update_BasicBlock_regions, &env);
1063
1064         env.post = NEW_ARR_F(ir_region *, env.l_post);
1065
1066         /* do the DFS walk */
1067         dfs_walk(irg, &env);
1068
1069         DB((dbg, LEVEL_1, "%zu regions left\n", env.postmax));
1070         if (env.postmax > 1) {
1071                 size_t postctr = 0;
1072                 do {
1073                         ir_region *reg, *n = env.post[postctr];
1074                         do {
1075                                 if (n->parent != NULL) {
1076                                         /* already folded */
1077                                         break;
1078                                 }
1079                                 /* locate an acyclic region if present */
1080                                 reg = acyclic_region_type(env.obst, n);
1081                                 if (reg == NULL) {
1082                                         /* locate a cyclic region */
1083                                         reg = cyclic_region_type(env.obst, n);
1084                                 }
1085                                 if (reg != NULL) {
1086                                         /* found a new region */
1087                                         reduce(&env, reg);
1088                                         n = reg;
1089                                 }
1090                         } while (reg != NULL);
1091                         ++postctr;
1092                 } while (postctr < env.postmax);
1093         }
1094         DB((dbg, LEVEL_1, "Structural analysis finished.\n"));
1095
1096         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1097
1098         DEL_ARR_F(env.post);
1099         current_ir_graph = rem;
1100
1101         res->top = env.post[0];
1102         res->irg = irg;
1103         return res;
1104 }
1105
1106 /**
1107  * Walk over the region tree.
1108  *
1109  * @param reg   a region node
1110  * @param pre   walker function, executed before the children of a tree node are visited
1111  * @param post  walker function, executed after the children of a tree node are visited
1112  * @param env   environment, passed to pre and post
1113  */
1114 static void region_tree_walk2(ir_region *reg, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1115 {
1116         size_t i, n;
1117
1118         if (pre)
1119                 pre(reg, env);
1120         if (reg->type != ir_rk_BasicBlock) {
1121                 for (i = 0, n = ARR_LEN(reg->parts); i < n; ++i)
1122                         region_tree_walk2(reg->parts[i].region, pre, post, env);
1123         }
1124         if (post)
1125                 post(reg, env);
1126 }
1127
1128 /**
1129  * Walk over the region tree.
1130  *
1131  * @param tree  the tree
1132  * @param pre   walker function, executed before the children of a tree node are visited
1133  * @param post  walker function, executed after the children of a tree node are visited
1134  * @param env   environment, passed to pre and post
1135  */
1136 void region_tree_walk(ir_reg_tree *tree, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1137 {
1138         region_tree_walk2(tree->top, pre, post, env);
1139 }