Add VEC_WIDEN_MULT_EVEN/ODD_EXPR
[platform/upstream/gcc.git] / gcc / tree-ssa-threadupdate.c
1 /* Thread edges through blocks and update the control flow and SSA graphs.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 201
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "flags.h"
27 #include "tm_p.h"
28 #include "basic-block.h"
29 #include "function.h"
30 #include "tree-flow.h"
31 #include "tree-dump.h"
32 #include "tree-pass.h"
33 #include "cfgloop.h"
34
35 /* Given a block B, update the CFG and SSA graph to reflect redirecting
36    one or more in-edges to B to instead reach the destination of an
37    out-edge from B while preserving any side effects in B.
38
39    i.e., given A->B and B->C, change A->B to be A->C yet still preserve the
40    side effects of executing B.
41
42      1. Make a copy of B (including its outgoing edges and statements).  Call
43         the copy B'.  Note B' has no incoming edges or PHIs at this time.
44
45      2. Remove the control statement at the end of B' and all outgoing edges
46         except B'->C.
47
48      3. Add a new argument to each PHI in C with the same value as the existing
49         argument associated with edge B->C.  Associate the new PHI arguments
50         with the edge B'->C.
51
52      4. For each PHI in B, find or create a PHI in B' with an identical
53         PHI_RESULT.  Add an argument to the PHI in B' which has the same
54         value as the PHI in B associated with the edge A->B.  Associate
55         the new argument in the PHI in B' with the edge A->B.
56
57      5. Change the edge A->B to A->B'.
58
59         5a. This automatically deletes any PHI arguments associated with the
60             edge A->B in B.
61
62         5b. This automatically associates each new argument added in step 4
63             with the edge A->B'.
64
65      6. Repeat for other incoming edges into B.
66
67      7. Put the duplicated resources in B and all the B' blocks into SSA form.
68
69    Note that block duplication can be minimized by first collecting the
70    set of unique destination blocks that the incoming edges should
71    be threaded to.
72
73    Block duplication can be further minimized by using B instead of 
74    creating B' for one destination if all edges into B are going to be
75    threaded to a successor of B.  We had code to do this at one time, but
76    I'm not convinced it is correct with the changes to avoid mucking up
77    the loop structure (which may cancel threading requests, thus a block
78    which we thought was going to become unreachable may still be reachable).
79    This code was also going to get ugly with the introduction of the ability
80    for a single jump thread request to bypass multiple blocks. 
81
82    We further reduce the number of edges and statements we create by
83    not copying all the outgoing edges and the control statement in
84    step #1.  We instead create a template block without the outgoing
85    edges and duplicate the template.  */
86
87
88 /* Steps #5 and #6 of the above algorithm are best implemented by walking
89    all the incoming edges which thread to the same destination edge at
90    the same time.  That avoids lots of table lookups to get information
91    for the destination edge.
92
93    To realize that implementation we create a list of incoming edges
94    which thread to the same outgoing edge.  Thus to implement steps
95    #5 and #6 we traverse our hash table of outgoing edge information.
96    For each entry we walk the list of incoming edges which thread to
97    the current outgoing edge.  */
98
99 struct el
100 {
101   edge e;
102   struct el *next;
103 };
104
105 /* Main data structure recording information regarding B's duplicate
106    blocks.  */
107
108 /* We need to efficiently record the unique thread destinations of this
109    block and specific information associated with those destinations.  We
110    may have many incoming edges threaded to the same outgoing edge.  This
111    can be naturally implemented with a hash table.  */
112
113 struct redirection_data
114 {
115   /* A duplicate of B with the trailing control statement removed and which
116      targets a single successor of B.  */
117   basic_block dup_block;
118
119   /* An outgoing edge from B.  DUP_BLOCK will have OUTGOING_EDGE->dest as
120      its single successor.  */
121   edge outgoing_edge;
122
123   edge intermediate_edge;
124
125   /* A list of incoming edges which we want to thread to
126      OUTGOING_EDGE->dest.  */
127   struct el *incoming_edges;
128 };
129
130 /* Main data structure to hold information for duplicates of BB.  */
131 static htab_t redirection_data;
132
133 /* Data structure of information to pass to hash table traversal routines.  */
134 struct local_info
135 {
136   /* The current block we are working on.  */
137   basic_block bb;
138
139   /* A template copy of BB with no outgoing edges or control statement that
140      we use for creating copies.  */
141   basic_block template_block;
142
143   /* TRUE if we thread one or more jumps, FALSE otherwise.  */
144   bool jumps_threaded;
145 };
146
147 /* Passes which use the jump threading code register jump threading
148    opportunities as they are discovered.  We keep the registered
149    jump threading opportunities in this vector as edge pairs
150    (original_edge, target_edge).  */
151 static VEC(edge,heap) *threaded_edges;
152
153 /* When we start updating the CFG for threading, data necessary for jump
154    threading is attached to the AUX field for the incoming edge.  Use these
155    macros to access the underlying structure attached to the AUX field.  */
156 #define THREAD_TARGET(E) ((edge *)(E)->aux)[0]
157 #define THREAD_TARGET2(E) ((edge *)(E)->aux)[1]
158
159 /* Jump threading statistics.  */
160
161 struct thread_stats_d
162 {
163   unsigned long num_threaded_edges;
164 };
165
166 struct thread_stats_d thread_stats;
167
168
169 /* Remove the last statement in block BB if it is a control statement
170    Also remove all outgoing edges except the edge which reaches DEST_BB.
171    If DEST_BB is NULL, then remove all outgoing edges.  */
172
173 static void
174 remove_ctrl_stmt_and_useless_edges (basic_block bb, basic_block dest_bb)
175 {
176   gimple_stmt_iterator gsi;
177   edge e;
178   edge_iterator ei;
179
180   gsi = gsi_last_bb (bb);
181
182   /* If the duplicate ends with a control statement, then remove it.
183
184      Note that if we are duplicating the template block rather than the
185      original basic block, then the duplicate might not have any real
186      statements in it.  */
187   if (!gsi_end_p (gsi)
188       && gsi_stmt (gsi)
189       && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
190           || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
191           || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH))
192     gsi_remove (&gsi, true);
193
194   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
195     {
196       if (e->dest != dest_bb)
197         remove_edge (e);
198       else
199         ei_next (&ei);
200     }
201 }
202
203 /* Create a duplicate of BB.  Record the duplicate block in RD.  */
204
205 static void
206 create_block_for_threading (basic_block bb, struct redirection_data *rd)
207 {
208   edge_iterator ei;
209   edge e;
210
211   /* We can use the generic block duplication code and simply remove
212      the stuff we do not need.  */
213   rd->dup_block = duplicate_block (bb, NULL, NULL);
214
215   FOR_EACH_EDGE (e, ei, rd->dup_block->succs)
216     e->aux = NULL;
217
218   /* Zero out the profile, since the block is unreachable for now.  */
219   rd->dup_block->frequency = 0;
220   rd->dup_block->count = 0;
221 }
222
223 /* Hashing and equality routines for our hash table.  */
224 static hashval_t
225 redirection_data_hash (const void *p)
226 {
227   edge e = ((const struct redirection_data *)p)->outgoing_edge;
228   return e->dest->index;
229 }
230
231 static int
232 redirection_data_eq (const void *p1, const void *p2)
233 {
234   edge e1 = ((const struct redirection_data *)p1)->outgoing_edge;
235   edge e2 = ((const struct redirection_data *)p2)->outgoing_edge;
236   edge e3 = ((const struct redirection_data *)p1)->intermediate_edge;
237   edge e4 = ((const struct redirection_data *)p2)->intermediate_edge;
238
239   return e1 == e2 && e3 == e4;
240 }
241
242 /* Given an outgoing edge E lookup and return its entry in our hash table.
243
244    If INSERT is true, then we insert the entry into the hash table if
245    it is not already present.  INCOMING_EDGE is added to the list of incoming
246    edges associated with E in the hash table.  */
247
248 static struct redirection_data *
249 lookup_redirection_data (edge e, enum insert_option insert)
250 {
251   void **slot;
252   struct redirection_data *elt;
253
254  /* Build a hash table element so we can see if E is already
255      in the table.  */
256   elt = XNEW (struct redirection_data);
257   elt->intermediate_edge = THREAD_TARGET2 (e) ? THREAD_TARGET (e) : NULL;
258   elt->outgoing_edge = THREAD_TARGET2 (e) ? THREAD_TARGET2 (e) 
259                                           : THREAD_TARGET (e);
260   elt->dup_block = NULL;
261   elt->incoming_edges = NULL;
262
263   slot = htab_find_slot (redirection_data, elt, insert);
264
265   /* This will only happen if INSERT is false and the entry is not
266      in the hash table.  */
267   if (slot == NULL)
268     {
269       free (elt);
270       return NULL;
271     }
272
273   /* This will only happen if E was not in the hash table and
274      INSERT is true.  */
275   if (*slot == NULL)
276     {
277       *slot = (void *)elt;
278       elt->incoming_edges = XNEW (struct el);
279       elt->incoming_edges->e = e;
280       elt->incoming_edges->next = NULL;
281       return elt;
282     }
283   /* E was in the hash table.  */
284   else
285     {
286       /* Free ELT as we do not need it anymore, we will extract the
287          relevant entry from the hash table itself.  */
288       free (elt);
289
290       /* Get the entry stored in the hash table.  */
291       elt = (struct redirection_data *) *slot;
292
293       /* If insertion was requested, then we need to add INCOMING_EDGE
294          to the list of incoming edges associated with E.  */
295       if (insert)
296         {
297           struct el *el = XNEW (struct el);
298           el->next = elt->incoming_edges;
299           el->e = e;
300           elt->incoming_edges = el;
301         }
302
303       return elt;
304     }
305 }
306
307 /* For each PHI in BB, copy the argument associated with SRC_E to TGT_E.  */
308
309 static void
310 copy_phi_args (basic_block bb, edge src_e, edge tgt_e)
311 {
312   gimple_stmt_iterator gsi;
313   int src_indx = src_e->dest_idx;
314
315   for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
316     {
317       gimple phi = gsi_stmt (gsi);
318       source_location locus = gimple_phi_arg_location (phi, src_indx);
319       tree block = gimple_phi_arg_block (phi, src_indx);
320       add_phi_arg (phi, gimple_phi_arg_def (phi, src_indx), tgt_e, locus,
321                    block);
322     }
323 }
324
325 /* We have recently made a copy of ORIG_BB, including its outgoing
326    edges.  The copy is NEW_BB.  Every PHI node in every direct successor of
327    ORIG_BB has a new argument associated with edge from NEW_BB to the
328    successor.  Initialize the PHI argument so that it is equal to the PHI
329    argument associated with the edge from ORIG_BB to the successor.  */
330
331 static void
332 update_destination_phis (basic_block orig_bb, basic_block new_bb)
333 {
334   edge_iterator ei;
335   edge e;
336
337   FOR_EACH_EDGE (e, ei, orig_bb->succs)
338     {
339       edge e2 = find_edge (new_bb, e->dest);
340       copy_phi_args (e->dest, e, e2);
341     }
342 }
343
344 /* Given a duplicate block and its single destination (both stored
345    in RD).  Create an edge between the duplicate and its single
346    destination.
347
348    Add an additional argument to any PHI nodes at the single
349    destination.  */
350
351 static void
352 create_edge_and_update_destination_phis (struct redirection_data *rd,
353                                          basic_block bb)
354 {
355   edge e = make_edge (bb, rd->outgoing_edge->dest, EDGE_FALLTHRU);
356
357   rescan_loop_exit (e, true, false);
358   e->probability = REG_BR_PROB_BASE;
359   e->count = bb->count;
360
361   if (rd->outgoing_edge->aux)
362     {
363       e->aux = (edge *) XNEWVEC (edge, 2);
364       THREAD_TARGET(e) = THREAD_TARGET (rd->outgoing_edge);
365       THREAD_TARGET2(e) = THREAD_TARGET2 (rd->outgoing_edge);
366     }
367   else
368     {
369       e->aux = NULL;
370     }
371
372   /* If there are any PHI nodes at the destination of the outgoing edge
373      from the duplicate block, then we will need to add a new argument
374      to them.  The argument should have the same value as the argument
375      associated with the outgoing edge stored in RD.  */
376   copy_phi_args (e->dest, rd->outgoing_edge, e);
377 }
378
379 /* Wire up the outgoing edges from the duplicate block and
380    update any PHIs as needed.  */
381 static void
382 fix_duplicate_block_edges (struct redirection_data *rd,
383                            struct local_info *local_info)
384 {
385   /* If we were threading through an joiner block, then we want
386      to keep its control statement and redirect an outgoing edge.
387      Else we want to remove the control statement & edges, then create
388      a new outgoing edge.  In both cases we may need to update PHIs.  */
389   if (THREAD_TARGET2 (rd->incoming_edges->e))
390     {
391       edge victim;
392       edge e2;
393       edge e = rd->incoming_edges->e;
394
395       /* This updates the PHIs at the destination of the duplicate
396          block.  */
397       update_destination_phis (local_info->bb, rd->dup_block);
398
399       /* Find the edge from the duplicate block to the block we're
400          threading through.  That's the edge we want to redirect.  */
401       victim = find_edge (rd->dup_block, THREAD_TARGET (e)->dest);
402       e2 = redirect_edge_and_branch (victim, THREAD_TARGET2 (e)->dest);
403
404       /* If we redirected the edge, then we need to copy PHI arguments
405          at the target.  If the edge already existed (e2 != victim case),
406          then the PHIs in the target already have the correct arguments.  */
407       if (e2 == victim)
408         copy_phi_args (e2->dest, THREAD_TARGET2 (e), e2);
409     }
410   else
411     {
412       remove_ctrl_stmt_and_useless_edges (rd->dup_block, NULL);
413       create_edge_and_update_destination_phis (rd, rd->dup_block);
414     }
415 }
416 /* Hash table traversal callback routine to create duplicate blocks.  */
417
418 static int
419 create_duplicates (void **slot, void *data)
420 {
421   struct redirection_data *rd = (struct redirection_data *) *slot;
422   struct local_info *local_info = (struct local_info *)data;
423
424   /* Create a template block if we have not done so already.  Otherwise
425      use the template to create a new block.  */
426   if (local_info->template_block == NULL)
427     {
428       create_block_for_threading (local_info->bb, rd);
429       local_info->template_block = rd->dup_block;
430
431       /* We do not create any outgoing edges for the template.  We will
432          take care of that in a later traversal.  That way we do not
433          create edges that are going to just be deleted.  */
434     }
435   else
436     {
437       create_block_for_threading (local_info->template_block, rd);
438
439       /* Go ahead and wire up outgoing edges and update PHIs for the duplicate
440          block.   */
441       fix_duplicate_block_edges (rd, local_info);
442     }
443
444   /* Keep walking the hash table.  */
445   return 1;
446 }
447
448 /* We did not create any outgoing edges for the template block during
449    block creation.  This hash table traversal callback creates the
450    outgoing edge for the template block.  */
451
452 static int
453 fixup_template_block (void **slot, void *data)
454 {
455   struct redirection_data *rd = (struct redirection_data *) *slot;
456   struct local_info *local_info = (struct local_info *)data;
457
458   /* If this is the template block halt the traversal after updating
459      it appropriately.
460
461      If we were threading through an joiner block, then we want
462      to keep its control statement and redirect an outgoing edge.
463      Else we want to remove the control statement & edges, then create
464      a new outgoing edge.  In both cases we may need to update PHIs.  */
465   if (rd->dup_block && rd->dup_block == local_info->template_block)
466     {
467       fix_duplicate_block_edges (rd, local_info);
468       return 0;
469     }
470
471   return 1;
472 }
473
474 /* Hash table traversal callback to redirect each incoming edge
475    associated with this hash table element to its new destination.  */
476
477 static int
478 redirect_edges (void **slot, void *data)
479 {
480   struct redirection_data *rd = (struct redirection_data *) *slot;
481   struct local_info *local_info = (struct local_info *)data;
482   struct el *next, *el;
483
484   /* Walk over all the incoming edges associated associated with this
485      hash table entry.  */
486   for (el = rd->incoming_edges; el; el = next)
487     {
488       edge e = el->e;
489
490       /* Go ahead and free this element from the list.  Doing this now
491          avoids the need for another list walk when we destroy the hash
492          table.  */
493       next = el->next;
494       free (el);
495
496       thread_stats.num_threaded_edges++;
497       /* If we are threading through a joiner block, then we have to
498          find the edge we want to redirect and update some PHI nodes.  */
499       if (THREAD_TARGET2 (e))
500         {
501           edge e2;
502
503           /* We want to redirect the incoming edge to the joiner block (E)
504              to instead reach the duplicate of the joiner block.  */
505           e2 = redirect_edge_and_branch (e, rd->dup_block);
506           flush_pending_stmts (e2);
507         }
508       else if (rd->dup_block)
509         {
510           edge e2;
511
512           if (dump_file && (dump_flags & TDF_DETAILS))
513             fprintf (dump_file, "  Threaded jump %d --> %d to %d\n",
514                      e->src->index, e->dest->index, rd->dup_block->index);
515
516           rd->dup_block->count += e->count;
517
518           /* Excessive jump threading may make frequencies large enough so
519              the computation overflows.  */
520           if (rd->dup_block->frequency < BB_FREQ_MAX * 2)
521             rd->dup_block->frequency += EDGE_FREQUENCY (e);
522           EDGE_SUCC (rd->dup_block, 0)->count += e->count;
523           /* Redirect the incoming edge to the appropriate duplicate
524              block.  */
525           e2 = redirect_edge_and_branch (e, rd->dup_block);
526           gcc_assert (e == e2);
527           flush_pending_stmts (e2);
528         }
529
530       /* Go ahead and clear E->aux.  It's not needed anymore and failure
531          to clear it will cause all kinds of unpleasant problems later.  */
532       free (e->aux);
533       e->aux = NULL;
534
535     }
536
537   /* Indicate that we actually threaded one or more jumps.  */
538   if (rd->incoming_edges)
539     local_info->jumps_threaded = true;
540
541   return 1;
542 }
543
544 /* Return true if this block has no executable statements other than
545    a simple ctrl flow instruction.  When the number of outgoing edges
546    is one, this is equivalent to a "forwarder" block.  */
547
548 static bool
549 redirection_block_p (basic_block bb)
550 {
551   gimple_stmt_iterator gsi;
552
553   /* Advance to the first executable statement.  */
554   gsi = gsi_start_bb (bb);
555   while (!gsi_end_p (gsi)
556          && (gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL
557              || is_gimple_debug (gsi_stmt (gsi))
558              || gimple_nop_p (gsi_stmt (gsi))))
559     gsi_next (&gsi);
560
561   /* Check if this is an empty block.  */
562   if (gsi_end_p (gsi))
563     return true;
564
565   /* Test that we've reached the terminating control statement.  */
566   return gsi_stmt (gsi)
567          && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
568              || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
569              || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH);
570 }
571
572 /* BB is a block which ends with a COND_EXPR or SWITCH_EXPR and when BB
573    is reached via one or more specific incoming edges, we know which
574    outgoing edge from BB will be traversed.
575
576    We want to redirect those incoming edges to the target of the
577    appropriate outgoing edge.  Doing so avoids a conditional branch
578    and may expose new optimization opportunities.  Note that we have
579    to update dominator tree and SSA graph after such changes.
580
581    The key to keeping the SSA graph update manageable is to duplicate
582    the side effects occurring in BB so that those side effects still
583    occur on the paths which bypass BB after redirecting edges.
584
585    We accomplish this by creating duplicates of BB and arranging for
586    the duplicates to unconditionally pass control to one specific
587    successor of BB.  We then revector the incoming edges into BB to
588    the appropriate duplicate of BB.
589
590    If NOLOOP_ONLY is true, we only perform the threading as long as it
591    does not affect the structure of the loops in a nontrivial way.  */
592
593 static bool
594 thread_block (basic_block bb, bool noloop_only)
595 {
596   /* E is an incoming edge into BB that we may or may not want to
597      redirect to a duplicate of BB.  */
598   edge e, e2;
599   edge_iterator ei;
600   struct local_info local_info;
601   struct loop *loop = bb->loop_father;
602
603   /* To avoid scanning a linear array for the element we need we instead
604      use a hash table.  For normal code there should be no noticeable
605      difference.  However, if we have a block with a large number of
606      incoming and outgoing edges such linear searches can get expensive.  */
607   redirection_data = htab_create (EDGE_COUNT (bb->succs),
608                                   redirection_data_hash,
609                                   redirection_data_eq,
610                                   free);
611
612   /* If we thread the latch of the loop to its exit, the loop ceases to
613      exist.  Make sure we do not restrict ourselves in order to preserve
614      this loop.  */
615   if (loop->header == bb)
616     {
617       e = loop_latch_edge (loop);
618
619       if (e->aux)
620         e2 = THREAD_TARGET (e);
621       else
622         e2 = NULL;
623
624       if (e2 && loop_exit_edge_p (loop, e2))
625         {
626           loop->header = NULL;
627           loop->latch = NULL;
628           loops_state_set (LOOPS_NEED_FIXUP);
629         }
630     }
631
632   /* Record each unique threaded destination into a hash table for
633      efficient lookups.  */
634   FOR_EACH_EDGE (e, ei, bb->preds)
635     {
636       if (e->aux == NULL)
637         continue;
638
639       if (THREAD_TARGET2 (e))
640         e2 = THREAD_TARGET2 (e);
641       else
642         e2 = THREAD_TARGET (e);
643
644       if (!e2
645           /* If NOLOOP_ONLY is true, we only allow threading through the
646              header of a loop to exit edges.  */
647           || (noloop_only
648               && bb == bb->loop_father->header
649               && (!loop_exit_edge_p (bb->loop_father, e2)
650                   || THREAD_TARGET2 (e))))
651         continue;
652
653       if (e->dest == e2->src)
654         update_bb_profile_for_threading (e->dest, EDGE_FREQUENCY (e),
655                                          e->count, THREAD_TARGET (e));
656
657       /* Insert the outgoing edge into the hash table if it is not
658          already in the hash table.  */
659       lookup_redirection_data (e, INSERT);
660     }
661
662   /* We do not update dominance info.  */
663   free_dominance_info (CDI_DOMINATORS);
664
665   /* We know we only thread through the loop header to loop exits.
666      Let the basic block duplication hook know we are not creating
667      a multiple entry loop.  */
668   if (noloop_only
669       && bb == bb->loop_father->header)
670     set_loop_copy (bb->loop_father, loop_outer (bb->loop_father));
671
672   /* Now create duplicates of BB.
673
674      Note that for a block with a high outgoing degree we can waste
675      a lot of time and memory creating and destroying useless edges.
676
677      So we first duplicate BB and remove the control structure at the
678      tail of the duplicate as well as all outgoing edges from the
679      duplicate.  We then use that duplicate block as a template for
680      the rest of the duplicates.  */
681   local_info.template_block = NULL;
682   local_info.bb = bb;
683   local_info.jumps_threaded = false;
684   htab_traverse (redirection_data, create_duplicates, &local_info);
685
686   /* The template does not have an outgoing edge.  Create that outgoing
687      edge and update PHI nodes as the edge's target as necessary.
688
689      We do this after creating all the duplicates to avoid creating
690      unnecessary edges.  */
691   htab_traverse (redirection_data, fixup_template_block, &local_info);
692
693   /* The hash table traversals above created the duplicate blocks (and the
694      statements within the duplicate blocks).  This loop creates PHI nodes for
695      the duplicated blocks and redirects the incoming edges into BB to reach
696      the duplicates of BB.  */
697   htab_traverse (redirection_data, redirect_edges, &local_info);
698
699   /* Done with this block.  Clear REDIRECTION_DATA.  */
700   htab_delete (redirection_data);
701   redirection_data = NULL;
702
703   if (noloop_only
704       && bb == bb->loop_father->header)
705     set_loop_copy (bb->loop_father, NULL);
706
707   /* Indicate to our caller whether or not any jumps were threaded.  */
708   return local_info.jumps_threaded;
709 }
710
711 /* Threads edge E through E->dest to the edge THREAD_TARGET (E).  Returns the
712    copy of E->dest created during threading, or E->dest if it was not necessary
713    to copy it (E is its single predecessor).  */
714
715 static basic_block
716 thread_single_edge (edge e)
717 {
718   basic_block bb = e->dest;
719   edge eto = THREAD_TARGET (e);
720   struct redirection_data rd;
721
722   free (e->aux);
723   e->aux = NULL;
724
725   thread_stats.num_threaded_edges++;
726
727   if (single_pred_p (bb))
728     {
729       /* If BB has just a single predecessor, we should only remove the
730          control statements at its end, and successors except for ETO.  */
731       remove_ctrl_stmt_and_useless_edges (bb, eto->dest);
732
733       /* And fixup the flags on the single remaining edge.  */
734       eto->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE | EDGE_ABNORMAL);
735       eto->flags |= EDGE_FALLTHRU;
736
737       return bb;
738     }
739
740   /* Otherwise, we need to create a copy.  */
741   if (e->dest == eto->src)
742     update_bb_profile_for_threading (bb, EDGE_FREQUENCY (e), e->count, eto);
743
744   rd.outgoing_edge = eto;
745
746   create_block_for_threading (bb, &rd);
747   remove_ctrl_stmt_and_useless_edges (rd.dup_block, NULL);
748   create_edge_and_update_destination_phis (&rd, rd.dup_block);
749
750   if (dump_file && (dump_flags & TDF_DETAILS))
751     fprintf (dump_file, "  Threaded jump %d --> %d to %d\n",
752              e->src->index, e->dest->index, rd.dup_block->index);
753
754   rd.dup_block->count = e->count;
755   rd.dup_block->frequency = EDGE_FREQUENCY (e);
756   single_succ_edge (rd.dup_block)->count = e->count;
757   redirect_edge_and_branch (e, rd.dup_block);
758   flush_pending_stmts (e);
759
760   return rd.dup_block;
761 }
762
763 /* Callback for dfs_enumerate_from.  Returns true if BB is different
764    from STOP and DBDS_CE_STOP.  */
765
766 static basic_block dbds_ce_stop;
767 static bool
768 dbds_continue_enumeration_p (const_basic_block bb, const void *stop)
769 {
770   return (bb != (const_basic_block) stop
771           && bb != dbds_ce_stop);
772 }
773
774 /* Evaluates the dominance relationship of latch of the LOOP and BB, and
775    returns the state.  */
776
777 enum bb_dom_status
778 {
779   /* BB does not dominate latch of the LOOP.  */
780   DOMST_NONDOMINATING,
781   /* The LOOP is broken (there is no path from the header to its latch.  */
782   DOMST_LOOP_BROKEN,
783   /* BB dominates the latch of the LOOP.  */
784   DOMST_DOMINATING
785 };
786
787 static enum bb_dom_status
788 determine_bb_domination_status (struct loop *loop, basic_block bb)
789 {
790   basic_block *bblocks;
791   unsigned nblocks, i;
792   bool bb_reachable = false;
793   edge_iterator ei;
794   edge e;
795
796   /* This function assumes BB is a successor of LOOP->header.
797      If that is not the case return DOMST_NONDOMINATING which
798      is always safe.  */
799     {
800       bool ok = false;
801
802       FOR_EACH_EDGE (e, ei, bb->preds)
803         {
804           if (e->src == loop->header)
805             {
806               ok = true;
807               break;
808             }
809         }
810
811       if (!ok)
812         return DOMST_NONDOMINATING;
813     }
814
815   if (bb == loop->latch)
816     return DOMST_DOMINATING;
817
818   /* Check that BB dominates LOOP->latch, and that it is back-reachable
819      from it.  */
820
821   bblocks = XCNEWVEC (basic_block, loop->num_nodes);
822   dbds_ce_stop = loop->header;
823   nblocks = dfs_enumerate_from (loop->latch, 1, dbds_continue_enumeration_p,
824                                 bblocks, loop->num_nodes, bb);
825   for (i = 0; i < nblocks; i++)
826     FOR_EACH_EDGE (e, ei, bblocks[i]->preds)
827       {
828         if (e->src == loop->header)
829           {
830             free (bblocks);
831             return DOMST_NONDOMINATING;
832           }
833         if (e->src == bb)
834           bb_reachable = true;
835       }
836
837   free (bblocks);
838   return (bb_reachable ? DOMST_DOMINATING : DOMST_LOOP_BROKEN);
839 }
840
841 /* Return true if BB is part of the new pre-header that is created
842    when threading the latch to DATA.  */
843
844 static bool
845 def_split_header_continue_p (const_basic_block bb, const void *data)
846 {
847   const_basic_block new_header = (const_basic_block) data;
848   return (bb->loop_father == new_header->loop_father
849           && bb != new_header);
850 }
851
852 /* Thread jumps through the header of LOOP.  Returns true if cfg changes.
853    If MAY_PEEL_LOOP_HEADERS is false, we avoid threading from entry edges
854    to the inside of the loop.  */
855
856 static bool
857 thread_through_loop_header (struct loop *loop, bool may_peel_loop_headers)
858 {
859   basic_block header = loop->header;
860   edge e, tgt_edge, latch = loop_latch_edge (loop);
861   edge_iterator ei;
862   basic_block tgt_bb, atgt_bb;
863   enum bb_dom_status domst;
864
865   /* We have already threaded through headers to exits, so all the threading
866      requests now are to the inside of the loop.  We need to avoid creating
867      irreducible regions (i.e., loops with more than one entry block), and
868      also loop with several latch edges, or new subloops of the loop (although
869      there are cases where it might be appropriate, it is difficult to decide,
870      and doing it wrongly may confuse other optimizers).
871
872      We could handle more general cases here.  However, the intention is to
873      preserve some information about the loop, which is impossible if its
874      structure changes significantly, in a way that is not well understood.
875      Thus we only handle few important special cases, in which also updating
876      of the loop-carried information should be feasible:
877
878      1) Propagation of latch edge to a block that dominates the latch block
879         of a loop.  This aims to handle the following idiom:
880
881         first = 1;
882         while (1)
883           {
884             if (first)
885               initialize;
886             first = 0;
887             body;
888           }
889
890         After threading the latch edge, this becomes
891
892         first = 1;
893         if (first)
894           initialize;
895         while (1)
896           {
897             first = 0;
898             body;
899           }
900
901         The original header of the loop is moved out of it, and we may thread
902         the remaining edges through it without further constraints.
903
904      2) All entry edges are propagated to a single basic block that dominates
905         the latch block of the loop.  This aims to handle the following idiom
906         (normally created for "for" loops):
907
908         i = 0;
909         while (1)
910           {
911             if (i >= 100)
912               break;
913             body;
914             i++;
915           }
916
917         This becomes
918
919         i = 0;
920         while (1)
921           {
922             body;
923             i++;
924             if (i >= 100)
925               break;
926           }
927      */
928
929   /* Threading through the header won't improve the code if the header has just
930      one successor.  */
931   if (single_succ_p (header))
932     goto fail;
933
934   if (latch->aux)
935     {
936       if (THREAD_TARGET2 (latch))
937         goto fail;
938       tgt_edge = THREAD_TARGET (latch);
939       tgt_bb = tgt_edge->dest;
940     }
941   else if (!may_peel_loop_headers
942            && !redirection_block_p (loop->header))
943     goto fail;
944   else
945     {
946       tgt_bb = NULL;
947       tgt_edge = NULL;
948       FOR_EACH_EDGE (e, ei, header->preds)
949         {
950           if (!e->aux)
951             {
952               if (e == latch)
953                 continue;
954
955               /* If latch is not threaded, and there is a header
956                  edge that is not threaded, we would create loop
957                  with multiple entries.  */
958               goto fail;
959             }
960
961           if (THREAD_TARGET2 (e))
962             goto fail;
963           tgt_edge = THREAD_TARGET (e);
964           atgt_bb = tgt_edge->dest;
965           if (!tgt_bb)
966             tgt_bb = atgt_bb;
967           /* Two targets of threading would make us create loop
968              with multiple entries.  */
969           else if (tgt_bb != atgt_bb)
970             goto fail;
971         }
972
973       if (!tgt_bb)
974         {
975           /* There are no threading requests.  */
976           return false;
977         }
978
979       /* Redirecting to empty loop latch is useless.  */
980       if (tgt_bb == loop->latch
981           && empty_block_p (loop->latch))
982         goto fail;
983     }
984
985   /* The target block must dominate the loop latch, otherwise we would be
986      creating a subloop.  */
987   domst = determine_bb_domination_status (loop, tgt_bb);
988   if (domst == DOMST_NONDOMINATING)
989     goto fail;
990   if (domst == DOMST_LOOP_BROKEN)
991     {
992       /* If the loop ceased to exist, mark it as such, and thread through its
993          original header.  */
994       loop->header = NULL;
995       loop->latch = NULL;
996       loops_state_set (LOOPS_NEED_FIXUP);
997       return thread_block (header, false);
998     }
999
1000   if (tgt_bb->loop_father->header == tgt_bb)
1001     {
1002       /* If the target of the threading is a header of a subloop, we need
1003          to create a preheader for it, so that the headers of the two loops
1004          do not merge.  */
1005       if (EDGE_COUNT (tgt_bb->preds) > 2)
1006         {
1007           tgt_bb = create_preheader (tgt_bb->loop_father, 0);
1008           gcc_assert (tgt_bb != NULL);
1009         }
1010       else
1011         tgt_bb = split_edge (tgt_edge);
1012     }
1013
1014   if (latch->aux)
1015     {
1016       basic_block *bblocks;
1017       unsigned nblocks, i;
1018
1019       /* First handle the case latch edge is redirected.  We are copying
1020          the loop header but not creating a multiple entry loop.  Make the
1021          cfg manipulation code aware of that fact.  */
1022       set_loop_copy (loop, loop);
1023       loop->latch = thread_single_edge (latch);
1024       set_loop_copy (loop, NULL);
1025       gcc_assert (single_succ (loop->latch) == tgt_bb);
1026       loop->header = tgt_bb;
1027
1028       /* Remove the new pre-header blocks from our loop.  */
1029       bblocks = XCNEWVEC (basic_block, loop->num_nodes);
1030       nblocks = dfs_enumerate_from (header, 0, def_split_header_continue_p,
1031                                     bblocks, loop->num_nodes, tgt_bb);
1032       for (i = 0; i < nblocks; i++)
1033         {
1034           remove_bb_from_loops (bblocks[i]);
1035           add_bb_to_loop (bblocks[i], loop_outer (loop));
1036         }
1037       free (bblocks);
1038
1039       /* Cancel remaining threading requests that would make the
1040          loop a multiple entry loop.  */
1041       FOR_EACH_EDGE (e, ei, header->preds)
1042         {
1043           edge e2;
1044           if (e->aux == NULL)
1045             continue;
1046
1047           if (THREAD_TARGET2 (e))
1048             e2 = THREAD_TARGET2 (e);
1049           else
1050             e2 = THREAD_TARGET (e);
1051
1052           if (e->src->loop_father != e2->dest->loop_father
1053               && e2->dest != loop->header)
1054             {
1055               free (e->aux);
1056               e->aux = NULL;
1057             }
1058         }
1059
1060       /* Thread the remaining edges through the former header.  */
1061       thread_block (header, false);
1062     }
1063   else
1064     {
1065       basic_block new_preheader;
1066
1067       /* Now consider the case entry edges are redirected to the new entry
1068          block.  Remember one entry edge, so that we can find the new
1069          preheader (its destination after threading).  */
1070       FOR_EACH_EDGE (e, ei, header->preds)
1071         {
1072           if (e->aux)
1073             break;
1074         }
1075
1076       /* The duplicate of the header is the new preheader of the loop.  Ensure
1077          that it is placed correctly in the loop hierarchy.  */
1078       set_loop_copy (loop, loop_outer (loop));
1079
1080       thread_block (header, false);
1081       set_loop_copy (loop, NULL);
1082       new_preheader = e->dest;
1083
1084       /* Create the new latch block.  This is always necessary, as the latch
1085          must have only a single successor, but the original header had at
1086          least two successors.  */
1087       loop->latch = NULL;
1088       mfb_kj_edge = single_succ_edge (new_preheader);
1089       loop->header = mfb_kj_edge->dest;
1090       latch = make_forwarder_block (tgt_bb, mfb_keep_just, NULL);
1091       loop->header = latch->dest;
1092       loop->latch = latch->src;
1093     }
1094
1095   return true;
1096
1097 fail:
1098   /* We failed to thread anything.  Cancel the requests.  */
1099   FOR_EACH_EDGE (e, ei, header->preds)
1100     {
1101       free (e->aux);
1102       e->aux = NULL;
1103     }
1104   return false;
1105 }
1106
1107 /* Walk through the registered jump threads and convert them into a
1108    form convenient for this pass.
1109
1110    Any block which has incoming edges threaded to outgoing edges
1111    will have its entry in THREADED_BLOCK set.
1112
1113    Any threaded edge will have its new outgoing edge stored in the
1114    original edge's AUX field.
1115
1116    This form avoids the need to walk all the edges in the CFG to
1117    discover blocks which need processing and avoids unnecessary
1118    hash table lookups to map from threaded edge to new target.  */
1119
1120 static void
1121 mark_threaded_blocks (bitmap threaded_blocks)
1122 {
1123   unsigned int i;
1124   bitmap_iterator bi;
1125   bitmap tmp = BITMAP_ALLOC (NULL);
1126   basic_block bb;
1127   edge e;
1128   edge_iterator ei;
1129
1130   for (i = 0; i < VEC_length (edge, threaded_edges); i += 3)
1131     {
1132       edge e = VEC_index (edge, threaded_edges, i);
1133       edge *x = (edge *) XNEWVEC (edge, 2);
1134
1135       e->aux = x;
1136       THREAD_TARGET (e) = VEC_index (edge, threaded_edges, i + 1);
1137       THREAD_TARGET2 (e) = VEC_index (edge, threaded_edges, i + 2);
1138       bitmap_set_bit (tmp, e->dest->index);
1139     }
1140
1141   /* If optimizing for size, only thread through block if we don't have
1142      to duplicate it or it's an otherwise empty redirection block.  */
1143   if (optimize_function_for_size_p (cfun))
1144     {
1145       EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
1146         {
1147           bb = BASIC_BLOCK (i);
1148           if (EDGE_COUNT (bb->preds) > 1
1149               && !redirection_block_p (bb))
1150             {
1151               FOR_EACH_EDGE (e, ei, bb->preds)
1152                 {
1153                   free (e->aux);
1154                   e->aux = NULL;
1155                 }
1156             }
1157           else
1158             bitmap_set_bit (threaded_blocks, i);
1159         }
1160     }
1161   else
1162     bitmap_copy (threaded_blocks, tmp);
1163
1164   BITMAP_FREE(tmp);
1165 }
1166
1167
1168 /* Walk through all blocks and thread incoming edges to the appropriate
1169    outgoing edge for each edge pair recorded in THREADED_EDGES.
1170
1171    It is the caller's responsibility to fix the dominance information
1172    and rewrite duplicated SSA_NAMEs back into SSA form.
1173
1174    If MAY_PEEL_LOOP_HEADERS is false, we avoid threading edges through
1175    loop headers if it does not simplify the loop.
1176
1177    Returns true if one or more edges were threaded, false otherwise.  */
1178
1179 bool
1180 thread_through_all_blocks (bool may_peel_loop_headers)
1181 {
1182   bool retval = false;
1183   unsigned int i;
1184   bitmap_iterator bi;
1185   bitmap threaded_blocks;
1186   struct loop *loop;
1187   loop_iterator li;
1188
1189   /* We must know about loops in order to preserve them.  */
1190   gcc_assert (current_loops != NULL);
1191
1192   if (threaded_edges == NULL)
1193     return false;
1194
1195   threaded_blocks = BITMAP_ALLOC (NULL);
1196   memset (&thread_stats, 0, sizeof (thread_stats));
1197
1198   mark_threaded_blocks (threaded_blocks);
1199
1200   initialize_original_copy_tables ();
1201
1202   /* First perform the threading requests that do not affect
1203      loop structure.  */
1204   EXECUTE_IF_SET_IN_BITMAP (threaded_blocks, 0, i, bi)
1205     {
1206       basic_block bb = BASIC_BLOCK (i);
1207
1208       if (EDGE_COUNT (bb->preds) > 0)
1209         retval |= thread_block (bb, true);
1210     }
1211
1212   /* Then perform the threading through loop headers.  We start with the
1213      innermost loop, so that the changes in cfg we perform won't affect
1214      further threading.  */
1215   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1216     {
1217       if (!loop->header
1218           || !bitmap_bit_p (threaded_blocks, loop->header->index))
1219         continue;
1220
1221       retval |= thread_through_loop_header (loop, may_peel_loop_headers);
1222     }
1223
1224   statistics_counter_event (cfun, "Jumps threaded",
1225                             thread_stats.num_threaded_edges);
1226
1227   free_original_copy_tables ();
1228
1229   BITMAP_FREE (threaded_blocks);
1230   threaded_blocks = NULL;
1231   VEC_free (edge, heap, threaded_edges);
1232   threaded_edges = NULL;
1233
1234   if (retval)
1235     loops_state_set (LOOPS_NEED_FIXUP);
1236
1237   return retval;
1238 }
1239
1240 /* Register a jump threading opportunity.  We queue up all the jump
1241    threading opportunities discovered by a pass and update the CFG
1242    and SSA form all at once.
1243
1244    E is the edge we can thread, E2 is the new target edge, i.e., we
1245    are effectively recording that E->dest can be changed to E2->dest
1246    after fixing the SSA graph.  */
1247
1248 void
1249 register_jump_thread (edge e, edge e2, edge e3)
1250 {
1251   /* This can occur if we're jumping to a constant address or
1252      or something similar.  Just get out now.  */
1253   if (e2 == NULL)
1254     return;
1255
1256   if (threaded_edges == NULL)
1257     threaded_edges = VEC_alloc (edge, heap, 15);
1258
1259   if (dump_file && (dump_flags & TDF_DETAILS)
1260       && e->dest != e2->src)
1261     fprintf (dump_file,
1262              "  Registering jump thread around one or more intermediate blocks\n");
1263
1264   VEC_safe_push (edge, heap, threaded_edges, e);
1265   VEC_safe_push (edge, heap, threaded_edges, e2);
1266   VEC_safe_push (edge, heap, threaded_edges, e3);
1267 }