S/390: Testsuite: Add asm scan patterns for -m31.
[official-gcc.git] / gcc / tree-ssa-threadupdate.c
blob3dd0e4f5fe6309aafdcccf281b00c97a6f6974ad
1 /* Thread edges through blocks and update the control flow and SSA graphs.
2 Copyright (C) 2004-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "tree.h"
25 #include "gimple.h"
26 #include "cfghooks.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "fold-const.h"
30 #include "cfganal.h"
31 #include "gimple-iterator.h"
32 #include "tree-ssa.h"
33 #include "tree-ssa-threadupdate.h"
34 #include "cfgloop.h"
35 #include "dbgcnt.h"
36 #include "tree-cfg.h"
38 /* Given a block B, update the CFG and SSA graph to reflect redirecting
39 one or more in-edges to B to instead reach the destination of an
40 out-edge from B while preserving any side effects in B.
42 i.e., given A->B and B->C, change A->B to be A->C yet still preserve the
43 side effects of executing B.
45 1. Make a copy of B (including its outgoing edges and statements). Call
46 the copy B'. Note B' has no incoming edges or PHIs at this time.
48 2. Remove the control statement at the end of B' and all outgoing edges
49 except B'->C.
51 3. Add a new argument to each PHI in C with the same value as the existing
52 argument associated with edge B->C. Associate the new PHI arguments
53 with the edge B'->C.
55 4. For each PHI in B, find or create a PHI in B' with an identical
56 PHI_RESULT. Add an argument to the PHI in B' which has the same
57 value as the PHI in B associated with the edge A->B. Associate
58 the new argument in the PHI in B' with the edge A->B.
60 5. Change the edge A->B to A->B'.
62 5a. This automatically deletes any PHI arguments associated with the
63 edge A->B in B.
65 5b. This automatically associates each new argument added in step 4
66 with the edge A->B'.
68 6. Repeat for other incoming edges into B.
70 7. Put the duplicated resources in B and all the B' blocks into SSA form.
72 Note that block duplication can be minimized by first collecting the
73 set of unique destination blocks that the incoming edges should
74 be threaded to.
76 We reduce the number of edges and statements we create by not copying all
77 the outgoing edges and the control statement in step #1. We instead create
78 a template block without the outgoing edges and duplicate the template.
80 Another case this code handles is threading through a "joiner" block. In
81 this case, we do not know the destination of the joiner block, but one
82 of the outgoing edges from the joiner block leads to a threadable path. This
83 case largely works as outlined above, except the duplicate of the joiner
84 block still contains a full set of outgoing edges and its control statement.
85 We just redirect one of its outgoing edges to our jump threading path. */
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.
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. */
99 struct el
101 edge e;
102 struct el *next;
105 /* Main data structure recording information regarding B's duplicate
106 blocks. */
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. */
113 struct redirection_data : free_ptr_hash<redirection_data>
115 /* We support wiring up two block duplicates in a jump threading path.
117 One is a normal block copy where we remove the control statement
118 and wire up its single remaining outgoing edge to the thread path.
120 The other is a joiner block where we leave the control statement
121 in place, but wire one of the outgoing edges to a thread path.
123 In theory we could have multiple block duplicates in a jump
124 threading path, but I haven't tried that.
126 The duplicate blocks appear in this array in the same order in
127 which they appear in the jump thread path. */
128 basic_block dup_blocks[2];
130 /* The jump threading path. */
131 vec<jump_thread_edge *> *path;
133 /* A list of incoming edges which we want to thread to the
134 same path. */
135 struct el *incoming_edges;
137 /* hash_table support. */
138 static inline hashval_t hash (const redirection_data *);
139 static inline int equal (const redirection_data *, const redirection_data *);
142 /* Dump a jump threading path, including annotations about each
143 edge in the path. */
145 static void
146 dump_jump_thread_path (FILE *dump_file, vec<jump_thread_edge *> path,
147 bool registering)
149 fprintf (dump_file,
150 " %s%s jump thread: (%d, %d) incoming edge; ",
151 (registering ? "Registering" : "Cancelling"),
152 (path[0]->type == EDGE_FSM_THREAD ? " FSM": ""),
153 path[0]->e->src->index, path[0]->e->dest->index);
155 for (unsigned int i = 1; i < path.length (); i++)
157 /* We can get paths with a NULL edge when the final destination
158 of a jump thread turns out to be a constant address. We dump
159 those paths when debugging, so we have to be prepared for that
160 possibility here. */
161 if (path[i]->e == NULL)
162 continue;
164 if (path[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
165 fprintf (dump_file, " (%d, %d) joiner; ",
166 path[i]->e->src->index, path[i]->e->dest->index);
167 if (path[i]->type == EDGE_COPY_SRC_BLOCK)
168 fprintf (dump_file, " (%d, %d) normal;",
169 path[i]->e->src->index, path[i]->e->dest->index);
170 if (path[i]->type == EDGE_NO_COPY_SRC_BLOCK)
171 fprintf (dump_file, " (%d, %d) nocopy;",
172 path[i]->e->src->index, path[i]->e->dest->index);
173 if (path[0]->type == EDGE_FSM_THREAD)
174 fprintf (dump_file, " (%d, %d) ",
175 path[i]->e->src->index, path[i]->e->dest->index);
177 fputc ('\n', dump_file);
180 /* Simple hashing function. For any given incoming edge E, we're going
181 to be most concerned with the final destination of its jump thread
182 path. So hash on the block index of the final edge in the path. */
184 inline hashval_t
185 redirection_data::hash (const redirection_data *p)
187 vec<jump_thread_edge *> *path = p->path;
188 return path->last ()->e->dest->index;
191 /* Given two hash table entries, return true if they have the same
192 jump threading path. */
193 inline int
194 redirection_data::equal (const redirection_data *p1, const redirection_data *p2)
196 vec<jump_thread_edge *> *path1 = p1->path;
197 vec<jump_thread_edge *> *path2 = p2->path;
199 if (path1->length () != path2->length ())
200 return false;
202 for (unsigned int i = 1; i < path1->length (); i++)
204 if ((*path1)[i]->type != (*path2)[i]->type
205 || (*path1)[i]->e != (*path2)[i]->e)
206 return false;
209 return true;
212 /* Rather than search all the edges in jump thread paths each time
213 DOM is able to simply if control statement, we build a hash table
214 with the deleted edges. We only care about the address of the edge,
215 not its contents. */
216 struct removed_edges : nofree_ptr_hash<edge_def>
218 static hashval_t hash (edge e) { return htab_hash_pointer (e); }
219 static bool equal (edge e1, edge e2) { return e1 == e2; }
222 static hash_table<removed_edges> *removed_edges;
224 /* Data structure of information to pass to hash table traversal routines. */
225 struct ssa_local_info_t
227 /* The current block we are working on. */
228 basic_block bb;
230 /* We only create a template block for the first duplicated block in a
231 jump threading path as we may need many duplicates of that block.
233 The second duplicate block in a path is specific to that path. Creating
234 and sharing a template for that block is considerably more difficult. */
235 basic_block template_block;
237 /* TRUE if we thread one or more jumps, FALSE otherwise. */
238 bool jumps_threaded;
240 /* Blocks duplicated for the thread. */
241 bitmap duplicate_blocks;
244 /* Passes which use the jump threading code register jump threading
245 opportunities as they are discovered. We keep the registered
246 jump threading opportunities in this vector as edge pairs
247 (original_edge, target_edge). */
248 static vec<vec<jump_thread_edge *> *> paths;
250 /* When we start updating the CFG for threading, data necessary for jump
251 threading is attached to the AUX field for the incoming edge. Use these
252 macros to access the underlying structure attached to the AUX field. */
253 #define THREAD_PATH(E) ((vec<jump_thread_edge *> *)(E)->aux)
255 /* Jump threading statistics. */
257 struct thread_stats_d
259 unsigned long num_threaded_edges;
262 struct thread_stats_d thread_stats;
265 /* Remove the last statement in block BB if it is a control statement
266 Also remove all outgoing edges except the edge which reaches DEST_BB.
267 If DEST_BB is NULL, then remove all outgoing edges. */
269 void
270 remove_ctrl_stmt_and_useless_edges (basic_block bb, basic_block dest_bb)
272 gimple_stmt_iterator gsi;
273 edge e;
274 edge_iterator ei;
276 gsi = gsi_last_bb (bb);
278 /* If the duplicate ends with a control statement, then remove it.
280 Note that if we are duplicating the template block rather than the
281 original basic block, then the duplicate might not have any real
282 statements in it. */
283 if (!gsi_end_p (gsi)
284 && gsi_stmt (gsi)
285 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
286 || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
287 || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH))
288 gsi_remove (&gsi, true);
290 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
292 if (e->dest != dest_bb)
294 free_dom_edge_info (e);
295 remove_edge (e);
297 else
298 ei_next (&ei);
301 /* If the remaining edge is a loop exit, there must have
302 a removed edge that was not a loop exit.
304 In that case BB and possibly other blocks were previously
305 in the loop, but are now outside the loop. Thus, we need
306 to update the loop structures. */
307 if (single_succ_p (bb)
308 && loop_outer (bb->loop_father)
309 && loop_exit_edge_p (bb->loop_father, single_succ_edge (bb)))
310 loops_state_set (LOOPS_NEED_FIXUP);
313 /* Create a duplicate of BB. Record the duplicate block in an array
314 indexed by COUNT stored in RD. */
316 static void
317 create_block_for_threading (basic_block bb,
318 struct redirection_data *rd,
319 unsigned int count,
320 bitmap *duplicate_blocks)
322 edge_iterator ei;
323 edge e;
325 /* We can use the generic block duplication code and simply remove
326 the stuff we do not need. */
327 rd->dup_blocks[count] = duplicate_block (bb, NULL, NULL);
329 FOR_EACH_EDGE (e, ei, rd->dup_blocks[count]->succs)
330 e->aux = NULL;
332 /* Zero out the profile, since the block is unreachable for now. */
333 rd->dup_blocks[count]->frequency = 0;
334 rd->dup_blocks[count]->count = 0;
335 if (duplicate_blocks)
336 bitmap_set_bit (*duplicate_blocks, rd->dup_blocks[count]->index);
339 /* Main data structure to hold information for duplicates of BB. */
341 static hash_table<redirection_data> *redirection_data;
343 /* Given an outgoing edge E lookup and return its entry in our hash table.
345 If INSERT is true, then we insert the entry into the hash table if
346 it is not already present. INCOMING_EDGE is added to the list of incoming
347 edges associated with E in the hash table. */
349 static struct redirection_data *
350 lookup_redirection_data (edge e, enum insert_option insert)
352 struct redirection_data **slot;
353 struct redirection_data *elt;
354 vec<jump_thread_edge *> *path = THREAD_PATH (e);
356 /* Build a hash table element so we can see if E is already
357 in the table. */
358 elt = XNEW (struct redirection_data);
359 elt->path = path;
360 elt->dup_blocks[0] = NULL;
361 elt->dup_blocks[1] = NULL;
362 elt->incoming_edges = NULL;
364 slot = redirection_data->find_slot (elt, insert);
366 /* This will only happen if INSERT is false and the entry is not
367 in the hash table. */
368 if (slot == NULL)
370 free (elt);
371 return NULL;
374 /* This will only happen if E was not in the hash table and
375 INSERT is true. */
376 if (*slot == NULL)
378 *slot = elt;
379 elt->incoming_edges = XNEW (struct el);
380 elt->incoming_edges->e = e;
381 elt->incoming_edges->next = NULL;
382 return elt;
384 /* E was in the hash table. */
385 else
387 /* Free ELT as we do not need it anymore, we will extract the
388 relevant entry from the hash table itself. */
389 free (elt);
391 /* Get the entry stored in the hash table. */
392 elt = *slot;
394 /* If insertion was requested, then we need to add INCOMING_EDGE
395 to the list of incoming edges associated with E. */
396 if (insert)
398 struct el *el = XNEW (struct el);
399 el->next = elt->incoming_edges;
400 el->e = e;
401 elt->incoming_edges = el;
404 return elt;
408 /* Similar to copy_phi_args, except that the PHI arg exists, it just
409 does not have a value associated with it. */
411 static void
412 copy_phi_arg_into_existing_phi (edge src_e, edge tgt_e)
414 int src_idx = src_e->dest_idx;
415 int tgt_idx = tgt_e->dest_idx;
417 /* Iterate over each PHI in e->dest. */
418 for (gphi_iterator gsi = gsi_start_phis (src_e->dest),
419 gsi2 = gsi_start_phis (tgt_e->dest);
420 !gsi_end_p (gsi);
421 gsi_next (&gsi), gsi_next (&gsi2))
423 gphi *src_phi = gsi.phi ();
424 gphi *dest_phi = gsi2.phi ();
425 tree val = gimple_phi_arg_def (src_phi, src_idx);
426 source_location locus = gimple_phi_arg_location (src_phi, src_idx);
428 SET_PHI_ARG_DEF (dest_phi, tgt_idx, val);
429 gimple_phi_arg_set_location (dest_phi, tgt_idx, locus);
433 /* Given ssa_name DEF, backtrack jump threading PATH from node IDX
434 to see if it has constant value in a flow sensitive manner. Set
435 LOCUS to location of the constant phi arg and return the value.
436 Return DEF directly if either PATH or idx is ZERO. */
438 static tree
439 get_value_locus_in_path (tree def, vec<jump_thread_edge *> *path,
440 basic_block bb, int idx, source_location *locus)
442 tree arg;
443 gphi *def_phi;
444 basic_block def_bb;
446 if (path == NULL || idx == 0)
447 return def;
449 def_phi = dyn_cast <gphi *> (SSA_NAME_DEF_STMT (def));
450 if (!def_phi)
451 return def;
453 def_bb = gimple_bb (def_phi);
454 /* Don't propagate loop invariants into deeper loops. */
455 if (!def_bb || bb_loop_depth (def_bb) < bb_loop_depth (bb))
456 return def;
458 /* Backtrack jump threading path from IDX to see if def has constant
459 value. */
460 for (int j = idx - 1; j >= 0; j--)
462 edge e = (*path)[j]->e;
463 if (e->dest == def_bb)
465 arg = gimple_phi_arg_def (def_phi, e->dest_idx);
466 if (is_gimple_min_invariant (arg))
468 *locus = gimple_phi_arg_location (def_phi, e->dest_idx);
469 return arg;
471 break;
475 return def;
478 /* For each PHI in BB, copy the argument associated with SRC_E to TGT_E.
479 Try to backtrack jump threading PATH from node IDX to see if the arg
480 has constant value, copy constant value instead of argument itself
481 if yes. */
483 static void
484 copy_phi_args (basic_block bb, edge src_e, edge tgt_e,
485 vec<jump_thread_edge *> *path, int idx)
487 gphi_iterator gsi;
488 int src_indx = src_e->dest_idx;
490 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
492 gphi *phi = gsi.phi ();
493 tree def = gimple_phi_arg_def (phi, src_indx);
494 source_location locus = gimple_phi_arg_location (phi, src_indx);
496 if (TREE_CODE (def) == SSA_NAME
497 && !virtual_operand_p (gimple_phi_result (phi)))
498 def = get_value_locus_in_path (def, path, bb, idx, &locus);
500 add_phi_arg (phi, def, tgt_e, locus);
504 /* We have recently made a copy of ORIG_BB, including its outgoing
505 edges. The copy is NEW_BB. Every PHI node in every direct successor of
506 ORIG_BB has a new argument associated with edge from NEW_BB to the
507 successor. Initialize the PHI argument so that it is equal to the PHI
508 argument associated with the edge from ORIG_BB to the successor.
509 PATH and IDX are used to check if the new PHI argument has constant
510 value in a flow sensitive manner. */
512 static void
513 update_destination_phis (basic_block orig_bb, basic_block new_bb,
514 vec<jump_thread_edge *> *path, int idx)
516 edge_iterator ei;
517 edge e;
519 FOR_EACH_EDGE (e, ei, orig_bb->succs)
521 edge e2 = find_edge (new_bb, e->dest);
522 copy_phi_args (e->dest, e, e2, path, idx);
526 /* Given a duplicate block and its single destination (both stored
527 in RD). Create an edge between the duplicate and its single
528 destination.
530 Add an additional argument to any PHI nodes at the single
531 destination. IDX is the start node in jump threading path
532 we start to check to see if the new PHI argument has constant
533 value along the jump threading path. */
535 static void
536 create_edge_and_update_destination_phis (struct redirection_data *rd,
537 basic_block bb, int idx)
539 edge e = make_edge (bb, rd->path->last ()->e->dest, EDGE_FALLTHRU);
541 rescan_loop_exit (e, true, false);
542 e->probability = REG_BR_PROB_BASE;
543 e->count = bb->count;
545 /* We used to copy the thread path here. That was added in 2007
546 and dutifully updated through the representation changes in 2013.
548 In 2013 we added code to thread from an interior node through
549 the backedge to another interior node. That runs after the code
550 to thread through loop headers from outside the loop.
552 The latter may delete edges in the CFG, including those
553 which appeared in the jump threading path we copied here. Thus
554 we'd end up using a dangling pointer.
556 After reviewing the 2007/2011 code, I can't see how anything
557 depended on copying the AUX field and clearly copying the jump
558 threading path is problematical due to embedded edge pointers.
559 It has been removed. */
560 e->aux = NULL;
562 /* If there are any PHI nodes at the destination of the outgoing edge
563 from the duplicate block, then we will need to add a new argument
564 to them. The argument should have the same value as the argument
565 associated with the outgoing edge stored in RD. */
566 copy_phi_args (e->dest, rd->path->last ()->e, e, rd->path, idx);
569 /* Look through PATH beginning at START and return TRUE if there are
570 any additional blocks that need to be duplicated. Otherwise,
571 return FALSE. */
572 static bool
573 any_remaining_duplicated_blocks (vec<jump_thread_edge *> *path,
574 unsigned int start)
576 for (unsigned int i = start + 1; i < path->length (); i++)
578 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK
579 || (*path)[i]->type == EDGE_COPY_SRC_BLOCK)
580 return true;
582 return false;
586 /* Compute the amount of profile count/frequency coming into the jump threading
587 path stored in RD that we are duplicating, returned in PATH_IN_COUNT_PTR and
588 PATH_IN_FREQ_PTR, as well as the amount of counts flowing out of the
589 duplicated path, returned in PATH_OUT_COUNT_PTR. LOCAL_INFO is used to
590 identify blocks duplicated for jump threading, which have duplicated
591 edges that need to be ignored in the analysis. Return true if path contains
592 a joiner, false otherwise.
594 In the non-joiner case, this is straightforward - all the counts/frequency
595 flowing into the jump threading path should flow through the duplicated
596 block and out of the duplicated path.
598 In the joiner case, it is very tricky. Some of the counts flowing into
599 the original path go offpath at the joiner. The problem is that while
600 we know how much total count goes off-path in the original control flow,
601 we don't know how many of the counts corresponding to just the jump
602 threading path go offpath at the joiner.
604 For example, assume we have the following control flow and identified
605 jump threading paths:
607 A B C
608 \ | /
609 Ea \ |Eb / Ec
610 \ | /
611 v v v
612 J <-- Joiner
614 Eoff/ \Eon
617 Soff Son <--- Normal
619 Ed/ \ Ee
624 Jump threading paths: A -> J -> Son -> D (path 1)
625 C -> J -> Son -> E (path 2)
627 Note that the control flow could be more complicated:
628 - Each jump threading path may have more than one incoming edge. I.e. A and
629 Ea could represent multiple incoming blocks/edges that are included in
630 path 1.
631 - There could be EDGE_NO_COPY_SRC_BLOCK edges after the joiner (either
632 before or after the "normal" copy block). These are not duplicated onto
633 the jump threading path, as they are single-successor.
634 - Any of the blocks along the path may have other incoming edges that
635 are not part of any jump threading path, but add profile counts along
636 the path.
638 In the aboe example, after all jump threading is complete, we will
639 end up with the following control flow:
641 A B C
642 | | |
643 Ea| |Eb |Ec
644 | | |
645 v v v
646 Ja J Jc
647 / \ / \Eon' / \
648 Eona/ \ ---/---\-------- \Eonc
649 / \ / / \ \
650 v v v v v
651 Sona Soff Son Sonc
652 \ /\ /
653 \___________ / \ _____/
654 \ / \/
655 vv v
658 The main issue to notice here is that when we are processing path 1
659 (A->J->Son->D) we need to figure out the outgoing edge weights to
660 the duplicated edges Ja->Sona and Ja->Soff, while ensuring that the
661 sum of the incoming weights to D remain Ed. The problem with simply
662 assuming that Ja (and Jc when processing path 2) has the same outgoing
663 probabilities to its successors as the original block J, is that after
664 all paths are processed and other edges/counts removed (e.g. none
665 of Ec will reach D after processing path 2), we may end up with not
666 enough count flowing along duplicated edge Sona->D.
668 Therefore, in the case of a joiner, we keep track of all counts
669 coming in along the current path, as well as from predecessors not
670 on any jump threading path (Eb in the above example). While we
671 first assume that the duplicated Eona for Ja->Sona has the same
672 probability as the original, we later compensate for other jump
673 threading paths that may eliminate edges. We do that by keep track
674 of all counts coming into the original path that are not in a jump
675 thread (Eb in the above example, but as noted earlier, there could
676 be other predecessors incoming to the path at various points, such
677 as at Son). Call this cumulative non-path count coming into the path
678 before D as Enonpath. We then ensure that the count from Sona->D is as at
679 least as big as (Ed - Enonpath), but no bigger than the minimum
680 weight along the jump threading path. The probabilities of both the
681 original and duplicated joiner block J and Ja will be adjusted
682 accordingly after the updates. */
684 static bool
685 compute_path_counts (struct redirection_data *rd,
686 ssa_local_info_t *local_info,
687 gcov_type *path_in_count_ptr,
688 gcov_type *path_out_count_ptr,
689 int *path_in_freq_ptr)
691 edge e = rd->incoming_edges->e;
692 vec<jump_thread_edge *> *path = THREAD_PATH (e);
693 edge elast = path->last ()->e;
694 gcov_type nonpath_count = 0;
695 bool has_joiner = false;
696 gcov_type path_in_count = 0;
697 int path_in_freq = 0;
699 /* Start by accumulating incoming edge counts to the path's first bb
700 into a couple buckets:
701 path_in_count: total count of incoming edges that flow into the
702 current path.
703 nonpath_count: total count of incoming edges that are not
704 flowing along *any* path. These are the counts
705 that will still flow along the original path after
706 all path duplication is done by potentially multiple
707 calls to this routine.
708 (any other incoming edge counts are for a different jump threading
709 path that will be handled by a later call to this routine.)
710 To make this easier, start by recording all incoming edges that flow into
711 the current path in a bitmap. We could add up the path's incoming edge
712 counts here, but we still need to walk all the first bb's incoming edges
713 below to add up the counts of the other edges not included in this jump
714 threading path. */
715 struct el *next, *el;
716 bitmap in_edge_srcs = BITMAP_ALLOC (NULL);
717 for (el = rd->incoming_edges; el; el = next)
719 next = el->next;
720 bitmap_set_bit (in_edge_srcs, el->e->src->index);
722 edge ein;
723 edge_iterator ei;
724 FOR_EACH_EDGE (ein, ei, e->dest->preds)
726 vec<jump_thread_edge *> *ein_path = THREAD_PATH (ein);
727 /* Simply check the incoming edge src against the set captured above. */
728 if (ein_path
729 && bitmap_bit_p (in_edge_srcs, (*ein_path)[0]->e->src->index))
731 /* It is necessary but not sufficient that the last path edges
732 are identical. There may be different paths that share the
733 same last path edge in the case where the last edge has a nocopy
734 source block. */
735 gcc_assert (ein_path->last ()->e == elast);
736 path_in_count += ein->count;
737 path_in_freq += EDGE_FREQUENCY (ein);
739 else if (!ein_path)
741 /* Keep track of the incoming edges that are not on any jump-threading
742 path. These counts will still flow out of original path after all
743 jump threading is complete. */
744 nonpath_count += ein->count;
748 /* This is needed due to insane incoming frequencies. */
749 if (path_in_freq > BB_FREQ_MAX)
750 path_in_freq = BB_FREQ_MAX;
752 BITMAP_FREE (in_edge_srcs);
754 /* Now compute the fraction of the total count coming into the first
755 path bb that is from the current threading path. */
756 gcov_type total_count = e->dest->count;
757 /* Handle incoming profile insanities. */
758 if (total_count < path_in_count)
759 path_in_count = total_count;
760 int onpath_scale = GCOV_COMPUTE_SCALE (path_in_count, total_count);
762 /* Walk the entire path to do some more computation in order to estimate
763 how much of the path_in_count will flow out of the duplicated threading
764 path. In the non-joiner case this is straightforward (it should be
765 the same as path_in_count, although we will handle incoming profile
766 insanities by setting it equal to the minimum count along the path).
768 In the joiner case, we need to estimate how much of the path_in_count
769 will stay on the threading path after the joiner's conditional branch.
770 We don't really know for sure how much of the counts
771 associated with this path go to each successor of the joiner, but we'll
772 estimate based on the fraction of the total count coming into the path
773 bb was from the threading paths (computed above in onpath_scale).
774 Afterwards, we will need to do some fixup to account for other threading
775 paths and possible profile insanities.
777 In order to estimate the joiner case's counts we also need to update
778 nonpath_count with any additional counts coming into the path. Other
779 blocks along the path may have additional predecessors from outside
780 the path. */
781 gcov_type path_out_count = path_in_count;
782 gcov_type min_path_count = path_in_count;
783 for (unsigned int i = 1; i < path->length (); i++)
785 edge epath = (*path)[i]->e;
786 gcov_type cur_count = epath->count;
787 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
789 has_joiner = true;
790 cur_count = apply_probability (cur_count, onpath_scale);
792 /* In the joiner case we need to update nonpath_count for any edges
793 coming into the path that will contribute to the count flowing
794 into the path successor. */
795 if (has_joiner && epath != elast)
797 /* Look for other incoming edges after joiner. */
798 FOR_EACH_EDGE (ein, ei, epath->dest->preds)
800 if (ein != epath
801 /* Ignore in edges from blocks we have duplicated for a
802 threading path, which have duplicated edge counts until
803 they are redirected by an invocation of this routine. */
804 && !bitmap_bit_p (local_info->duplicate_blocks,
805 ein->src->index))
806 nonpath_count += ein->count;
809 if (cur_count < path_out_count)
810 path_out_count = cur_count;
811 if (epath->count < min_path_count)
812 min_path_count = epath->count;
815 /* We computed path_out_count above assuming that this path targeted
816 the joiner's on-path successor with the same likelihood as it
817 reached the joiner. However, other thread paths through the joiner
818 may take a different path through the normal copy source block
819 (i.e. they have a different elast), meaning that they do not
820 contribute any counts to this path's elast. As a result, it may
821 turn out that this path must have more count flowing to the on-path
822 successor of the joiner. Essentially, all of this path's elast
823 count must be contributed by this path and any nonpath counts
824 (since any path through the joiner with a different elast will not
825 include a copy of this elast in its duplicated path).
826 So ensure that this path's path_out_count is at least the
827 difference between elast->count and nonpath_count. Otherwise the edge
828 counts after threading will not be sane. */
829 if (has_joiner && path_out_count < elast->count - nonpath_count)
831 path_out_count = elast->count - nonpath_count;
832 /* But neither can we go above the minimum count along the path
833 we are duplicating. This can be an issue due to profile
834 insanities coming in to this pass. */
835 if (path_out_count > min_path_count)
836 path_out_count = min_path_count;
839 *path_in_count_ptr = path_in_count;
840 *path_out_count_ptr = path_out_count;
841 *path_in_freq_ptr = path_in_freq;
842 return has_joiner;
846 /* Update the counts and frequencies for both an original path
847 edge EPATH and its duplicate EDUP. The duplicate source block
848 will get a count/frequency of PATH_IN_COUNT and PATH_IN_FREQ,
849 and the duplicate edge EDUP will have a count of PATH_OUT_COUNT. */
850 static void
851 update_profile (edge epath, edge edup, gcov_type path_in_count,
852 gcov_type path_out_count, int path_in_freq)
855 /* First update the duplicated block's count / frequency. */
856 if (edup)
858 basic_block dup_block = edup->src;
859 gcc_assert (dup_block->count == 0);
860 gcc_assert (dup_block->frequency == 0);
861 dup_block->count = path_in_count;
862 dup_block->frequency = path_in_freq;
865 /* Now update the original block's count and frequency in the
866 opposite manner - remove the counts/freq that will flow
867 into the duplicated block. Handle underflow due to precision/
868 rounding issues. */
869 epath->src->count -= path_in_count;
870 if (epath->src->count < 0)
871 epath->src->count = 0;
872 epath->src->frequency -= path_in_freq;
873 if (epath->src->frequency < 0)
874 epath->src->frequency = 0;
876 /* Next update this path edge's original and duplicated counts. We know
877 that the duplicated path will have path_out_count flowing
878 out of it (in the joiner case this is the count along the duplicated path
879 out of the duplicated joiner). This count can then be removed from the
880 original path edge. */
881 if (edup)
882 edup->count = path_out_count;
883 epath->count -= path_out_count;
884 gcc_assert (epath->count >= 0);
888 /* The duplicate and original joiner blocks may end up with different
889 probabilities (different from both the original and from each other).
890 Recompute the probabilities here once we have updated the edge
891 counts and frequencies. */
893 static void
894 recompute_probabilities (basic_block bb)
896 edge esucc;
897 edge_iterator ei;
898 FOR_EACH_EDGE (esucc, ei, bb->succs)
900 if (!bb->count)
901 continue;
903 /* Prevent overflow computation due to insane profiles. */
904 if (esucc->count < bb->count)
905 esucc->probability = GCOV_COMPUTE_SCALE (esucc->count,
906 bb->count);
907 else
908 /* Can happen with missing/guessed probabilities, since we
909 may determine that more is flowing along duplicated
910 path than joiner succ probabilities allowed.
911 Counts and freqs will be insane after jump threading,
912 at least make sure probability is sane or we will
913 get a flow verification error.
914 Not much we can do to make counts/freqs sane without
915 redoing the profile estimation. */
916 esucc->probability = REG_BR_PROB_BASE;
921 /* Update the counts of the original and duplicated edges from a joiner
922 that go off path, given that we have already determined that the
923 duplicate joiner DUP_BB has incoming count PATH_IN_COUNT and
924 outgoing count along the path PATH_OUT_COUNT. The original (on-)path
925 edge from joiner is EPATH. */
927 static void
928 update_joiner_offpath_counts (edge epath, basic_block dup_bb,
929 gcov_type path_in_count,
930 gcov_type path_out_count)
932 /* Compute the count that currently flows off path from the joiner.
933 In other words, the total count of joiner's out edges other than
934 epath. Compute this by walking the successors instead of
935 subtracting epath's count from the joiner bb count, since there
936 are sometimes slight insanities where the total out edge count is
937 larger than the bb count (possibly due to rounding/truncation
938 errors). */
939 gcov_type total_orig_off_path_count = 0;
940 edge enonpath;
941 edge_iterator ei;
942 FOR_EACH_EDGE (enonpath, ei, epath->src->succs)
944 if (enonpath == epath)
945 continue;
946 total_orig_off_path_count += enonpath->count;
949 /* For the path that we are duplicating, the amount that will flow
950 off path from the duplicated joiner is the delta between the
951 path's cumulative in count and the portion of that count we
952 estimated above as flowing from the joiner along the duplicated
953 path. */
954 gcov_type total_dup_off_path_count = path_in_count - path_out_count;
956 /* Now do the actual updates of the off-path edges. */
957 FOR_EACH_EDGE (enonpath, ei, epath->src->succs)
959 /* Look for edges going off of the threading path. */
960 if (enonpath == epath)
961 continue;
963 /* Find the corresponding edge out of the duplicated joiner. */
964 edge enonpathdup = find_edge (dup_bb, enonpath->dest);
965 gcc_assert (enonpathdup);
967 /* We can't use the original probability of the joiner's out
968 edges, since the probabilities of the original branch
969 and the duplicated branches may vary after all threading is
970 complete. But apportion the duplicated joiner's off-path
971 total edge count computed earlier (total_dup_off_path_count)
972 among the duplicated off-path edges based on their original
973 ratio to the full off-path count (total_orig_off_path_count).
975 int scale = GCOV_COMPUTE_SCALE (enonpath->count,
976 total_orig_off_path_count);
977 /* Give the duplicated offpath edge a portion of the duplicated
978 total. */
979 enonpathdup->count = apply_scale (scale,
980 total_dup_off_path_count);
981 /* Now update the original offpath edge count, handling underflow
982 due to rounding errors. */
983 enonpath->count -= enonpathdup->count;
984 if (enonpath->count < 0)
985 enonpath->count = 0;
990 /* Check if the paths through RD all have estimated frequencies but zero
991 profile counts. This is more accurate than checking the entry block
992 for a zero profile count, since profile insanities sometimes creep in. */
994 static bool
995 estimated_freqs_path (struct redirection_data *rd)
997 edge e = rd->incoming_edges->e;
998 vec<jump_thread_edge *> *path = THREAD_PATH (e);
999 edge ein;
1000 edge_iterator ei;
1001 bool non_zero_freq = false;
1002 FOR_EACH_EDGE (ein, ei, e->dest->preds)
1004 if (ein->count)
1005 return false;
1006 non_zero_freq |= ein->src->frequency != 0;
1009 for (unsigned int i = 1; i < path->length (); i++)
1011 edge epath = (*path)[i]->e;
1012 if (epath->src->count)
1013 return false;
1014 non_zero_freq |= epath->src->frequency != 0;
1015 edge esucc;
1016 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1018 if (esucc->count)
1019 return false;
1020 non_zero_freq |= esucc->src->frequency != 0;
1023 return non_zero_freq;
1027 /* Invoked for routines that have guessed frequencies and no profile
1028 counts to record the block and edge frequencies for paths through RD
1029 in the profile count fields of those blocks and edges. This is because
1030 ssa_fix_duplicate_block_edges incrementally updates the block and
1031 edge counts as edges are redirected, and it is difficult to do that
1032 for edge frequencies which are computed on the fly from the source
1033 block frequency and probability. When a block frequency is updated
1034 its outgoing edge frequencies are affected and become difficult to
1035 adjust. */
1037 static void
1038 freqs_to_counts_path (struct redirection_data *rd)
1040 edge e = rd->incoming_edges->e;
1041 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1042 edge ein;
1043 edge_iterator ei;
1044 FOR_EACH_EDGE (ein, ei, e->dest->preds)
1046 /* Scale up the frequency by REG_BR_PROB_BASE, to avoid rounding
1047 errors applying the probability when the frequencies are very
1048 small. */
1049 ein->count = apply_probability (ein->src->frequency * REG_BR_PROB_BASE,
1050 ein->probability);
1053 for (unsigned int i = 1; i < path->length (); i++)
1055 edge epath = (*path)[i]->e;
1056 edge esucc;
1057 /* Scale up the frequency by REG_BR_PROB_BASE, to avoid rounding
1058 errors applying the edge probability when the frequencies are very
1059 small. */
1060 epath->src->count = epath->src->frequency * REG_BR_PROB_BASE;
1061 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1062 esucc->count = apply_probability (esucc->src->count,
1063 esucc->probability);
1068 /* For routines that have guessed frequencies and no profile counts, where we
1069 used freqs_to_counts_path to record block and edge frequencies for paths
1070 through RD, we clear the counts after completing all updates for RD.
1071 The updates in ssa_fix_duplicate_block_edges are based off the count fields,
1072 but the block frequencies and edge probabilities were updated as well,
1073 so we can simply clear the count fields. */
1075 static void
1076 clear_counts_path (struct redirection_data *rd)
1078 edge e = rd->incoming_edges->e;
1079 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1080 edge ein, esucc;
1081 edge_iterator ei;
1082 FOR_EACH_EDGE (ein, ei, e->dest->preds)
1083 ein->count = 0;
1085 /* First clear counts along original path. */
1086 for (unsigned int i = 1; i < path->length (); i++)
1088 edge epath = (*path)[i]->e;
1089 FOR_EACH_EDGE (esucc, ei, epath->src->succs)
1090 esucc->count = 0;
1091 epath->src->count = 0;
1093 /* Also need to clear the counts along duplicated path. */
1094 for (unsigned int i = 0; i < 2; i++)
1096 basic_block dup = rd->dup_blocks[i];
1097 if (!dup)
1098 continue;
1099 FOR_EACH_EDGE (esucc, ei, dup->succs)
1100 esucc->count = 0;
1101 dup->count = 0;
1105 /* Wire up the outgoing edges from the duplicate blocks and
1106 update any PHIs as needed. Also update the profile counts
1107 on the original and duplicate blocks and edges. */
1108 void
1109 ssa_fix_duplicate_block_edges (struct redirection_data *rd,
1110 ssa_local_info_t *local_info)
1112 bool multi_incomings = (rd->incoming_edges->next != NULL);
1113 edge e = rd->incoming_edges->e;
1114 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1115 edge elast = path->last ()->e;
1116 gcov_type path_in_count = 0;
1117 gcov_type path_out_count = 0;
1118 int path_in_freq = 0;
1120 /* This routine updates profile counts, frequencies, and probabilities
1121 incrementally. Since it is difficult to do the incremental updates
1122 using frequencies/probabilities alone, for routines without profile
1123 data we first take a snapshot of the existing block and edge frequencies
1124 by copying them into the empty profile count fields. These counts are
1125 then used to do the incremental updates, and cleared at the end of this
1126 routine. If the function is marked as having a profile, we still check
1127 to see if the paths through RD are using estimated frequencies because
1128 the routine had zero profile counts. */
1129 bool do_freqs_to_counts = (profile_status_for_fn (cfun) != PROFILE_READ
1130 || estimated_freqs_path (rd));
1131 if (do_freqs_to_counts)
1132 freqs_to_counts_path (rd);
1134 /* First determine how much profile count to move from original
1135 path to the duplicate path. This is tricky in the presence of
1136 a joiner (see comments for compute_path_counts), where some portion
1137 of the path's counts will flow off-path from the joiner. In the
1138 non-joiner case the path_in_count and path_out_count should be the
1139 same. */
1140 bool has_joiner = compute_path_counts (rd, local_info,
1141 &path_in_count, &path_out_count,
1142 &path_in_freq);
1144 int cur_path_freq = path_in_freq;
1145 for (unsigned int count = 0, i = 1; i < path->length (); i++)
1147 edge epath = (*path)[i]->e;
1149 /* If we were threading through an joiner block, then we want
1150 to keep its control statement and redirect an outgoing edge.
1151 Else we want to remove the control statement & edges, then create
1152 a new outgoing edge. In both cases we may need to update PHIs. */
1153 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1155 edge victim;
1156 edge e2;
1158 gcc_assert (has_joiner);
1160 /* This updates the PHIs at the destination of the duplicate
1161 block. Pass 0 instead of i if we are threading a path which
1162 has multiple incoming edges. */
1163 update_destination_phis (local_info->bb, rd->dup_blocks[count],
1164 path, multi_incomings ? 0 : i);
1166 /* Find the edge from the duplicate block to the block we're
1167 threading through. That's the edge we want to redirect. */
1168 victim = find_edge (rd->dup_blocks[count], (*path)[i]->e->dest);
1170 /* If there are no remaining blocks on the path to duplicate,
1171 then redirect VICTIM to the final destination of the jump
1172 threading path. */
1173 if (!any_remaining_duplicated_blocks (path, i))
1175 e2 = redirect_edge_and_branch (victim, elast->dest);
1176 /* If we redirected the edge, then we need to copy PHI arguments
1177 at the target. If the edge already existed (e2 != victim
1178 case), then the PHIs in the target already have the correct
1179 arguments. */
1180 if (e2 == victim)
1181 copy_phi_args (e2->dest, elast, e2,
1182 path, multi_incomings ? 0 : i);
1184 else
1186 /* Redirect VICTIM to the next duplicated block in the path. */
1187 e2 = redirect_edge_and_branch (victim, rd->dup_blocks[count + 1]);
1189 /* We need to update the PHIs in the next duplicated block. We
1190 want the new PHI args to have the same value as they had
1191 in the source of the next duplicate block.
1193 Thus, we need to know which edge we traversed into the
1194 source of the duplicate. Furthermore, we may have
1195 traversed many edges to reach the source of the duplicate.
1197 Walk through the path starting at element I until we
1198 hit an edge marked with EDGE_COPY_SRC_BLOCK. We want
1199 the edge from the prior element. */
1200 for (unsigned int j = i + 1; j < path->length (); j++)
1202 if ((*path)[j]->type == EDGE_COPY_SRC_BLOCK)
1204 copy_phi_arg_into_existing_phi ((*path)[j - 1]->e, e2);
1205 break;
1210 /* Update the counts and frequency of both the original block
1211 and path edge, and the duplicates. The path duplicate's
1212 incoming count and frequency are the totals for all edges
1213 incoming to this jump threading path computed earlier.
1214 And we know that the duplicated path will have path_out_count
1215 flowing out of it (i.e. along the duplicated path out of the
1216 duplicated joiner). */
1217 update_profile (epath, e2, path_in_count, path_out_count,
1218 path_in_freq);
1220 /* Next we need to update the counts of the original and duplicated
1221 edges from the joiner that go off path. */
1222 update_joiner_offpath_counts (epath, e2->src, path_in_count,
1223 path_out_count);
1225 /* Finally, we need to set the probabilities on the duplicated
1226 edges out of the duplicated joiner (e2->src). The probabilities
1227 along the original path will all be updated below after we finish
1228 processing the whole path. */
1229 recompute_probabilities (e2->src);
1231 /* Record the frequency flowing to the downstream duplicated
1232 path blocks. */
1233 cur_path_freq = EDGE_FREQUENCY (e2);
1235 else if ((*path)[i]->type == EDGE_COPY_SRC_BLOCK)
1237 remove_ctrl_stmt_and_useless_edges (rd->dup_blocks[count], NULL);
1238 create_edge_and_update_destination_phis (rd, rd->dup_blocks[count],
1239 multi_incomings ? 0 : i);
1240 if (count == 1)
1241 single_succ_edge (rd->dup_blocks[1])->aux = NULL;
1243 /* Update the counts and frequency of both the original block
1244 and path edge, and the duplicates. Since we are now after
1245 any joiner that may have existed on the path, the count
1246 flowing along the duplicated threaded path is path_out_count.
1247 If we didn't have a joiner, then cur_path_freq was the sum
1248 of the total frequencies along all incoming edges to the
1249 thread path (path_in_freq). If we had a joiner, it would have
1250 been updated at the end of that handling to the edge frequency
1251 along the duplicated joiner path edge. */
1252 update_profile (epath, EDGE_SUCC (rd->dup_blocks[count], 0),
1253 path_out_count, path_out_count,
1254 cur_path_freq);
1256 else
1258 /* No copy case. In this case we don't have an equivalent block
1259 on the duplicated thread path to update, but we do need
1260 to remove the portion of the counts/freqs that were moved
1261 to the duplicated path from the counts/freqs flowing through
1262 this block on the original path. Since all the no-copy edges
1263 are after any joiner, the removed count is the same as
1264 path_out_count.
1266 If we didn't have a joiner, then cur_path_freq was the sum
1267 of the total frequencies along all incoming edges to the
1268 thread path (path_in_freq). If we had a joiner, it would have
1269 been updated at the end of that handling to the edge frequency
1270 along the duplicated joiner path edge. */
1271 update_profile (epath, NULL, path_out_count, path_out_count,
1272 cur_path_freq);
1275 /* Increment the index into the duplicated path when we processed
1276 a duplicated block. */
1277 if ((*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK
1278 || (*path)[i]->type == EDGE_COPY_SRC_BLOCK)
1280 count++;
1284 /* Now walk orig blocks and update their probabilities, since the
1285 counts and freqs should be updated properly by above loop. */
1286 for (unsigned int i = 1; i < path->length (); i++)
1288 edge epath = (*path)[i]->e;
1289 recompute_probabilities (epath->src);
1292 /* Done with all profile and frequency updates, clear counts if they
1293 were copied. */
1294 if (do_freqs_to_counts)
1295 clear_counts_path (rd);
1298 /* Hash table traversal callback routine to create duplicate blocks. */
1301 ssa_create_duplicates (struct redirection_data **slot,
1302 ssa_local_info_t *local_info)
1304 struct redirection_data *rd = *slot;
1306 /* The second duplicated block in a jump threading path is specific
1307 to the path. So it gets stored in RD rather than in LOCAL_DATA.
1309 Each time we're called, we have to look through the path and see
1310 if a second block needs to be duplicated.
1312 Note the search starts with the third edge on the path. The first
1313 edge is the incoming edge, the second edge always has its source
1314 duplicated. Thus we start our search with the third edge. */
1315 vec<jump_thread_edge *> *path = rd->path;
1316 for (unsigned int i = 2; i < path->length (); i++)
1318 if ((*path)[i]->type == EDGE_COPY_SRC_BLOCK
1319 || (*path)[i]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1321 create_block_for_threading ((*path)[i]->e->src, rd, 1,
1322 &local_info->duplicate_blocks);
1323 break;
1327 /* Create a template block if we have not done so already. Otherwise
1328 use the template to create a new block. */
1329 if (local_info->template_block == NULL)
1331 create_block_for_threading ((*path)[1]->e->src, rd, 0,
1332 &local_info->duplicate_blocks);
1333 local_info->template_block = rd->dup_blocks[0];
1335 /* We do not create any outgoing edges for the template. We will
1336 take care of that in a later traversal. That way we do not
1337 create edges that are going to just be deleted. */
1339 else
1341 create_block_for_threading (local_info->template_block, rd, 0,
1342 &local_info->duplicate_blocks);
1344 /* Go ahead and wire up outgoing edges and update PHIs for the duplicate
1345 block. */
1346 ssa_fix_duplicate_block_edges (rd, local_info);
1349 /* Keep walking the hash table. */
1350 return 1;
1353 /* We did not create any outgoing edges for the template block during
1354 block creation. This hash table traversal callback creates the
1355 outgoing edge for the template block. */
1357 inline int
1358 ssa_fixup_template_block (struct redirection_data **slot,
1359 ssa_local_info_t *local_info)
1361 struct redirection_data *rd = *slot;
1363 /* If this is the template block halt the traversal after updating
1364 it appropriately.
1366 If we were threading through an joiner block, then we want
1367 to keep its control statement and redirect an outgoing edge.
1368 Else we want to remove the control statement & edges, then create
1369 a new outgoing edge. In both cases we may need to update PHIs. */
1370 if (rd->dup_blocks[0] && rd->dup_blocks[0] == local_info->template_block)
1372 ssa_fix_duplicate_block_edges (rd, local_info);
1373 return 0;
1376 return 1;
1379 /* Hash table traversal callback to redirect each incoming edge
1380 associated with this hash table element to its new destination. */
1383 ssa_redirect_edges (struct redirection_data **slot,
1384 ssa_local_info_t *local_info)
1386 struct redirection_data *rd = *slot;
1387 struct el *next, *el;
1389 /* Walk over all the incoming edges associated with this hash table
1390 entry. */
1391 for (el = rd->incoming_edges; el; el = next)
1393 edge e = el->e;
1394 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1396 /* Go ahead and free this element from the list. Doing this now
1397 avoids the need for another list walk when we destroy the hash
1398 table. */
1399 next = el->next;
1400 free (el);
1402 thread_stats.num_threaded_edges++;
1404 if (rd->dup_blocks[0])
1406 edge e2;
1408 if (dump_file && (dump_flags & TDF_DETAILS))
1409 fprintf (dump_file, " Threaded jump %d --> %d to %d\n",
1410 e->src->index, e->dest->index, rd->dup_blocks[0]->index);
1412 /* Redirect the incoming edge (possibly to the joiner block) to the
1413 appropriate duplicate block. */
1414 e2 = redirect_edge_and_branch (e, rd->dup_blocks[0]);
1415 gcc_assert (e == e2);
1416 flush_pending_stmts (e2);
1419 /* Go ahead and clear E->aux. It's not needed anymore and failure
1420 to clear it will cause all kinds of unpleasant problems later. */
1421 delete_jump_thread_path (path);
1422 e->aux = NULL;
1426 /* Indicate that we actually threaded one or more jumps. */
1427 if (rd->incoming_edges)
1428 local_info->jumps_threaded = true;
1430 return 1;
1433 /* Return true if this block has no executable statements other than
1434 a simple ctrl flow instruction. When the number of outgoing edges
1435 is one, this is equivalent to a "forwarder" block. */
1437 static bool
1438 redirection_block_p (basic_block bb)
1440 gimple_stmt_iterator gsi;
1442 /* Advance to the first executable statement. */
1443 gsi = gsi_start_bb (bb);
1444 while (!gsi_end_p (gsi)
1445 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL
1446 || is_gimple_debug (gsi_stmt (gsi))
1447 || gimple_nop_p (gsi_stmt (gsi))
1448 || gimple_clobber_p (gsi_stmt (gsi))))
1449 gsi_next (&gsi);
1451 /* Check if this is an empty block. */
1452 if (gsi_end_p (gsi))
1453 return true;
1455 /* Test that we've reached the terminating control statement. */
1456 return gsi_stmt (gsi)
1457 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_COND
1458 || gimple_code (gsi_stmt (gsi)) == GIMPLE_GOTO
1459 || gimple_code (gsi_stmt (gsi)) == GIMPLE_SWITCH);
1462 /* BB is a block which ends with a COND_EXPR or SWITCH_EXPR and when BB
1463 is reached via one or more specific incoming edges, we know which
1464 outgoing edge from BB will be traversed.
1466 We want to redirect those incoming edges to the target of the
1467 appropriate outgoing edge. Doing so avoids a conditional branch
1468 and may expose new optimization opportunities. Note that we have
1469 to update dominator tree and SSA graph after such changes.
1471 The key to keeping the SSA graph update manageable is to duplicate
1472 the side effects occurring in BB so that those side effects still
1473 occur on the paths which bypass BB after redirecting edges.
1475 We accomplish this by creating duplicates of BB and arranging for
1476 the duplicates to unconditionally pass control to one specific
1477 successor of BB. We then revector the incoming edges into BB to
1478 the appropriate duplicate of BB.
1480 If NOLOOP_ONLY is true, we only perform the threading as long as it
1481 does not affect the structure of the loops in a nontrivial way.
1483 If JOINERS is true, then thread through joiner blocks as well. */
1485 static bool
1486 thread_block_1 (basic_block bb, bool noloop_only, bool joiners)
1488 /* E is an incoming edge into BB that we may or may not want to
1489 redirect to a duplicate of BB. */
1490 edge e, e2;
1491 edge_iterator ei;
1492 ssa_local_info_t local_info;
1494 local_info.duplicate_blocks = BITMAP_ALLOC (NULL);
1496 /* To avoid scanning a linear array for the element we need we instead
1497 use a hash table. For normal code there should be no noticeable
1498 difference. However, if we have a block with a large number of
1499 incoming and outgoing edges such linear searches can get expensive. */
1500 redirection_data
1501 = new hash_table<struct redirection_data> (EDGE_COUNT (bb->succs));
1503 /* Record each unique threaded destination into a hash table for
1504 efficient lookups. */
1505 FOR_EACH_EDGE (e, ei, bb->preds)
1507 if (e->aux == NULL)
1508 continue;
1510 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1512 if (((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK && !joiners)
1513 || ((*path)[1]->type == EDGE_COPY_SRC_BLOCK && joiners))
1514 continue;
1516 e2 = path->last ()->e;
1517 if (!e2 || noloop_only)
1519 /* If NOLOOP_ONLY is true, we only allow threading through the
1520 header of a loop to exit edges. */
1522 /* One case occurs when there was loop header buried in a jump
1523 threading path that crosses loop boundaries. We do not try
1524 and thread this elsewhere, so just cancel the jump threading
1525 request by clearing the AUX field now. */
1526 if ((bb->loop_father != e2->src->loop_father
1527 && !loop_exit_edge_p (e2->src->loop_father, e2))
1528 || (e2->src->loop_father != e2->dest->loop_father
1529 && !loop_exit_edge_p (e2->src->loop_father, e2)))
1531 /* Since this case is not handled by our special code
1532 to thread through a loop header, we must explicitly
1533 cancel the threading request here. */
1534 delete_jump_thread_path (path);
1535 e->aux = NULL;
1536 continue;
1539 /* Another case occurs when trying to thread through our
1540 own loop header, possibly from inside the loop. We will
1541 thread these later. */
1542 unsigned int i;
1543 for (i = 1; i < path->length (); i++)
1545 if ((*path)[i]->e->src == bb->loop_father->header
1546 && (!loop_exit_edge_p (bb->loop_father, e2)
1547 || (*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK))
1548 break;
1551 if (i != path->length ())
1552 continue;
1555 /* Insert the outgoing edge into the hash table if it is not
1556 already in the hash table. */
1557 lookup_redirection_data (e, INSERT);
1560 /* We do not update dominance info. */
1561 free_dominance_info (CDI_DOMINATORS);
1563 /* We know we only thread through the loop header to loop exits.
1564 Let the basic block duplication hook know we are not creating
1565 a multiple entry loop. */
1566 if (noloop_only
1567 && bb == bb->loop_father->header)
1568 set_loop_copy (bb->loop_father, loop_outer (bb->loop_father));
1570 /* Now create duplicates of BB.
1572 Note that for a block with a high outgoing degree we can waste
1573 a lot of time and memory creating and destroying useless edges.
1575 So we first duplicate BB and remove the control structure at the
1576 tail of the duplicate as well as all outgoing edges from the
1577 duplicate. We then use that duplicate block as a template for
1578 the rest of the duplicates. */
1579 local_info.template_block = NULL;
1580 local_info.bb = bb;
1581 local_info.jumps_threaded = false;
1582 redirection_data->traverse <ssa_local_info_t *, ssa_create_duplicates>
1583 (&local_info);
1585 /* The template does not have an outgoing edge. Create that outgoing
1586 edge and update PHI nodes as the edge's target as necessary.
1588 We do this after creating all the duplicates to avoid creating
1589 unnecessary edges. */
1590 redirection_data->traverse <ssa_local_info_t *, ssa_fixup_template_block>
1591 (&local_info);
1593 /* The hash table traversals above created the duplicate blocks (and the
1594 statements within the duplicate blocks). This loop creates PHI nodes for
1595 the duplicated blocks and redirects the incoming edges into BB to reach
1596 the duplicates of BB. */
1597 redirection_data->traverse <ssa_local_info_t *, ssa_redirect_edges>
1598 (&local_info);
1600 /* Done with this block. Clear REDIRECTION_DATA. */
1601 delete redirection_data;
1602 redirection_data = NULL;
1604 if (noloop_only
1605 && bb == bb->loop_father->header)
1606 set_loop_copy (bb->loop_father, NULL);
1608 BITMAP_FREE (local_info.duplicate_blocks);
1609 local_info.duplicate_blocks = NULL;
1611 /* Indicate to our caller whether or not any jumps were threaded. */
1612 return local_info.jumps_threaded;
1615 /* Wrapper for thread_block_1 so that we can first handle jump
1616 thread paths which do not involve copying joiner blocks, then
1617 handle jump thread paths which have joiner blocks.
1619 By doing things this way we can be as aggressive as possible and
1620 not worry that copying a joiner block will create a jump threading
1621 opportunity. */
1623 static bool
1624 thread_block (basic_block bb, bool noloop_only)
1626 bool retval;
1627 retval = thread_block_1 (bb, noloop_only, false);
1628 retval |= thread_block_1 (bb, noloop_only, true);
1629 return retval;
1632 /* Callback for dfs_enumerate_from. Returns true if BB is different
1633 from STOP and DBDS_CE_STOP. */
1635 static basic_block dbds_ce_stop;
1636 static bool
1637 dbds_continue_enumeration_p (const_basic_block bb, const void *stop)
1639 return (bb != (const_basic_block) stop
1640 && bb != dbds_ce_stop);
1643 /* Evaluates the dominance relationship of latch of the LOOP and BB, and
1644 returns the state. */
1646 enum bb_dom_status
1648 /* BB does not dominate latch of the LOOP. */
1649 DOMST_NONDOMINATING,
1650 /* The LOOP is broken (there is no path from the header to its latch. */
1651 DOMST_LOOP_BROKEN,
1652 /* BB dominates the latch of the LOOP. */
1653 DOMST_DOMINATING
1656 static enum bb_dom_status
1657 determine_bb_domination_status (struct loop *loop, basic_block bb)
1659 basic_block *bblocks;
1660 unsigned nblocks, i;
1661 bool bb_reachable = false;
1662 edge_iterator ei;
1663 edge e;
1665 /* This function assumes BB is a successor of LOOP->header.
1666 If that is not the case return DOMST_NONDOMINATING which
1667 is always safe. */
1669 bool ok = false;
1671 FOR_EACH_EDGE (e, ei, bb->preds)
1673 if (e->src == loop->header)
1675 ok = true;
1676 break;
1680 if (!ok)
1681 return DOMST_NONDOMINATING;
1684 if (bb == loop->latch)
1685 return DOMST_DOMINATING;
1687 /* Check that BB dominates LOOP->latch, and that it is back-reachable
1688 from it. */
1690 bblocks = XCNEWVEC (basic_block, loop->num_nodes);
1691 dbds_ce_stop = loop->header;
1692 nblocks = dfs_enumerate_from (loop->latch, 1, dbds_continue_enumeration_p,
1693 bblocks, loop->num_nodes, bb);
1694 for (i = 0; i < nblocks; i++)
1695 FOR_EACH_EDGE (e, ei, bblocks[i]->preds)
1697 if (e->src == loop->header)
1699 free (bblocks);
1700 return DOMST_NONDOMINATING;
1702 if (e->src == bb)
1703 bb_reachable = true;
1706 free (bblocks);
1707 return (bb_reachable ? DOMST_DOMINATING : DOMST_LOOP_BROKEN);
1710 /* Thread jumps through the header of LOOP. Returns true if cfg changes.
1711 If MAY_PEEL_LOOP_HEADERS is false, we avoid threading from entry edges
1712 to the inside of the loop. */
1714 static bool
1715 thread_through_loop_header (struct loop *loop, bool may_peel_loop_headers)
1717 basic_block header = loop->header;
1718 edge e, tgt_edge, latch = loop_latch_edge (loop);
1719 edge_iterator ei;
1720 basic_block tgt_bb, atgt_bb;
1721 enum bb_dom_status domst;
1723 /* We have already threaded through headers to exits, so all the threading
1724 requests now are to the inside of the loop. We need to avoid creating
1725 irreducible regions (i.e., loops with more than one entry block), and
1726 also loop with several latch edges, or new subloops of the loop (although
1727 there are cases where it might be appropriate, it is difficult to decide,
1728 and doing it wrongly may confuse other optimizers).
1730 We could handle more general cases here. However, the intention is to
1731 preserve some information about the loop, which is impossible if its
1732 structure changes significantly, in a way that is not well understood.
1733 Thus we only handle few important special cases, in which also updating
1734 of the loop-carried information should be feasible:
1736 1) Propagation of latch edge to a block that dominates the latch block
1737 of a loop. This aims to handle the following idiom:
1739 first = 1;
1740 while (1)
1742 if (first)
1743 initialize;
1744 first = 0;
1745 body;
1748 After threading the latch edge, this becomes
1750 first = 1;
1751 if (first)
1752 initialize;
1753 while (1)
1755 first = 0;
1756 body;
1759 The original header of the loop is moved out of it, and we may thread
1760 the remaining edges through it without further constraints.
1762 2) All entry edges are propagated to a single basic block that dominates
1763 the latch block of the loop. This aims to handle the following idiom
1764 (normally created for "for" loops):
1766 i = 0;
1767 while (1)
1769 if (i >= 100)
1770 break;
1771 body;
1772 i++;
1775 This becomes
1777 i = 0;
1778 while (1)
1780 body;
1781 i++;
1782 if (i >= 100)
1783 break;
1787 /* Threading through the header won't improve the code if the header has just
1788 one successor. */
1789 if (single_succ_p (header))
1790 goto fail;
1792 if (!may_peel_loop_headers && !redirection_block_p (loop->header))
1793 goto fail;
1794 else
1796 tgt_bb = NULL;
1797 tgt_edge = NULL;
1798 FOR_EACH_EDGE (e, ei, header->preds)
1800 if (!e->aux)
1802 if (e == latch)
1803 continue;
1805 /* If latch is not threaded, and there is a header
1806 edge that is not threaded, we would create loop
1807 with multiple entries. */
1808 goto fail;
1811 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1813 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1814 goto fail;
1815 tgt_edge = (*path)[1]->e;
1816 atgt_bb = tgt_edge->dest;
1817 if (!tgt_bb)
1818 tgt_bb = atgt_bb;
1819 /* Two targets of threading would make us create loop
1820 with multiple entries. */
1821 else if (tgt_bb != atgt_bb)
1822 goto fail;
1825 if (!tgt_bb)
1827 /* There are no threading requests. */
1828 return false;
1831 /* Redirecting to empty loop latch is useless. */
1832 if (tgt_bb == loop->latch
1833 && empty_block_p (loop->latch))
1834 goto fail;
1837 /* The target block must dominate the loop latch, otherwise we would be
1838 creating a subloop. */
1839 domst = determine_bb_domination_status (loop, tgt_bb);
1840 if (domst == DOMST_NONDOMINATING)
1841 goto fail;
1842 if (domst == DOMST_LOOP_BROKEN)
1844 /* If the loop ceased to exist, mark it as such, and thread through its
1845 original header. */
1846 mark_loop_for_removal (loop);
1847 return thread_block (header, false);
1850 if (tgt_bb->loop_father->header == tgt_bb)
1852 /* If the target of the threading is a header of a subloop, we need
1853 to create a preheader for it, so that the headers of the two loops
1854 do not merge. */
1855 if (EDGE_COUNT (tgt_bb->preds) > 2)
1857 tgt_bb = create_preheader (tgt_bb->loop_father, 0);
1858 gcc_assert (tgt_bb != NULL);
1860 else
1861 tgt_bb = split_edge (tgt_edge);
1864 basic_block new_preheader;
1866 /* Now consider the case entry edges are redirected to the new entry
1867 block. Remember one entry edge, so that we can find the new
1868 preheader (its destination after threading). */
1869 FOR_EACH_EDGE (e, ei, header->preds)
1871 if (e->aux)
1872 break;
1875 /* The duplicate of the header is the new preheader of the loop. Ensure
1876 that it is placed correctly in the loop hierarchy. */
1877 set_loop_copy (loop, loop_outer (loop));
1879 thread_block (header, false);
1880 set_loop_copy (loop, NULL);
1881 new_preheader = e->dest;
1883 /* Create the new latch block. This is always necessary, as the latch
1884 must have only a single successor, but the original header had at
1885 least two successors. */
1886 loop->latch = NULL;
1887 mfb_kj_edge = single_succ_edge (new_preheader);
1888 loop->header = mfb_kj_edge->dest;
1889 latch = make_forwarder_block (tgt_bb, mfb_keep_just, NULL);
1890 loop->header = latch->dest;
1891 loop->latch = latch->src;
1892 return true;
1894 fail:
1895 /* We failed to thread anything. Cancel the requests. */
1896 FOR_EACH_EDGE (e, ei, header->preds)
1898 vec<jump_thread_edge *> *path = THREAD_PATH (e);
1900 if (path)
1902 delete_jump_thread_path (path);
1903 e->aux = NULL;
1906 return false;
1909 /* E1 and E2 are edges into the same basic block. Return TRUE if the
1910 PHI arguments associated with those edges are equal or there are no
1911 PHI arguments, otherwise return FALSE. */
1913 static bool
1914 phi_args_equal_on_edges (edge e1, edge e2)
1916 gphi_iterator gsi;
1917 int indx1 = e1->dest_idx;
1918 int indx2 = e2->dest_idx;
1920 for (gsi = gsi_start_phis (e1->dest); !gsi_end_p (gsi); gsi_next (&gsi))
1922 gphi *phi = gsi.phi ();
1924 if (!operand_equal_p (gimple_phi_arg_def (phi, indx1),
1925 gimple_phi_arg_def (phi, indx2), 0))
1926 return false;
1928 return true;
1931 /* Walk through the registered jump threads and convert them into a
1932 form convenient for this pass.
1934 Any block which has incoming edges threaded to outgoing edges
1935 will have its entry in THREADED_BLOCK set.
1937 Any threaded edge will have its new outgoing edge stored in the
1938 original edge's AUX field.
1940 This form avoids the need to walk all the edges in the CFG to
1941 discover blocks which need processing and avoids unnecessary
1942 hash table lookups to map from threaded edge to new target. */
1944 static void
1945 mark_threaded_blocks (bitmap threaded_blocks)
1947 unsigned int i;
1948 bitmap_iterator bi;
1949 bitmap tmp = BITMAP_ALLOC (NULL);
1950 basic_block bb;
1951 edge e;
1952 edge_iterator ei;
1954 /* It is possible to have jump threads in which one is a subpath
1955 of the other. ie, (A, B), (B, C), (C, D) where B is a joiner
1956 block and (B, C), (C, D) where no joiner block exists.
1958 When this occurs ignore the jump thread request with the joiner
1959 block. It's totally subsumed by the simpler jump thread request.
1961 This results in less block copying, simpler CFGs. More importantly,
1962 when we duplicate the joiner block, B, in this case we will create
1963 a new threading opportunity that we wouldn't be able to optimize
1964 until the next jump threading iteration.
1966 So first convert the jump thread requests which do not require a
1967 joiner block. */
1968 for (i = 0; i < paths.length (); i++)
1970 vec<jump_thread_edge *> *path = paths[i];
1972 if ((*path)[1]->type != EDGE_COPY_SRC_JOINER_BLOCK)
1974 edge e = (*path)[0]->e;
1975 e->aux = (void *)path;
1976 bitmap_set_bit (tmp, e->dest->index);
1980 /* Now iterate again, converting cases where we want to thread
1981 through a joiner block, but only if no other edge on the path
1982 already has a jump thread attached to it. We do this in two passes,
1983 to avoid situations where the order in the paths vec can hide overlapping
1984 threads (the path is recorded on the incoming edge, so we would miss
1985 cases where the second path starts at a downstream edge on the same
1986 path). First record all joiner paths, deleting any in the unexpected
1987 case where there is already a path for that incoming edge. */
1988 for (i = 0; i < paths.length ();)
1990 vec<jump_thread_edge *> *path = paths[i];
1992 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK)
1994 /* Attach the path to the starting edge if none is yet recorded. */
1995 if ((*path)[0]->e->aux == NULL)
1997 (*path)[0]->e->aux = path;
1998 i++;
2000 else
2002 paths.unordered_remove (i);
2003 if (dump_file && (dump_flags & TDF_DETAILS))
2004 dump_jump_thread_path (dump_file, *path, false);
2005 delete_jump_thread_path (path);
2008 else
2010 i++;
2014 /* Second, look for paths that have any other jump thread attached to
2015 them, and either finish converting them or cancel them. */
2016 for (i = 0; i < paths.length ();)
2018 vec<jump_thread_edge *> *path = paths[i];
2019 edge e = (*path)[0]->e;
2021 if ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK && e->aux == path)
2023 unsigned int j;
2024 for (j = 1; j < path->length (); j++)
2025 if ((*path)[j]->e->aux != NULL)
2026 break;
2028 /* If we iterated through the entire path without exiting the loop,
2029 then we are good to go, record it. */
2030 if (j == path->length ())
2032 bitmap_set_bit (tmp, e->dest->index);
2033 i++;
2035 else
2037 e->aux = NULL;
2038 paths.unordered_remove (i);
2039 if (dump_file && (dump_flags & TDF_DETAILS))
2040 dump_jump_thread_path (dump_file, *path, false);
2041 delete_jump_thread_path (path);
2044 else
2046 i++;
2050 /* If optimizing for size, only thread through block if we don't have
2051 to duplicate it or it's an otherwise empty redirection block. */
2052 if (optimize_function_for_size_p (cfun))
2054 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2056 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2057 if (EDGE_COUNT (bb->preds) > 1
2058 && !redirection_block_p (bb))
2060 FOR_EACH_EDGE (e, ei, bb->preds)
2062 if (e->aux)
2064 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2065 delete_jump_thread_path (path);
2066 e->aux = NULL;
2070 else
2071 bitmap_set_bit (threaded_blocks, i);
2074 else
2075 bitmap_copy (threaded_blocks, tmp);
2077 /* Look for jump threading paths which cross multiple loop headers.
2079 The code to thread through loop headers will change the CFG in ways
2080 that break assumptions made by the loop optimization code.
2082 We don't want to blindly cancel the requests. We can instead do better
2083 by trimming off the end of the jump thread path. */
2084 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2086 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
2087 FOR_EACH_EDGE (e, ei, bb->preds)
2089 if (e->aux)
2091 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2093 for (unsigned int i = 0, crossed_headers = 0;
2094 i < path->length ();
2095 i++)
2097 basic_block dest = (*path)[i]->e->dest;
2098 crossed_headers += (dest == dest->loop_father->header);
2099 if (crossed_headers > 1)
2101 /* Trim from entry I onwards. */
2102 for (unsigned int j = i; j < path->length (); j++)
2103 delete (*path)[j];
2104 path->truncate (i);
2106 /* Now that we've truncated the path, make sure
2107 what's left is still valid. We need at least
2108 two edges on the path and the last edge can not
2109 be a joiner. This should never happen, but let's
2110 be safe. */
2111 if (path->length () < 2
2112 || (path->last ()->type
2113 == EDGE_COPY_SRC_JOINER_BLOCK))
2115 delete_jump_thread_path (path);
2116 e->aux = NULL;
2118 break;
2125 /* If we have a joiner block (J) which has two successors S1 and S2 and
2126 we are threading though S1 and the final destination of the thread
2127 is S2, then we must verify that any PHI nodes in S2 have the same
2128 PHI arguments for the edge J->S2 and J->S1->...->S2.
2130 We used to detect this prior to registering the jump thread, but
2131 that prohibits propagation of edge equivalences into non-dominated
2132 PHI nodes as the equivalency test might occur before propagation.
2134 This must also occur after we truncate any jump threading paths
2135 as this scenario may only show up after truncation.
2137 This works for now, but will need improvement as part of the FSA
2138 optimization.
2140 Note since we've moved the thread request data to the edges,
2141 we have to iterate on those rather than the threaded_edges vector. */
2142 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2144 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2145 FOR_EACH_EDGE (e, ei, bb->preds)
2147 if (e->aux)
2149 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2150 bool have_joiner = ((*path)[1]->type == EDGE_COPY_SRC_JOINER_BLOCK);
2152 if (have_joiner)
2154 basic_block joiner = e->dest;
2155 edge final_edge = path->last ()->e;
2156 basic_block final_dest = final_edge->dest;
2157 edge e2 = find_edge (joiner, final_dest);
2159 if (e2 && !phi_args_equal_on_edges (e2, final_edge))
2161 delete_jump_thread_path (path);
2162 e->aux = NULL;
2169 BITMAP_FREE (tmp);
2173 /* Verify that the REGION is a valid jump thread. A jump thread is a special
2174 case of SEME Single Entry Multiple Exits region in which all nodes in the
2175 REGION have exactly one incoming edge. The only exception is the first block
2176 that may not have been connected to the rest of the cfg yet. */
2178 DEBUG_FUNCTION void
2179 verify_jump_thread (basic_block *region, unsigned n_region)
2181 for (unsigned i = 0; i < n_region; i++)
2182 gcc_assert (EDGE_COUNT (region[i]->preds) <= 1);
2185 /* Return true when BB is one of the first N items in BBS. */
2187 static inline bool
2188 bb_in_bbs (basic_block bb, basic_block *bbs, int n)
2190 for (int i = 0; i < n; i++)
2191 if (bb == bbs[i])
2192 return true;
2194 return false;
2197 /* Duplicates a jump-thread path of N_REGION basic blocks.
2198 The ENTRY edge is redirected to the duplicate of the region.
2200 Remove the last conditional statement in the last basic block in the REGION,
2201 and create a single fallthru edge pointing to the same destination as the
2202 EXIT edge.
2204 The new basic blocks are stored to REGION_COPY in the same order as they had
2205 in REGION, provided that REGION_COPY is not NULL.
2207 Returns false if it is unable to copy the region, true otherwise. */
2209 static bool
2210 duplicate_thread_path (edge entry, edge exit,
2211 basic_block *region, unsigned n_region,
2212 basic_block *region_copy)
2214 unsigned i;
2215 bool free_region_copy = false;
2216 struct loop *loop = entry->dest->loop_father;
2217 edge exit_copy;
2218 edge redirected;
2219 int total_freq = 0, entry_freq = 0;
2220 gcov_type total_count = 0, entry_count = 0;
2222 if (!can_copy_bbs_p (region, n_region))
2223 return false;
2225 /* Some sanity checking. Note that we do not check for all possible
2226 missuses of the functions. I.e. if you ask to copy something weird,
2227 it will work, but the state of structures probably will not be
2228 correct. */
2229 for (i = 0; i < n_region; i++)
2231 /* We do not handle subloops, i.e. all the blocks must belong to the
2232 same loop. */
2233 if (region[i]->loop_father != loop)
2234 return false;
2237 initialize_original_copy_tables ();
2239 set_loop_copy (loop, loop);
2241 if (!region_copy)
2243 region_copy = XNEWVEC (basic_block, n_region);
2244 free_region_copy = true;
2247 if (entry->dest->count)
2249 total_count = entry->dest->count;
2250 entry_count = entry->count;
2251 /* Fix up corner cases, to avoid division by zero or creation of negative
2252 frequencies. */
2253 if (entry_count > total_count)
2254 entry_count = total_count;
2256 else
2258 total_freq = entry->dest->frequency;
2259 entry_freq = EDGE_FREQUENCY (entry);
2260 /* Fix up corner cases, to avoid division by zero or creation of negative
2261 frequencies. */
2262 if (total_freq == 0)
2263 total_freq = 1;
2264 else if (entry_freq > total_freq)
2265 entry_freq = total_freq;
2268 copy_bbs (region, n_region, region_copy, &exit, 1, &exit_copy, loop,
2269 split_edge_bb_loc (entry), false);
2271 /* Fix up: copy_bbs redirects all edges pointing to copied blocks. The
2272 following code ensures that all the edges exiting the jump-thread path are
2273 redirected back to the original code: these edges are exceptions
2274 invalidating the property that is propagated by executing all the blocks of
2275 the jump-thread path in order. */
2277 for (i = 0; i < n_region; i++)
2279 edge e;
2280 edge_iterator ei;
2281 basic_block bb = region_copy[i];
2283 if (single_succ_p (bb))
2285 /* Make sure the successor is the next node in the path. */
2286 gcc_assert (i + 1 == n_region
2287 || region_copy[i + 1] == single_succ_edge (bb)->dest);
2288 continue;
2291 /* Special case the last block on the path: make sure that it does not
2292 jump back on the copied path. */
2293 if (i + 1 == n_region)
2295 FOR_EACH_EDGE (e, ei, bb->succs)
2296 if (bb_in_bbs (e->dest, region_copy, n_region - 1))
2298 basic_block orig = get_bb_original (e->dest);
2299 if (orig)
2300 redirect_edge_and_branch_force (e, orig);
2302 continue;
2305 /* Redirect all other edges jumping to non-adjacent blocks back to the
2306 original code. */
2307 FOR_EACH_EDGE (e, ei, bb->succs)
2308 if (region_copy[i + 1] != e->dest)
2310 basic_block orig = get_bb_original (e->dest);
2311 if (orig)
2312 redirect_edge_and_branch_force (e, orig);
2316 if (total_count)
2318 scale_bbs_frequencies_gcov_type (region, n_region,
2319 total_count - entry_count,
2320 total_count);
2321 scale_bbs_frequencies_gcov_type (region_copy, n_region, entry_count,
2322 total_count);
2324 else
2326 scale_bbs_frequencies_int (region, n_region, total_freq - entry_freq,
2327 total_freq);
2328 scale_bbs_frequencies_int (region_copy, n_region, entry_freq, total_freq);
2331 if (flag_checking)
2332 verify_jump_thread (region_copy, n_region);
2334 /* Remove the last branch in the jump thread path. */
2335 remove_ctrl_stmt_and_useless_edges (region_copy[n_region - 1], exit->dest);
2337 /* And fixup the flags on the single remaining edge. */
2338 edge fix_e = find_edge (region_copy[n_region - 1], exit->dest);
2339 fix_e->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE | EDGE_ABNORMAL);
2340 fix_e->flags |= EDGE_FALLTHRU;
2342 edge e = make_edge (region_copy[n_region - 1], exit->dest, EDGE_FALLTHRU);
2344 if (e) {
2345 rescan_loop_exit (e, true, false);
2346 e->probability = REG_BR_PROB_BASE;
2347 e->count = region_copy[n_region - 1]->count;
2350 /* Redirect the entry and add the phi node arguments. */
2351 if (entry->dest == loop->header)
2352 mark_loop_for_removal (loop);
2353 redirected = redirect_edge_and_branch (entry, get_bb_copy (entry->dest));
2354 gcc_assert (redirected != NULL);
2355 flush_pending_stmts (entry);
2357 /* Add the other PHI node arguments. */
2358 add_phi_args_after_copy (region_copy, n_region, NULL);
2360 if (free_region_copy)
2361 free (region_copy);
2363 free_original_copy_tables ();
2364 return true;
2367 /* Return true when PATH is a valid jump-thread path. */
2369 static bool
2370 valid_jump_thread_path (vec<jump_thread_edge *> *path)
2372 unsigned len = path->length ();
2373 bool threaded_multiway_branch = false;
2374 bool multiway_branch_in_path = false;
2375 bool threaded_through_latch = false;
2377 /* Check that the path is connected and see if there's a multi-way
2378 branch on the path and whether or not a multi-way branch
2379 is threaded. */
2380 for (unsigned int j = 0; j < len - 1; j++)
2382 edge e = (*path)[j]->e;
2383 struct loop *loop = e->dest->loop_father;
2385 if (e->dest != (*path)[j+1]->e->src)
2386 return false;
2388 /* If we're threading through the loop latch back into the
2389 same loop and the destination does not dominate the loop
2390 latch, then this thread would create an irreducible loop. */
2391 if (loop->latch
2392 && loop_latch_edge (loop) == e
2393 && loop == path->last()->e->dest->loop_father
2394 && (determine_bb_domination_status (loop, path->last ()->e->dest)
2395 == DOMST_NONDOMINATING))
2396 threaded_through_latch = true;
2398 gimple *last = last_stmt (e->dest);
2399 if (j == len - 2)
2400 threaded_multiway_branch
2401 |= (last && gimple_code (last) == GIMPLE_SWITCH);
2402 else
2403 multiway_branch_in_path
2404 |= (last && gimple_code (last) == GIMPLE_SWITCH);
2407 /* If we are trying to thread through the loop latch to a block in the
2408 loop that does not dominate the loop latch, then that will create an
2409 irreducible loop. We avoid that unless the jump thread has a multi-way
2410 branch, in which case we have deemed it worth losing other
2411 loop optimizations later if we can eliminate the multi-way branch. */
2412 if (!threaded_multiway_branch && threaded_through_latch)
2414 if (dump_file && (dump_flags & TDF_DETAILS))
2416 fprintf (dump_file,
2417 "Thread through latch without threading a multiway "
2418 "branch.\n");
2419 dump_jump_thread_path (dump_file, *path, false);
2421 return false;
2424 /* When there is a multi-way branch on the path, then threading can
2425 explode the CFG due to duplicating the edges for that multi-way
2426 branch. So like above, only allow a multi-way branch on the path
2427 if we actually thread a multi-way branch. */
2428 if (!threaded_multiway_branch && multiway_branch_in_path)
2430 if (dump_file && (dump_flags & TDF_DETAILS))
2432 fprintf (dump_file,
2433 "Thread through multiway branch without threading "
2434 "a multiway branch.\n");
2435 dump_jump_thread_path (dump_file, *path, false);
2437 return false;
2440 return true;
2443 /* Remove any queued jump threads that include edge E.
2445 We don't actually remove them here, just record the edges into ax
2446 hash table. That way we can do the search once per iteration of
2447 DOM/VRP rather than for every case where DOM optimizes away a COND_EXPR. */
2449 void
2450 remove_jump_threads_including (edge_def *e)
2452 if (!paths.exists ())
2453 return;
2455 if (!removed_edges)
2456 removed_edges = new hash_table<struct removed_edges> (17);
2458 edge *slot = removed_edges->find_slot (e, INSERT);
2459 *slot = e;
2462 /* Walk through all blocks and thread incoming edges to the appropriate
2463 outgoing edge for each edge pair recorded in THREADED_EDGES.
2465 It is the caller's responsibility to fix the dominance information
2466 and rewrite duplicated SSA_NAMEs back into SSA form.
2468 If MAY_PEEL_LOOP_HEADERS is false, we avoid threading edges through
2469 loop headers if it does not simplify the loop.
2471 Returns true if one or more edges were threaded, false otherwise. */
2473 bool
2474 thread_through_all_blocks (bool may_peel_loop_headers)
2476 bool retval = false;
2477 unsigned int i;
2478 bitmap_iterator bi;
2479 bitmap threaded_blocks;
2480 struct loop *loop;
2482 if (!paths.exists ())
2484 retval = false;
2485 goto out;
2488 threaded_blocks = BITMAP_ALLOC (NULL);
2489 memset (&thread_stats, 0, sizeof (thread_stats));
2491 /* Remove any paths that referenced removed edges. */
2492 if (removed_edges)
2493 for (i = 0; i < paths.length (); )
2495 unsigned int j;
2496 vec<jump_thread_edge *> *path = paths[i];
2498 for (j = 0; j < path->length (); j++)
2500 edge e = (*path)[j]->e;
2501 if (removed_edges->find_slot (e, NO_INSERT))
2502 break;
2505 if (j != path->length ())
2507 delete_jump_thread_path (path);
2508 paths.unordered_remove (i);
2509 continue;
2511 i++;
2514 /* Jump-thread all FSM threads before other jump-threads. */
2515 for (i = 0; i < paths.length ();)
2517 vec<jump_thread_edge *> *path = paths[i];
2518 edge entry = (*path)[0]->e;
2520 /* Only code-generate FSM jump-threads in this loop. */
2521 if ((*path)[0]->type != EDGE_FSM_THREAD)
2523 i++;
2524 continue;
2527 /* Do not jump-thread twice from the same block. */
2528 if (bitmap_bit_p (threaded_blocks, entry->src->index)
2529 /* We may not want to realize this jump thread path
2530 for various reasons. So check it first. */
2531 || !valid_jump_thread_path (path))
2533 /* Remove invalid FSM jump-thread paths. */
2534 delete_jump_thread_path (path);
2535 paths.unordered_remove (i);
2536 continue;
2539 unsigned len = path->length ();
2540 edge exit = (*path)[len - 1]->e;
2541 basic_block *region = XNEWVEC (basic_block, len - 1);
2543 for (unsigned int j = 0; j < len - 1; j++)
2544 region[j] = (*path)[j]->e->dest;
2546 if (duplicate_thread_path (entry, exit, region, len - 1, NULL))
2548 /* We do not update dominance info. */
2549 free_dominance_info (CDI_DOMINATORS);
2550 bitmap_set_bit (threaded_blocks, entry->src->index);
2551 retval = true;
2552 thread_stats.num_threaded_edges++;
2555 delete_jump_thread_path (path);
2556 paths.unordered_remove (i);
2557 free (region);
2560 /* Remove from PATHS all the jump-threads starting with an edge already
2561 jump-threaded. */
2562 for (i = 0; i < paths.length ();)
2564 vec<jump_thread_edge *> *path = paths[i];
2565 edge entry = (*path)[0]->e;
2567 /* Do not jump-thread twice from the same block. */
2568 if (bitmap_bit_p (threaded_blocks, entry->src->index))
2570 delete_jump_thread_path (path);
2571 paths.unordered_remove (i);
2573 else
2574 i++;
2577 bitmap_clear (threaded_blocks);
2579 mark_threaded_blocks (threaded_blocks);
2581 initialize_original_copy_tables ();
2583 /* First perform the threading requests that do not affect
2584 loop structure. */
2585 EXECUTE_IF_SET_IN_BITMAP (threaded_blocks, 0, i, bi)
2587 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
2589 if (EDGE_COUNT (bb->preds) > 0)
2590 retval |= thread_block (bb, true);
2593 /* Then perform the threading through loop headers. We start with the
2594 innermost loop, so that the changes in cfg we perform won't affect
2595 further threading. */
2596 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2598 if (!loop->header
2599 || !bitmap_bit_p (threaded_blocks, loop->header->index))
2600 continue;
2602 retval |= thread_through_loop_header (loop, may_peel_loop_headers);
2605 /* Any jump threading paths that are still attached to edges at this
2606 point must be one of two cases.
2608 First, we could have a jump threading path which went from outside
2609 a loop to inside a loop that was ignored because a prior jump thread
2610 across a backedge was realized (which indirectly causes the loop
2611 above to ignore the latter thread). We can detect these because the
2612 loop structures will be different and we do not currently try to
2613 optimize this case.
2615 Second, we could be threading across a backedge to a point within the
2616 same loop. This occurrs for the FSA/FSM optimization and we would
2617 like to optimize it. However, we have to be very careful as this
2618 may completely scramble the loop structures, with the result being
2619 irreducible loops causing us to throw away our loop structure.
2621 As a compromise for the latter case, if the thread path ends in
2622 a block where the last statement is a multiway branch, then go
2623 ahead and thread it, else ignore it. */
2624 basic_block bb;
2625 edge e;
2626 FOR_EACH_BB_FN (bb, cfun)
2628 /* If we do end up threading here, we can remove elements from
2629 BB->preds. Thus we can not use the FOR_EACH_EDGE iterator. */
2630 for (edge_iterator ei = ei_start (bb->preds);
2631 (e = ei_safe_edge (ei));)
2632 if (e->aux)
2634 vec<jump_thread_edge *> *path = THREAD_PATH (e);
2636 /* Case 1, threading from outside to inside the loop
2637 after we'd already threaded through the header. */
2638 if ((*path)[0]->e->dest->loop_father
2639 != path->last ()->e->src->loop_father)
2641 delete_jump_thread_path (path);
2642 e->aux = NULL;
2643 ei_next (&ei);
2645 else
2647 delete_jump_thread_path (path);
2648 e->aux = NULL;
2649 ei_next (&ei);
2652 else
2653 ei_next (&ei);
2656 statistics_counter_event (cfun, "Jumps threaded",
2657 thread_stats.num_threaded_edges);
2659 free_original_copy_tables ();
2661 BITMAP_FREE (threaded_blocks);
2662 threaded_blocks = NULL;
2663 paths.release ();
2665 if (retval)
2666 loops_state_set (LOOPS_NEED_FIXUP);
2668 out:
2669 delete removed_edges;
2670 removed_edges = NULL;
2671 return retval;
2674 /* Delete the jump threading path PATH. We have to explcitly delete
2675 each entry in the vector, then the container. */
2677 void
2678 delete_jump_thread_path (vec<jump_thread_edge *> *path)
2680 for (unsigned int i = 0; i < path->length (); i++)
2681 delete (*path)[i];
2682 path->release();
2683 delete path;
2686 /* Register a jump threading opportunity. We queue up all the jump
2687 threading opportunities discovered by a pass and update the CFG
2688 and SSA form all at once.
2690 E is the edge we can thread, E2 is the new target edge, i.e., we
2691 are effectively recording that E->dest can be changed to E2->dest
2692 after fixing the SSA graph. */
2694 void
2695 register_jump_thread (vec<jump_thread_edge *> *path)
2697 if (!dbg_cnt (registered_jump_thread))
2699 delete_jump_thread_path (path);
2700 return;
2703 /* First make sure there are no NULL outgoing edges on the jump threading
2704 path. That can happen for jumping to a constant address. */
2705 for (unsigned int i = 0; i < path->length (); i++)
2707 if ((*path)[i]->e == NULL)
2709 if (dump_file && (dump_flags & TDF_DETAILS))
2711 fprintf (dump_file,
2712 "Found NULL edge in jump threading path. Cancelling jump thread:\n");
2713 dump_jump_thread_path (dump_file, *path, false);
2716 delete_jump_thread_path (path);
2717 return;
2720 /* Only the FSM threader is allowed to thread across
2721 backedges in the CFG. */
2722 if (flag_checking
2723 && (*path)[0]->type != EDGE_FSM_THREAD)
2724 gcc_assert (((*path)[i]->e->flags & EDGE_DFS_BACK) == 0);
2727 if (dump_file && (dump_flags & TDF_DETAILS))
2728 dump_jump_thread_path (dump_file, *path, true);
2730 if (!paths.exists ())
2731 paths.create (5);
2733 paths.safe_push (path);