OSDN Git Service

* pa-host.c (MAP_FAILED): Define if not defined.
[pf3gnuchains/gcc-fork.git] / gcc / cfgloop.c
1 /* Natural loop discovery code for GNU compiler.
2    Copyright (C) 2000, 2001, 2003, 2004 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "hard-reg-set.h"
27 #include "obstack.h"
28 #include "basic-block.h"
29 #include "toplev.h"
30 #include "cfgloop.h"
31 #include "flags.h"
32 #include "tree.h"
33 #include "tree-flow.h"
34
35 /* Ratio of frequencies of edges so that one of more latch edges is
36    considered to belong to inner loop with same header.  */
37 #define HEAVY_EDGE_RATIO 8
38
39 #define HEADER_BLOCK(B) (* (int *) (B)->aux)
40 #define LATCH_EDGE(E) (*(int *) (E)->aux)
41
42 static void flow_loops_cfg_dump (const struct loops *, FILE *);
43 static void flow_loop_entry_edges_find (struct loop *);
44 static void flow_loop_exit_edges_find (struct loop *);
45 static int flow_loop_nodes_find (basic_block, struct loop *);
46 static void flow_loop_pre_header_scan (struct loop *);
47 static basic_block flow_loop_pre_header_find (basic_block);
48 static int flow_loop_level_compute (struct loop *);
49 static int flow_loops_level_compute (struct loops *);
50 static void establish_preds (struct loop *);
51 static void canonicalize_loop_headers (void);
52 static bool glb_enum_p (basic_block, void *);
53 \f
54 /* Dump loop related CFG information.  */
55
56 static void
57 flow_loops_cfg_dump (const struct loops *loops, FILE *file)
58 {
59   int i;
60   basic_block bb;
61
62   if (! loops->num || ! file)
63     return;
64
65   FOR_EACH_BB (bb)
66     {
67       edge succ;
68       edge_iterator ei;
69
70       fprintf (file, ";; %d succs { ", bb->index);
71       FOR_EACH_EDGE (succ, ei, bb->succs)
72         fprintf (file, "%d ", succ->dest->index);
73       fprintf (file, "}\n");
74     }
75
76   /* Dump the DFS node order.  */
77   if (loops->cfg.dfs_order)
78     {
79       fputs (";; DFS order: ", file);
80       for (i = 0; i < n_basic_blocks; i++)
81         fprintf (file, "%d ", loops->cfg.dfs_order[i]);
82
83       fputs ("\n", file);
84     }
85
86   /* Dump the reverse completion node order.  */
87   if (loops->cfg.rc_order)
88     {
89       fputs (";; RC order: ", file);
90       for (i = 0; i < n_basic_blocks; i++)
91         fprintf (file, "%d ", loops->cfg.rc_order[i]);
92
93       fputs ("\n", file);
94     }
95 }
96
97 /* Return nonzero if the nodes of LOOP are a subset of OUTER.  */
98
99 bool
100 flow_loop_nested_p (const struct loop *outer, const struct loop *loop)
101 {
102   return (loop->depth > outer->depth
103          && loop->pred[outer->depth] == outer);
104 }
105
106 /* Returns the loop such that LOOP is nested DEPTH (indexed from zero)
107    loops within LOOP.  */
108
109 struct loop *
110 superloop_at_depth (struct loop *loop, unsigned depth)
111 {
112   gcc_assert (depth <= (unsigned) loop->depth);
113
114   if (depth == (unsigned) loop->depth)
115     return loop;
116
117   return loop->pred[depth];
118 }
119
120 /* Dump the loop information specified by LOOP to the stream FILE
121    using auxiliary dump callback function LOOP_DUMP_AUX if non null.  */
122
123 void
124 flow_loop_dump (const struct loop *loop, FILE *file,
125                 void (*loop_dump_aux) (const struct loop *, FILE *, int),
126                 int verbose)
127 {
128   basic_block *bbs;
129   unsigned i;
130
131   if (! loop || ! loop->header)
132     return;
133
134   fprintf (file, ";;\n;; Loop %d:%s\n", loop->num,
135              loop->invalid ? " invalid" : "");
136
137   fprintf (file, ";;  header %d, latch %d, pre-header %d\n",
138            loop->header->index, loop->latch->index,
139            loop->pre_header ? loop->pre_header->index : -1);
140   fprintf (file, ";;  depth %d, level %d, outer %ld\n",
141            loop->depth, loop->level,
142            (long) (loop->outer ? loop->outer->num : -1));
143
144   if (loop->pre_header_edges)
145     flow_edge_list_print (";;  pre-header edges", loop->pre_header_edges,
146                           loop->num_pre_header_edges, file);
147
148   flow_edge_list_print (";;  entry edges", loop->entry_edges,
149                         loop->num_entries, file);
150   fprintf (file, ";;  nodes:");
151   bbs = get_loop_body (loop);
152   for (i = 0; i < loop->num_nodes; i++)
153     fprintf (file, " %d", bbs[i]->index);
154   free (bbs);
155   fprintf (file, "\n");
156   flow_edge_list_print (";;  exit edges", loop->exit_edges,
157                         loop->num_exits, file);
158
159   if (loop_dump_aux)
160     loop_dump_aux (loop, file, verbose);
161 }
162
163 /* Dump the loop information specified by LOOPS to the stream FILE,
164    using auxiliary dump callback function LOOP_DUMP_AUX if non null.  */
165
166 void
167 flow_loops_dump (const struct loops *loops, FILE *file, void (*loop_dump_aux) (const struct loop *, FILE *, int), int verbose)
168 {
169   int i;
170   int num_loops;
171
172   num_loops = loops->num;
173   if (! num_loops || ! file)
174     return;
175
176   fprintf (file, ";; %d loops found, %d levels\n",
177            num_loops, loops->levels);
178
179   for (i = 0; i < num_loops; i++)
180     {
181       struct loop *loop = loops->parray[i];
182
183       if (!loop)
184         continue;
185
186       flow_loop_dump (loop, file, loop_dump_aux, verbose);
187     }
188
189   if (verbose)
190     flow_loops_cfg_dump (loops, file);
191 }
192
193 /* Free data allocated for LOOP.  */
194 void
195 flow_loop_free (struct loop *loop)
196 {
197   if (loop->pre_header_edges)
198     free (loop->pre_header_edges);
199   if (loop->entry_edges)
200     free (loop->entry_edges);
201   if (loop->exit_edges)
202     free (loop->exit_edges);
203   if (loop->pred)
204     free (loop->pred);
205   free (loop);
206 }
207
208 /* Free all the memory allocated for LOOPS.  */
209
210 void
211 flow_loops_free (struct loops *loops)
212 {
213   if (loops->parray)
214     {
215       unsigned i;
216
217       gcc_assert (loops->num);
218
219       /* Free the loop descriptors.  */
220       for (i = 0; i < loops->num; i++)
221         {
222           struct loop *loop = loops->parray[i];
223
224           if (!loop)
225             continue;
226
227           flow_loop_free (loop);
228         }
229
230       free (loops->parray);
231       loops->parray = NULL;
232
233       if (loops->cfg.dfs_order)
234         free (loops->cfg.dfs_order);
235       if (loops->cfg.rc_order)
236         free (loops->cfg.rc_order);
237
238     }
239 }
240
241 /* Find the entry edges into the LOOP.  */
242
243 static void
244 flow_loop_entry_edges_find (struct loop *loop)
245 {
246   edge e;
247   edge_iterator ei;
248   int num_entries;
249
250   num_entries = 0;
251   FOR_EACH_EDGE (e, ei, loop->header->preds)
252     {
253       if (flow_loop_outside_edge_p (loop, e))
254         num_entries++;
255     }
256
257   gcc_assert (num_entries);
258
259   loop->entry_edges = xmalloc (num_entries * sizeof (edge *));
260
261   num_entries = 0;
262   FOR_EACH_EDGE (e, ei, loop->header->preds)
263     {
264       if (flow_loop_outside_edge_p (loop, e))
265         loop->entry_edges[num_entries++] = e;
266     }
267
268   loop->num_entries = num_entries;
269 }
270
271 /* Find the exit edges from the LOOP.  */
272
273 static void
274 flow_loop_exit_edges_find (struct loop *loop)
275 {
276   edge e;
277   basic_block node, *bbs;
278   unsigned num_exits, i;
279
280   loop->exit_edges = NULL;
281   loop->num_exits = 0;
282
283   /* Check all nodes within the loop to see if there are any
284      successors not in the loop.  Note that a node may have multiple
285      exiting edges.  */
286   num_exits = 0;
287   bbs = get_loop_body (loop);
288   for (i = 0; i < loop->num_nodes; i++)
289     {
290       edge_iterator ei;
291       node = bbs[i];
292       FOR_EACH_EDGE (e, ei, node->succs)
293         {
294           basic_block dest = e->dest;
295
296           if (!flow_bb_inside_loop_p (loop, dest))
297             num_exits++;
298         }
299     }
300
301   if (! num_exits)
302     {
303       free (bbs);
304       return;
305     }
306
307   loop->exit_edges = xmalloc (num_exits * sizeof (edge *));
308
309   /* Store all exiting edges into an array.  */
310   num_exits = 0;
311   for (i = 0; i < loop->num_nodes; i++)
312     {
313       edge_iterator ei;
314       node = bbs[i];
315       FOR_EACH_EDGE (e, ei, node->succs)
316         {
317           basic_block dest = e->dest;
318
319           if (!flow_bb_inside_loop_p (loop, dest))
320             {
321               e->flags |= EDGE_LOOP_EXIT;
322               loop->exit_edges[num_exits++] = e;
323             }
324       }
325     }
326   free (bbs);
327   loop->num_exits = num_exits;
328 }
329
330 /* Find the nodes contained within the LOOP with header HEADER.
331    Return the number of nodes within the loop.  */
332
333 static int
334 flow_loop_nodes_find (basic_block header, struct loop *loop)
335 {
336   basic_block *stack;
337   int sp;
338   int num_nodes = 1;
339
340   header->loop_father = loop;
341   header->loop_depth = loop->depth;
342
343   if (loop->latch->loop_father != loop)
344     {
345       stack = xmalloc (n_basic_blocks * sizeof (basic_block));
346       sp = 0;
347       num_nodes++;
348       stack[sp++] = loop->latch;
349       loop->latch->loop_father = loop;
350       loop->latch->loop_depth = loop->depth;
351
352       while (sp)
353         {
354           basic_block node;
355           edge e;
356           edge_iterator ei;
357
358           node = stack[--sp];
359
360           FOR_EACH_EDGE (e, ei, node->preds)
361             {
362               basic_block ancestor = e->src;
363
364               if (ancestor != ENTRY_BLOCK_PTR
365                   && ancestor->loop_father != loop)
366                 {
367                   ancestor->loop_father = loop;
368                   ancestor->loop_depth = loop->depth;
369                   num_nodes++;
370                   stack[sp++] = ancestor;
371                 }
372             }
373         }
374       free (stack);
375     }
376   return num_nodes;
377 }
378
379 /* For each loop in the lOOPS tree that has just a single exit
380    record the exit edge.  */
381
382 void
383 mark_single_exit_loops (struct loops *loops)
384 {
385   basic_block bb;
386   edge e;
387   struct loop *loop;
388   unsigned i;
389
390   for (i = 1; i < loops->num; i++)
391     {
392       loop = loops->parray[i];
393       if (loop)
394         loop->single_exit = NULL;
395     }
396
397   FOR_EACH_BB (bb)
398     {
399       edge_iterator ei;
400       if (bb->loop_father == loops->tree_root)
401         continue;
402       FOR_EACH_EDGE (e, ei, bb->succs)
403         {
404           if (e->dest == EXIT_BLOCK_PTR)
405             continue;
406
407           if (flow_bb_inside_loop_p (bb->loop_father, e->dest))
408             continue;
409
410           for (loop = bb->loop_father;
411                loop != e->dest->loop_father;
412                loop = loop->outer)
413             {
414               /* If we have already seen an exit, mark this by the edge that
415                  surely does not occur as any exit.  */
416               if (loop->single_exit)
417                 loop->single_exit = EDGE_SUCC (ENTRY_BLOCK_PTR, 0);
418               else
419                 loop->single_exit = e;
420             }
421         }
422     }
423
424   for (i = 1; i < loops->num; i++)
425     {
426       loop = loops->parray[i];
427       if (!loop)
428         continue;
429
430       if (loop->single_exit == EDGE_SUCC (ENTRY_BLOCK_PTR, 0))
431         loop->single_exit = NULL;
432     }
433
434   loops->state |= LOOPS_HAVE_MARKED_SINGLE_EXITS;
435 }
436
437 /* Find the root node of the loop pre-header extended basic block and
438    the edges along the trace from the root node to the loop header.  */
439
440 static void
441 flow_loop_pre_header_scan (struct loop *loop)
442 {
443   int num;
444   basic_block ebb;
445   edge e;
446
447   loop->num_pre_header_edges = 0;
448   if (loop->num_entries != 1)
449     return;
450
451   ebb = loop->entry_edges[0]->src;
452   if (ebb == ENTRY_BLOCK_PTR)
453     return;
454
455   /* Count number of edges along trace from loop header to
456      root of pre-header extended basic block.  Usually this is
457      only one or two edges.  */
458   for (num = 1;
459        EDGE_PRED (ebb, 0)->src != ENTRY_BLOCK_PTR && EDGE_COUNT (ebb->preds) == 1;
460        num++)
461     ebb = EDGE_PRED (ebb, 0)->src;
462
463   loop->pre_header_edges = xmalloc (num * sizeof (edge));
464   loop->num_pre_header_edges = num;
465
466   /* Store edges in order that they are followed.  The source of the first edge
467      is the root node of the pre-header extended basic block and the
468      destination of the last last edge is the loop header.  */
469   for (e = loop->entry_edges[0]; num; e = EDGE_PRED (e->src, 0))
470     loop->pre_header_edges[--num] = e;
471 }
472
473 /* Return the block for the pre-header of the loop with header
474    HEADER.  Return NULL if there is no pre-header.  */
475
476 static basic_block
477 flow_loop_pre_header_find (basic_block header)
478 {
479   basic_block pre_header;
480   edge e;
481   edge_iterator ei;
482
483   /* If block p is a predecessor of the header and is the only block
484      that the header does not dominate, then it is the pre-header.  */
485   pre_header = NULL;
486   FOR_EACH_EDGE (e, ei, header->preds)
487     {
488       basic_block node = e->src;
489
490       if (node != ENTRY_BLOCK_PTR
491           && ! dominated_by_p (CDI_DOMINATORS, node, header))
492         {
493           if (pre_header == NULL)
494             pre_header = node;
495           else
496             {
497               /* There are multiple edges into the header from outside
498                  the loop so there is no pre-header block.  */
499               pre_header = NULL;
500               break;
501             }
502         }
503     }
504
505   return pre_header;
506 }
507
508 static void
509 establish_preds (struct loop *loop)
510 {
511   struct loop *ploop, *father = loop->outer;
512
513   loop->depth = father->depth + 1;
514   if (loop->pred)
515     free (loop->pred);
516   loop->pred = xmalloc (sizeof (struct loop *) * loop->depth);
517   memcpy (loop->pred, father->pred, sizeof (struct loop *) * father->depth);
518   loop->pred[father->depth] = father;
519
520   for (ploop = loop->inner; ploop; ploop = ploop->next)
521     establish_preds (ploop);
522 }
523
524 /* Add LOOP to the loop hierarchy tree where FATHER is father of the
525    added loop.  If LOOP has some children, take care of that their
526    pred field will be initialized correctly.  */
527
528 void
529 flow_loop_tree_node_add (struct loop *father, struct loop *loop)
530 {
531   loop->next = father->inner;
532   father->inner = loop;
533   loop->outer = father;
534
535   establish_preds (loop);
536 }
537
538 /* Remove LOOP from the loop hierarchy tree.  */
539
540 void
541 flow_loop_tree_node_remove (struct loop *loop)
542 {
543   struct loop *prev, *father;
544
545   father = loop->outer;
546   loop->outer = NULL;
547
548   /* Remove loop from the list of sons.  */
549   if (father->inner == loop)
550     father->inner = loop->next;
551   else
552     {
553       for (prev = father->inner; prev->next != loop; prev = prev->next);
554       prev->next = loop->next;
555     }
556
557   loop->depth = -1;
558   free (loop->pred);
559   loop->pred = NULL;
560 }
561
562 /* Helper function to compute loop nesting depth and enclosed loop level
563    for the natural loop specified by LOOP.  Returns the loop level.  */
564
565 static int
566 flow_loop_level_compute (struct loop *loop)
567 {
568   struct loop *inner;
569   int level = 1;
570
571   if (! loop)
572     return 0;
573
574   /* Traverse loop tree assigning depth and computing level as the
575      maximum level of all the inner loops of this loop.  The loop
576      level is equivalent to the height of the loop in the loop tree
577      and corresponds to the number of enclosed loop levels (including
578      itself).  */
579   for (inner = loop->inner; inner; inner = inner->next)
580     {
581       int ilevel = flow_loop_level_compute (inner) + 1;
582
583       if (ilevel > level)
584         level = ilevel;
585     }
586
587   loop->level = level;
588   return level;
589 }
590
591 /* Compute the loop nesting depth and enclosed loop level for the loop
592    hierarchy tree specified by LOOPS.  Return the maximum enclosed loop
593    level.  */
594
595 static int
596 flow_loops_level_compute (struct loops *loops)
597 {
598   return flow_loop_level_compute (loops->tree_root);
599 }
600
601 /* Scan a single natural loop specified by LOOP collecting information
602    about it specified by FLAGS.  */
603
604 int
605 flow_loop_scan (struct loop *loop, int flags)
606 {
607   if (flags & LOOP_ENTRY_EDGES)
608     {
609       /* Find edges which enter the loop header.
610          Note that the entry edges should only
611          enter the header of a natural loop.  */
612       flow_loop_entry_edges_find (loop);
613     }
614
615   if (flags & LOOP_EXIT_EDGES)
616     {
617       /* Find edges which exit the loop.  */
618       flow_loop_exit_edges_find (loop);
619     }
620
621   if (flags & LOOP_PRE_HEADER)
622     {
623       /* Look to see if the loop has a pre-header node.  */
624       loop->pre_header = flow_loop_pre_header_find (loop->header);
625
626       /* Find the blocks within the extended basic block of
627          the loop pre-header.  */
628       flow_loop_pre_header_scan (loop);
629     }
630
631   return 1;
632 }
633
634 /* A callback to update latch and header info for basic block JUMP created
635    by redirecting an edge.  */
636
637 static void
638 update_latch_info (basic_block jump)
639 {
640   alloc_aux_for_block (jump, sizeof (int));
641   HEADER_BLOCK (jump) = 0;
642   alloc_aux_for_edge (EDGE_PRED (jump, 0), sizeof (int));
643   LATCH_EDGE (EDGE_PRED (jump, 0)) = 0;
644   set_immediate_dominator (CDI_DOMINATORS, jump, EDGE_PRED (jump, 0)->src);
645 }
646
647 /* A callback for make_forwarder block, to redirect all edges except for
648    MFB_KJ_EDGE to the entry part.  E is the edge for that we should decide
649    whether to redirect it.  */
650
651 static edge mfb_kj_edge;
652 static bool
653 mfb_keep_just (edge e)
654 {
655   return e != mfb_kj_edge;
656 }
657
658 /* A callback for make_forwarder block, to redirect the latch edges into an
659    entry part.  E is the edge for that we should decide whether to redirect
660    it.  */
661
662 static bool
663 mfb_keep_nonlatch (edge e)
664 {
665   return LATCH_EDGE (e);
666 }
667
668 /* Takes care of merging natural loops with shared headers.  */
669
670 static void
671 canonicalize_loop_headers (void)
672 {
673   basic_block header;
674   edge e;
675
676   alloc_aux_for_blocks (sizeof (int));
677   alloc_aux_for_edges (sizeof (int));
678
679   /* Split blocks so that each loop has only single latch.  */
680   FOR_EACH_BB (header)
681     {
682       edge_iterator ei;
683       int num_latches = 0;
684       int have_abnormal_edge = 0;
685
686       FOR_EACH_EDGE (e, ei, header->preds)
687         {
688           basic_block latch = e->src;
689
690           if (e->flags & EDGE_ABNORMAL)
691             have_abnormal_edge = 1;
692
693           if (latch != ENTRY_BLOCK_PTR
694               && dominated_by_p (CDI_DOMINATORS, latch, header))
695             {
696               num_latches++;
697               LATCH_EDGE (e) = 1;
698             }
699         }
700       if (have_abnormal_edge)
701         HEADER_BLOCK (header) = 0;
702       else
703         HEADER_BLOCK (header) = num_latches;
704     }
705
706   if (HEADER_BLOCK (EDGE_SUCC (ENTRY_BLOCK_PTR, 0)->dest))
707     {
708       basic_block bb;
709
710       /* We could not redirect edges freely here. On the other hand,
711          we can simply split the edge from entry block.  */
712       bb = split_edge (EDGE_SUCC (ENTRY_BLOCK_PTR, 0));
713
714       alloc_aux_for_edge (EDGE_SUCC (bb, 0), sizeof (int));
715       LATCH_EDGE (EDGE_SUCC (bb, 0)) = 0;
716       alloc_aux_for_block (bb, sizeof (int));
717       HEADER_BLOCK (bb) = 0;
718     }
719
720   FOR_EACH_BB (header)
721     {
722       int max_freq, is_heavy;
723       edge heavy, tmp_edge;
724       edge_iterator ei;
725
726       if (HEADER_BLOCK (header) <= 1)
727         continue;
728
729       /* Find a heavy edge.  */
730       is_heavy = 1;
731       heavy = NULL;
732       max_freq = 0;
733       FOR_EACH_EDGE (e, ei, header->preds)
734         if (LATCH_EDGE (e) &&
735             EDGE_FREQUENCY (e) > max_freq)
736           max_freq = EDGE_FREQUENCY (e);
737       FOR_EACH_EDGE (e, ei, header->preds)
738         if (LATCH_EDGE (e) &&
739             EDGE_FREQUENCY (e) >= max_freq / HEAVY_EDGE_RATIO)
740           {
741             if (heavy)
742               {
743                 is_heavy = 0;
744                 break;
745               }
746             else
747               heavy = e;
748           }
749
750       if (is_heavy)
751         {
752           /* Split out the heavy edge, and create inner loop for it.  */
753           mfb_kj_edge = heavy;
754           tmp_edge = make_forwarder_block (header, mfb_keep_just,
755                                            update_latch_info);
756           alloc_aux_for_block (tmp_edge->dest, sizeof (int));
757           HEADER_BLOCK (tmp_edge->dest) = 1;
758           alloc_aux_for_edge (tmp_edge, sizeof (int));
759           LATCH_EDGE (tmp_edge) = 0;
760           HEADER_BLOCK (header)--;
761         }
762
763       if (HEADER_BLOCK (header) > 1)
764         {
765           /* Create a new latch block.  */
766           tmp_edge = make_forwarder_block (header, mfb_keep_nonlatch,
767                                            update_latch_info);
768           alloc_aux_for_block (tmp_edge->dest, sizeof (int));
769           HEADER_BLOCK (tmp_edge->src) = 0;
770           HEADER_BLOCK (tmp_edge->dest) = 1;
771           alloc_aux_for_edge (tmp_edge, sizeof (int));
772           LATCH_EDGE (tmp_edge) = 1;
773         }
774     }
775
776   free_aux_for_blocks ();
777   free_aux_for_edges ();
778
779 #ifdef ENABLE_CHECKING
780   verify_dominators (CDI_DOMINATORS);
781 #endif
782 }
783
784 /* Initialize all the parallel_p fields of the loops structure to true.  */
785
786 static void
787 initialize_loops_parallel_p (struct loops *loops)
788 {
789   unsigned int i;
790
791   for (i = 0; i < loops->num; i++)
792     {
793       struct loop *loop = loops->parray[i];
794       loop->parallel_p = true;
795     }
796 }
797
798 /* Find all the natural loops in the function and save in LOOPS structure and
799    recalculate loop_depth information in basic block structures.  FLAGS
800    controls which loop information is collected.  Return the number of natural
801    loops found.  */
802
803 int
804 flow_loops_find (struct loops *loops, int flags)
805 {
806   int i;
807   int b;
808   int num_loops;
809   edge e;
810   sbitmap headers;
811   int *dfs_order;
812   int *rc_order;
813   basic_block header;
814   basic_block bb;
815
816   /* This function cannot be repeatedly called with different
817      flags to build up the loop information.  The loop tree
818      must always be built if this function is called.  */
819   gcc_assert (flags & LOOP_TREE);
820
821   memset (loops, 0, sizeof *loops);
822
823   /* Taking care of this degenerate case makes the rest of
824      this code simpler.  */
825   if (n_basic_blocks == 0)
826     return 0;
827
828   dfs_order = NULL;
829   rc_order = NULL;
830
831   /* Ensure that the dominators are computed.  */
832   calculate_dominance_info (CDI_DOMINATORS);
833
834   /* Join loops with shared headers.  */
835   canonicalize_loop_headers ();
836
837   /* Count the number of loop headers.  This should be the
838      same as the number of natural loops.  */
839   headers = sbitmap_alloc (last_basic_block);
840   sbitmap_zero (headers);
841
842   num_loops = 0;
843   FOR_EACH_BB (header)
844     {
845       edge_iterator ei;
846       int more_latches = 0;
847
848       header->loop_depth = 0;
849
850       /* If we have an abnormal predecessor, do not consider the
851          loop (not worth the problems).  */
852       FOR_EACH_EDGE (e, ei, header->preds)
853         if (e->flags & EDGE_ABNORMAL)
854           break;
855       if (e)
856         continue;
857
858       FOR_EACH_EDGE (e, ei, header->preds)
859         {
860           basic_block latch = e->src;
861
862           gcc_assert (!(e->flags & EDGE_ABNORMAL));
863
864           /* Look for back edges where a predecessor is dominated
865              by this block.  A natural loop has a single entry
866              node (header) that dominates all the nodes in the
867              loop.  It also has single back edge to the header
868              from a latch node.  */
869           if (latch != ENTRY_BLOCK_PTR
870               && dominated_by_p (CDI_DOMINATORS, latch, header))
871             {
872               /* Shared headers should be eliminated by now.  */
873               gcc_assert (!more_latches);
874               more_latches = 1;
875               SET_BIT (headers, header->index);
876               num_loops++;
877             }
878         }
879     }
880
881   /* Allocate loop structures.  */
882   loops->parray = xcalloc (num_loops + 1, sizeof (struct loop *));
883
884   /* Dummy loop containing whole function.  */
885   loops->parray[0] = xcalloc (1, sizeof (struct loop));
886   loops->parray[0]->next = NULL;
887   loops->parray[0]->inner = NULL;
888   loops->parray[0]->outer = NULL;
889   loops->parray[0]->depth = 0;
890   loops->parray[0]->pred = NULL;
891   loops->parray[0]->num_nodes = n_basic_blocks + 2;
892   loops->parray[0]->latch = EXIT_BLOCK_PTR;
893   loops->parray[0]->header = ENTRY_BLOCK_PTR;
894   ENTRY_BLOCK_PTR->loop_father = loops->parray[0];
895   EXIT_BLOCK_PTR->loop_father = loops->parray[0];
896
897   loops->tree_root = loops->parray[0];
898
899   /* Find and record information about all the natural loops
900      in the CFG.  */
901   loops->num = 1;
902   FOR_EACH_BB (bb)
903     bb->loop_father = loops->tree_root;
904
905   if (num_loops)
906     {
907       /* Compute depth first search order of the CFG so that outer
908          natural loops will be found before inner natural loops.  */
909       dfs_order = xmalloc (n_basic_blocks * sizeof (int));
910       rc_order = xmalloc (n_basic_blocks * sizeof (int));
911       flow_depth_first_order_compute (dfs_order, rc_order);
912
913       /* Save CFG derived information to avoid recomputing it.  */
914       loops->cfg.dfs_order = dfs_order;
915       loops->cfg.rc_order = rc_order;
916
917       num_loops = 1;
918
919       for (b = 0; b < n_basic_blocks; b++)
920         {
921           struct loop *loop;
922           edge_iterator ei;
923
924           /* Search the nodes of the CFG in reverse completion order
925              so that we can find outer loops first.  */
926           if (!TEST_BIT (headers, rc_order[b]))
927             continue;
928
929           header = BASIC_BLOCK (rc_order[b]);
930
931           loop = loops->parray[num_loops] = xcalloc (1, sizeof (struct loop));
932
933           loop->header = header;
934           loop->num = num_loops;
935           num_loops++;
936
937           /* Look for the latch for this header block.  */
938           FOR_EACH_EDGE (e, ei, header->preds)
939             {
940               basic_block latch = e->src;
941
942               if (latch != ENTRY_BLOCK_PTR
943                   && dominated_by_p (CDI_DOMINATORS, latch, header))
944                 {
945                   loop->latch = latch;
946                   break;
947                 }
948             }
949
950           flow_loop_tree_node_add (header->loop_father, loop);
951           loop->num_nodes = flow_loop_nodes_find (loop->header, loop);
952         }
953
954       /* Assign the loop nesting depth and enclosed loop level for each
955          loop.  */
956       loops->levels = flow_loops_level_compute (loops);
957
958       /* Scan the loops.  */
959       for (i = 1; i < num_loops; i++)
960         flow_loop_scan (loops->parray[i], flags);
961
962       loops->num = num_loops;
963       initialize_loops_parallel_p (loops);
964     }
965
966   sbitmap_free (headers);
967
968   loops->state = 0;
969 #ifdef ENABLE_CHECKING
970   verify_flow_info ();
971   verify_loop_structure (loops);
972 #endif
973
974   return loops->num;
975 }
976
977 /* Return nonzero if basic block BB belongs to LOOP.  */
978 bool
979 flow_bb_inside_loop_p (const struct loop *loop, const basic_block bb)
980 {
981   struct loop *source_loop;
982
983   if (bb == ENTRY_BLOCK_PTR || bb == EXIT_BLOCK_PTR)
984     return 0;
985
986   source_loop = bb->loop_father;
987   return loop == source_loop || flow_loop_nested_p (loop, source_loop);
988 }
989
990 /* Return nonzero if edge E enters header of LOOP from outside of LOOP.  */
991
992 bool
993 flow_loop_outside_edge_p (const struct loop *loop, edge e)
994 {
995   gcc_assert (e->dest == loop->header);
996   return !flow_bb_inside_loop_p (loop, e->src);
997 }
998
999 /* Enumeration predicate for get_loop_body.  */
1000 static bool
1001 glb_enum_p (basic_block bb, void *glb_header)
1002 {
1003   return bb != (basic_block) glb_header;
1004 }
1005
1006 /* Gets basic blocks of a LOOP.  Header is the 0-th block, rest is in dfs
1007    order against direction of edges from latch.  Specially, if
1008    header != latch, latch is the 1-st block.  */
1009 basic_block *
1010 get_loop_body (const struct loop *loop)
1011 {
1012   basic_block *tovisit, bb;
1013   unsigned tv = 0;
1014
1015   gcc_assert (loop->num_nodes);
1016
1017   tovisit = xcalloc (loop->num_nodes, sizeof (basic_block));
1018   tovisit[tv++] = loop->header;
1019
1020   if (loop->latch == EXIT_BLOCK_PTR)
1021     {
1022       /* There may be blocks unreachable from EXIT_BLOCK.  */
1023       gcc_assert (loop->num_nodes == (unsigned) n_basic_blocks + 2);
1024       FOR_EACH_BB (bb)
1025         tovisit[tv++] = bb;
1026       tovisit[tv++] = EXIT_BLOCK_PTR;
1027     }
1028   else if (loop->latch != loop->header)
1029     {
1030       tv = dfs_enumerate_from (loop->latch, 1, glb_enum_p,
1031                                tovisit + 1, loop->num_nodes - 1,
1032                                loop->header) + 1;
1033     }
1034
1035   gcc_assert (tv == loop->num_nodes);
1036   return tovisit;
1037 }
1038
1039 /* Fills dominance descendants inside LOOP of the basic block BB into
1040    array TOVISIT from index *TV.  */
1041
1042 static void
1043 fill_sons_in_loop (const struct loop *loop, basic_block bb,
1044                    basic_block *tovisit, int *tv)
1045 {
1046   basic_block son, postpone = NULL;
1047
1048   tovisit[(*tv)++] = bb;
1049   for (son = first_dom_son (CDI_DOMINATORS, bb);
1050        son;
1051        son = next_dom_son (CDI_DOMINATORS, son))
1052     {
1053       if (!flow_bb_inside_loop_p (loop, son))
1054         continue;
1055
1056       if (dominated_by_p (CDI_DOMINATORS, loop->latch, son))
1057         {
1058           postpone = son;
1059           continue;
1060         }
1061       fill_sons_in_loop (loop, son, tovisit, tv);
1062     }
1063
1064   if (postpone)
1065     fill_sons_in_loop (loop, postpone, tovisit, tv);
1066 }
1067
1068 /* Gets body of a LOOP (that must be different from the outermost loop)
1069    sorted by dominance relation.  Additionally, if a basic block s dominates
1070    the latch, then only blocks dominated by s are be after it.  */
1071
1072 basic_block *
1073 get_loop_body_in_dom_order (const struct loop *loop)
1074 {
1075   basic_block *tovisit;
1076   int tv;
1077
1078   gcc_assert (loop->num_nodes);
1079
1080   tovisit = xcalloc (loop->num_nodes, sizeof (basic_block));
1081
1082   gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1083
1084   tv = 0;
1085   fill_sons_in_loop (loop, loop->header, tovisit, &tv);
1086
1087   gcc_assert (tv == (int) loop->num_nodes);
1088
1089   return tovisit;
1090 }
1091
1092 /* Get body of a LOOP in breadth first sort order.  */
1093
1094 basic_block *
1095 get_loop_body_in_bfs_order (const struct loop *loop)
1096 {
1097   basic_block *blocks;
1098   basic_block bb;
1099   bitmap visited;
1100   unsigned int i = 0;
1101   unsigned int vc = 1;
1102
1103   gcc_assert (loop->num_nodes);
1104   gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1105
1106   blocks = xcalloc (loop->num_nodes, sizeof (basic_block));
1107   visited = BITMAP_XMALLOC ();
1108
1109   bb = loop->header;
1110   while (i < loop->num_nodes)
1111     {
1112       edge e;
1113       edge_iterator ei;
1114       
1115       if (!bitmap_bit_p (visited, bb->index))
1116         { 
1117           /* This basic block is now visited */
1118           bitmap_set_bit (visited, bb->index);
1119           blocks[i++] = bb;
1120         }
1121       
1122       FOR_EACH_EDGE (e, ei, bb->succs)
1123         { 
1124           if (flow_bb_inside_loop_p (loop, e->dest))
1125             { 
1126               if (!bitmap_bit_p (visited, e->dest->index))
1127                 { 
1128                   bitmap_set_bit (visited, e->dest->index);
1129                   blocks[i++] = e->dest;
1130                 }
1131             }
1132         }
1133       
1134       gcc_assert (i >= vc);
1135       
1136       bb = blocks[vc++];
1137     }
1138   
1139   BITMAP_XFREE (visited);
1140   return blocks;
1141 }
1142
1143 /* Gets exit edges of a LOOP, returning their number in N_EDGES.  */
1144 edge *
1145 get_loop_exit_edges (const struct loop *loop, unsigned int *n_edges)
1146 {
1147   edge *edges, e;
1148   unsigned i, n;
1149   basic_block * body;
1150   edge_iterator ei;
1151
1152   gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1153
1154   body = get_loop_body (loop);
1155   n = 0;
1156   for (i = 0; i < loop->num_nodes; i++)
1157     FOR_EACH_EDGE (e, ei, body[i]->succs)
1158       if (!flow_bb_inside_loop_p (loop, e->dest))
1159         n++;
1160   edges = xmalloc (n * sizeof (edge));
1161   *n_edges = n;
1162   n = 0;
1163   for (i = 0; i < loop->num_nodes; i++)
1164     FOR_EACH_EDGE (e, ei, body[i]->succs)
1165       if (!flow_bb_inside_loop_p (loop, e->dest))
1166         edges[n++] = e;
1167   free (body);
1168
1169   return edges;
1170 }
1171
1172 /* Counts the number of conditional branches inside LOOP.  */
1173
1174 unsigned
1175 num_loop_branches (const struct loop *loop)
1176 {
1177   unsigned i, n;
1178   basic_block * body;
1179
1180   gcc_assert (loop->latch != EXIT_BLOCK_PTR);
1181
1182   body = get_loop_body (loop);
1183   n = 0;
1184   for (i = 0; i < loop->num_nodes; i++)
1185     if (EDGE_COUNT (body[i]->succs) >= 2)
1186       n++;
1187   free (body);
1188
1189   return n;
1190 }
1191
1192 /* Adds basic block BB to LOOP.  */
1193 void
1194 add_bb_to_loop (basic_block bb, struct loop *loop)
1195 {
1196    int i;
1197
1198    bb->loop_father = loop;
1199    bb->loop_depth = loop->depth;
1200    loop->num_nodes++;
1201    for (i = 0; i < loop->depth; i++)
1202      loop->pred[i]->num_nodes++;
1203  }
1204
1205 /* Remove basic block BB from loops.  */
1206 void
1207 remove_bb_from_loops (basic_block bb)
1208 {
1209    int i;
1210    struct loop *loop = bb->loop_father;
1211
1212    loop->num_nodes--;
1213    for (i = 0; i < loop->depth; i++)
1214      loop->pred[i]->num_nodes--;
1215    bb->loop_father = NULL;
1216    bb->loop_depth = 0;
1217  }
1218
1219 /* Finds nearest common ancestor in loop tree for given loops.  */
1220 struct loop *
1221 find_common_loop (struct loop *loop_s, struct loop *loop_d)
1222 {
1223   if (!loop_s) return loop_d;
1224   if (!loop_d) return loop_s;
1225
1226   if (loop_s->depth < loop_d->depth)
1227     loop_d = loop_d->pred[loop_s->depth];
1228   else if (loop_s->depth > loop_d->depth)
1229     loop_s = loop_s->pred[loop_d->depth];
1230
1231   while (loop_s != loop_d)
1232     {
1233       loop_s = loop_s->outer;
1234       loop_d = loop_d->outer;
1235     }
1236   return loop_s;
1237 }
1238
1239 /* Cancels the LOOP; it must be innermost one.  */
1240 void
1241 cancel_loop (struct loops *loops, struct loop *loop)
1242 {
1243   basic_block *bbs;
1244   unsigned i;
1245
1246   gcc_assert (!loop->inner);
1247
1248   /* Move blocks up one level (they should be removed as soon as possible).  */
1249   bbs = get_loop_body (loop);
1250   for (i = 0; i < loop->num_nodes; i++)
1251     bbs[i]->loop_father = loop->outer;
1252
1253   /* Remove the loop from structure.  */
1254   flow_loop_tree_node_remove (loop);
1255
1256   /* Remove loop from loops array.  */
1257   loops->parray[loop->num] = NULL;
1258
1259   /* Free loop data.  */
1260   flow_loop_free (loop);
1261 }
1262
1263 /* Cancels LOOP and all its subloops.  */
1264 void
1265 cancel_loop_tree (struct loops *loops, struct loop *loop)
1266 {
1267   while (loop->inner)
1268     cancel_loop_tree (loops, loop->inner);
1269   cancel_loop (loops, loop);
1270 }
1271
1272 /* Checks that LOOPS are all right:
1273      -- sizes of loops are all right
1274      -- results of get_loop_body really belong to the loop
1275      -- loop header have just single entry edge and single latch edge
1276      -- loop latches have only single successor that is header of their loop
1277      -- irreducible loops are correctly marked
1278   */
1279 void
1280 verify_loop_structure (struct loops *loops)
1281 {
1282   unsigned *sizes, i, j;
1283   sbitmap irreds;
1284   basic_block *bbs, bb;
1285   struct loop *loop;
1286   int err = 0;
1287   edge e;
1288
1289   /* Check sizes.  */
1290   sizes = xcalloc (loops->num, sizeof (int));
1291   sizes[0] = 2;
1292
1293   FOR_EACH_BB (bb)
1294     for (loop = bb->loop_father; loop; loop = loop->outer)
1295       sizes[loop->num]++;
1296
1297   for (i = 0; i < loops->num; i++)
1298     {
1299       if (!loops->parray[i])
1300         continue;
1301
1302       if (loops->parray[i]->num_nodes != sizes[i])
1303         {
1304           error ("Size of loop %d should be %d, not %d.",
1305                    i, sizes[i], loops->parray[i]->num_nodes);
1306           err = 1;
1307         }
1308     }
1309
1310   /* Check get_loop_body.  */
1311   for (i = 1; i < loops->num; i++)
1312     {
1313       loop = loops->parray[i];
1314       if (!loop)
1315         continue;
1316       bbs = get_loop_body (loop);
1317
1318       for (j = 0; j < loop->num_nodes; j++)
1319         if (!flow_bb_inside_loop_p (loop, bbs[j]))
1320           {
1321             error ("Bb %d do not belong to loop %d.",
1322                     bbs[j]->index, i);
1323             err = 1;
1324           }
1325       free (bbs);
1326     }
1327
1328   /* Check headers and latches.  */
1329   for (i = 1; i < loops->num; i++)
1330     {
1331       loop = loops->parray[i];
1332       if (!loop)
1333         continue;
1334
1335       if ((loops->state & LOOPS_HAVE_PREHEADERS)
1336           && EDGE_COUNT (loop->header->preds) != 2)
1337         {
1338           error ("Loop %d's header does not have exactly 2 entries.", i);
1339           err = 1;
1340         }
1341       if (loops->state & LOOPS_HAVE_SIMPLE_LATCHES)
1342         {
1343           if (EDGE_COUNT (loop->latch->succs) != 1)
1344             {
1345               error ("Loop %d's latch does not have exactly 1 successor.", i);
1346               err = 1;
1347             }
1348           if (EDGE_SUCC (loop->latch, 0)->dest != loop->header)
1349             {
1350               error ("Loop %d's latch does not have header as successor.", i);
1351               err = 1;
1352             }
1353           if (loop->latch->loop_father != loop)
1354             {
1355               error ("Loop %d's latch does not belong directly to it.", i);
1356               err = 1;
1357             }
1358         }
1359       if (loop->header->loop_father != loop)
1360         {
1361           error ("Loop %d's header does not belong directly to it.", i);
1362           err = 1;
1363         }
1364       if ((loops->state & LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)
1365           && (loop_latch_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP))
1366         {
1367           error ("Loop %d's latch is marked as part of irreducible region.", i);
1368           err = 1;
1369         }
1370     }
1371
1372   /* Check irreducible loops.  */
1373   if (loops->state & LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)
1374     {
1375       /* Record old info.  */
1376       irreds = sbitmap_alloc (last_basic_block);
1377       FOR_EACH_BB (bb)
1378         {
1379           edge_iterator ei;
1380           if (bb->flags & BB_IRREDUCIBLE_LOOP)
1381             SET_BIT (irreds, bb->index);
1382           else
1383             RESET_BIT (irreds, bb->index);
1384           FOR_EACH_EDGE (e, ei, bb->succs)
1385             if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1386               e->flags |= EDGE_ALL_FLAGS + 1;
1387         }
1388
1389       /* Recount it.  */
1390       mark_irreducible_loops (loops);
1391
1392       /* Compare.  */
1393       FOR_EACH_BB (bb)
1394         {
1395           edge_iterator ei;
1396
1397           if ((bb->flags & BB_IRREDUCIBLE_LOOP)
1398               && !TEST_BIT (irreds, bb->index))
1399             {
1400               error ("Basic block %d should be marked irreducible.", bb->index);
1401               err = 1;
1402             }
1403           else if (!(bb->flags & BB_IRREDUCIBLE_LOOP)
1404               && TEST_BIT (irreds, bb->index))
1405             {
1406               error ("Basic block %d should not be marked irreducible.", bb->index);
1407               err = 1;
1408             }
1409           FOR_EACH_EDGE (e, ei, bb->succs)
1410             {
1411               if ((e->flags & EDGE_IRREDUCIBLE_LOOP)
1412                   && !(e->flags & (EDGE_ALL_FLAGS + 1)))
1413                 {
1414                   error ("Edge from %d to %d should be marked irreducible.",
1415                          e->src->index, e->dest->index);
1416                   err = 1;
1417                 }
1418               else if (!(e->flags & EDGE_IRREDUCIBLE_LOOP)
1419                        && (e->flags & (EDGE_ALL_FLAGS + 1)))
1420                 {
1421                   error ("Edge from %d to %d should not be marked irreducible.",
1422                          e->src->index, e->dest->index);
1423                   err = 1;
1424                 }
1425               e->flags &= ~(EDGE_ALL_FLAGS + 1);
1426             }
1427         }
1428       free (irreds);
1429     }
1430
1431   /* Check the single_exit.  */
1432   if (loops->state & LOOPS_HAVE_MARKED_SINGLE_EXITS)
1433     {
1434       memset (sizes, 0, sizeof (unsigned) * loops->num);
1435       FOR_EACH_BB (bb)
1436         {
1437           edge_iterator ei;
1438           if (bb->loop_father == loops->tree_root)
1439             continue;
1440           FOR_EACH_EDGE (e, ei, bb->succs)
1441             {
1442               if (e->dest == EXIT_BLOCK_PTR)
1443                 continue;
1444
1445               if (flow_bb_inside_loop_p (bb->loop_father, e->dest))
1446                 continue;
1447
1448               for (loop = bb->loop_father;
1449                    loop != e->dest->loop_father;
1450                    loop = loop->outer)
1451                 {
1452                   sizes[loop->num]++;
1453                   if (loop->single_exit
1454                       && loop->single_exit != e)
1455                     {
1456                       error ("Wrong single exit %d->%d recorded for loop %d.",
1457                              loop->single_exit->src->index,
1458                              loop->single_exit->dest->index,
1459                              loop->num);
1460                       error ("Right exit is %d->%d.",
1461                              e->src->index, e->dest->index);
1462                       err = 1;
1463                     }
1464                 }
1465             }
1466         }
1467
1468       for (i = 1; i < loops->num; i++)
1469         {
1470           loop = loops->parray[i];
1471           if (!loop)
1472             continue;
1473
1474           if (sizes[i] == 1
1475               && !loop->single_exit)
1476             {
1477               error ("Single exit not recorded for loop %d.", loop->num);
1478               err = 1;
1479             }
1480
1481           if (sizes[i] != 1
1482               && loop->single_exit)
1483             {
1484               error ("Loop %d should not have single exit (%d -> %d).",
1485                      loop->num,
1486                      loop->single_exit->src->index,
1487                      loop->single_exit->dest->index);
1488               err = 1;
1489             }
1490         }
1491     }
1492
1493   gcc_assert (!err);
1494
1495   free (sizes);
1496 }
1497
1498 /* Returns latch edge of LOOP.  */
1499 edge
1500 loop_latch_edge (const struct loop *loop)
1501 {
1502   return find_edge (loop->latch, loop->header);
1503 }
1504
1505 /* Returns preheader edge of LOOP.  */
1506 edge
1507 loop_preheader_edge (const struct loop *loop)
1508 {
1509   edge e;
1510   edge_iterator ei;
1511
1512   FOR_EACH_EDGE (e, ei, loop->header->preds)
1513     if (e->src != loop->latch)
1514       break;
1515
1516   return e;
1517 }