1 /* Lower GIMPLE_SWITCH expressions to something more efficient than
3 Copyright (C) 2006-2018 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
22 /* This file handles the lowering of GIMPLE_SWITCH to an indexed
23 load, or a series of bit-test-and-branch expressions. */
27 #include "coretypes.h"
29 #include "insn-codes.h"
34 #include "tree-pass.h"
36 #include "optabs-tree.h"
38 #include "gimple-pretty-print.h"
40 #include "fold-const.h"
42 #include "stor-layout.h"
45 #include "gimple-iterator.h"
46 #include "gimplify-me.h"
49 #include "alloc-pool.h"
51 #include "tree-into-ssa.h"
52 #include "omp-general.h"
54 /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
55 type in the GIMPLE type system that is language-independent? */
56 #include "langhooks.h"
58 #include "tree-switch-conversion.h"
60 using namespace tree_switch_conversion
;
64 switch_conversion::switch_conversion (): m_final_bb (NULL
), m_other_count (),
65 m_constructors (NULL
), m_default_values (NULL
),
66 m_arr_ref_first (NULL
), m_arr_ref_last (NULL
),
67 m_reason (NULL
), m_default_case_nonstandard (false), m_cfg_altered (false)
71 /* Collection information about SWTCH statement. */
74 switch_conversion::collect (gswitch
*swtch
)
76 unsigned int branch_num
= gimple_switch_num_labels (swtch
);
77 tree min_case
, max_case
;
79 edge e
, e_default
, e_first
;
85 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
86 is a default label which is the first in the vector.
87 Collect the bits we can deduce from the CFG. */
88 m_index_expr
= gimple_switch_index (swtch
);
89 m_switch_bb
= gimple_bb (swtch
);
91 = label_to_block (CASE_LABEL (gimple_switch_default_label (swtch
)));
92 e_default
= find_edge (m_switch_bb
, m_default_bb
);
93 m_default_prob
= e_default
->probability
;
94 m_default_count
= e_default
->count ();
95 FOR_EACH_EDGE (e
, ei
, m_switch_bb
->succs
)
97 m_other_count
+= e
->count ();
99 /* Get upper and lower bounds of case values, and the covered range. */
100 min_case
= gimple_switch_label (swtch
, 1);
101 max_case
= gimple_switch_label (swtch
, branch_num
- 1);
103 m_range_min
= CASE_LOW (min_case
);
104 if (CASE_HIGH (max_case
) != NULL_TREE
)
105 m_range_max
= CASE_HIGH (max_case
);
107 m_range_max
= CASE_LOW (max_case
);
109 m_contiguous_range
= true;
110 tree last
= CASE_HIGH (min_case
) ? CASE_HIGH (min_case
) : m_range_min
;
111 for (i
= 2; i
< branch_num
; i
++)
113 tree elt
= gimple_switch_label (swtch
, i
);
114 if (wi::to_wide (last
) + 1 != wi::to_wide (CASE_LOW (elt
)))
116 m_contiguous_range
= false;
119 last
= CASE_HIGH (elt
) ? CASE_HIGH (elt
) : CASE_LOW (elt
);
122 if (m_contiguous_range
)
124 first
= label_to_block (CASE_LABEL (gimple_switch_label (swtch
, 1)));
125 e_first
= find_edge (m_switch_bb
, first
);
129 first
= m_default_bb
;
133 /* See if there is one common successor block for all branch
134 targets. If it exists, record it in FINAL_BB.
135 Start with the destination of the first non-default case
136 if the range is contiguous and default case otherwise as
137 guess or its destination in case it is a forwarder block. */
138 if (! single_pred_p (e_first
->dest
))
139 m_final_bb
= e_first
->dest
;
140 else if (single_succ_p (e_first
->dest
)
141 && ! single_pred_p (single_succ (e_first
->dest
)))
142 m_final_bb
= single_succ (e_first
->dest
);
143 /* Require that all switch destinations are either that common
144 FINAL_BB or a forwarder to it, except for the default
145 case if contiguous range. */
147 FOR_EACH_EDGE (e
, ei
, m_switch_bb
->succs
)
149 if (e
->dest
== m_final_bb
)
152 if (single_pred_p (e
->dest
)
153 && single_succ_p (e
->dest
)
154 && single_succ (e
->dest
) == m_final_bb
)
157 if (e
== e_default
&& m_contiguous_range
)
159 m_default_case_nonstandard
= true;
168 = int_const_binop (MINUS_EXPR
, m_range_max
, m_range_min
);
170 /* Get a count of the number of case labels. Single-valued case labels
171 simply count as one, but a case range counts double, since it may
172 require two compares if it gets lowered as a branching tree. */
174 for (i
= 1; i
< branch_num
; i
++)
176 tree elt
= gimple_switch_label (swtch
, i
);
179 && ! tree_int_cst_equal (CASE_LOW (elt
), CASE_HIGH (elt
)))
183 /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
184 block. Assume a CFG cleanup would have already removed degenerate
185 switch statements, this allows us to just use EDGE_COUNT. */
186 m_uniq
= EDGE_COUNT (gimple_bb (swtch
)->succs
) - 1;
189 /* Checks whether the range given by individual case statements of the switch
190 switch statement isn't too big and whether the number of branches actually
191 satisfies the size of the new array. */
194 switch_conversion::check_range ()
196 gcc_assert (m_range_size
);
197 if (!tree_fits_uhwi_p (m_range_size
))
199 m_reason
= "index range way too large or otherwise unusable";
203 if (tree_to_uhwi (m_range_size
)
204 > ((unsigned) m_count
* SWITCH_CONVERSION_BRANCH_RATIO
))
206 m_reason
= "the maximum range-branch ratio exceeded";
213 /* Checks whether all but the final BB basic blocks are empty. */
216 switch_conversion::check_all_empty_except_final ()
218 edge e
, e_default
= find_edge (m_switch_bb
, m_default_bb
);
221 FOR_EACH_EDGE (e
, ei
, m_switch_bb
->succs
)
223 if (e
->dest
== m_final_bb
)
226 if (!empty_block_p (e
->dest
))
228 if (m_contiguous_range
&& e
== e_default
)
230 m_default_case_nonstandard
= true;
234 m_reason
= "bad case - a non-final BB not empty";
242 /* This function checks whether all required values in phi nodes in final_bb
243 are constants. Required values are those that correspond to a basic block
244 which is a part of the examined switch statement. It returns true if the
245 phi nodes are OK, otherwise false. */
248 switch_conversion::check_final_bb ()
253 for (gsi
= gsi_start_phis (m_final_bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
255 gphi
*phi
= gsi
.phi ();
258 if (virtual_operand_p (gimple_phi_result (phi
)))
263 for (i
= 0; i
< gimple_phi_num_args (phi
); i
++)
265 basic_block bb
= gimple_phi_arg_edge (phi
, i
)->src
;
267 if (bb
== m_switch_bb
268 || (single_pred_p (bb
)
269 && single_pred (bb
) == m_switch_bb
270 && (!m_default_case_nonstandard
271 || empty_block_p (bb
))))
274 const char *reason
= NULL
;
276 val
= gimple_phi_arg_def (phi
, i
);
277 if (!is_gimple_ip_invariant (val
))
278 reason
= "non-invariant value from a case";
281 reloc
= initializer_constant_valid_p (val
, TREE_TYPE (val
));
282 if ((flag_pic
&& reloc
!= null_pointer_node
)
283 || (!flag_pic
&& reloc
== NULL_TREE
))
287 = "value from a case would need runtime relocations";
290 = "value from a case is not a valid initializer";
295 /* For contiguous range, we can allow non-constant
296 or one that needs relocation, as long as it is
297 only reachable from the default case. */
298 if (bb
== m_switch_bb
)
300 if (!m_contiguous_range
|| bb
!= m_default_bb
)
306 unsigned int branch_num
= gimple_switch_num_labels (m_switch
);
307 for (unsigned int i
= 1; i
< branch_num
; i
++)
309 tree lab
= CASE_LABEL (gimple_switch_label (m_switch
, i
));
310 if (label_to_block (lab
) == bb
)
316 m_default_case_nonstandard
= true;
325 /* The following function allocates default_values, target_{in,out}_names and
326 constructors arrays. The last one is also populated with pointers to
327 vectors that will become constructors of new arrays. */
330 switch_conversion::create_temp_arrays ()
334 m_default_values
= XCNEWVEC (tree
, m_phi_count
* 3);
335 /* ??? Macros do not support multi argument templates in their
336 argument list. We create a typedef to work around that problem. */
337 typedef vec
<constructor_elt
, va_gc
> *vec_constructor_elt_gc
;
338 m_constructors
= XCNEWVEC (vec_constructor_elt_gc
, m_phi_count
);
339 m_target_inbound_names
= m_default_values
+ m_phi_count
;
340 m_target_outbound_names
= m_target_inbound_names
+ m_phi_count
;
341 for (i
= 0; i
< m_phi_count
; i
++)
342 vec_alloc (m_constructors
[i
], tree_to_uhwi (m_range_size
) + 1);
345 /* Populate the array of default values in the order of phi nodes.
346 DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
347 if the range is non-contiguous or the default case has standard
348 structure, otherwise it is the first non-default case instead. */
351 switch_conversion::gather_default_values (tree default_case
)
354 basic_block bb
= label_to_block (CASE_LABEL (default_case
));
358 gcc_assert (CASE_LOW (default_case
) == NULL_TREE
359 || m_default_case_nonstandard
);
361 if (bb
== m_final_bb
)
362 e
= find_edge (m_switch_bb
, bb
);
364 e
= single_succ_edge (bb
);
366 for (gsi
= gsi_start_phis (m_final_bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
368 gphi
*phi
= gsi
.phi ();
369 if (virtual_operand_p (gimple_phi_result (phi
)))
371 tree val
= PHI_ARG_DEF_FROM_EDGE (phi
, e
);
373 m_default_values
[i
++] = val
;
377 /* The following function populates the vectors in the constructors array with
378 future contents of the static arrays. The vectors are populated in the
379 order of phi nodes. */
382 switch_conversion::build_constructors ()
384 unsigned i
, branch_num
= gimple_switch_num_labels (m_switch
);
385 tree pos
= m_range_min
;
386 tree pos_one
= build_int_cst (TREE_TYPE (pos
), 1);
388 for (i
= 1; i
< branch_num
; i
++)
390 tree cs
= gimple_switch_label (m_switch
, i
);
391 basic_block bb
= label_to_block (CASE_LABEL (cs
));
397 if (bb
== m_final_bb
)
398 e
= find_edge (m_switch_bb
, bb
);
400 e
= single_succ_edge (bb
);
403 while (tree_int_cst_lt (pos
, CASE_LOW (cs
)))
406 for (k
= 0; k
< m_phi_count
; k
++)
410 elt
.index
= int_const_binop (MINUS_EXPR
, pos
, m_range_min
);
412 = unshare_expr_without_location (m_default_values
[k
]);
413 m_constructors
[k
]->quick_push (elt
);
416 pos
= int_const_binop (PLUS_EXPR
, pos
, pos_one
);
418 gcc_assert (tree_int_cst_equal (pos
, CASE_LOW (cs
)));
422 high
= CASE_HIGH (cs
);
424 high
= CASE_LOW (cs
);
425 for (gsi
= gsi_start_phis (m_final_bb
);
426 !gsi_end_p (gsi
); gsi_next (&gsi
))
428 gphi
*phi
= gsi
.phi ();
429 if (virtual_operand_p (gimple_phi_result (phi
)))
431 tree val
= PHI_ARG_DEF_FROM_EDGE (phi
, e
);
432 tree low
= CASE_LOW (cs
);
439 elt
.index
= int_const_binop (MINUS_EXPR
, pos
, m_range_min
);
440 elt
.value
= unshare_expr_without_location (val
);
441 m_constructors
[j
]->quick_push (elt
);
443 pos
= int_const_binop (PLUS_EXPR
, pos
, pos_one
);
444 } while (!tree_int_cst_lt (high
, pos
)
445 && tree_int_cst_lt (low
, pos
));
451 /* If all values in the constructor vector are the same, return the value.
452 Otherwise return NULL_TREE. Not supposed to be called for empty
456 switch_conversion::contains_same_values_p (vec
<constructor_elt
, va_gc
> *vec
)
459 tree prev
= NULL_TREE
;
460 constructor_elt
*elt
;
462 FOR_EACH_VEC_SAFE_ELT (vec
, i
, elt
)
466 else if (!operand_equal_p (elt
->value
, prev
, OEP_ONLY_CONST
))
472 /* Return type which should be used for array elements, either TYPE's
473 main variant or, for integral types, some smaller integral type
474 that can still hold all the constants. */
477 switch_conversion::array_value_type (tree type
, int num
)
479 unsigned int i
, len
= vec_safe_length (m_constructors
[num
]);
480 constructor_elt
*elt
;
484 /* Types with alignments greater than their size can reach here, e.g. out of
485 SRA. We couldn't use these as an array component type so get back to the
486 main variant first, which, for our purposes, is fine for other types as
489 type
= TYPE_MAIN_VARIANT (type
);
491 if (!INTEGRAL_TYPE_P (type
))
494 scalar_int_mode type_mode
= SCALAR_INT_TYPE_MODE (type
);
495 scalar_int_mode mode
= get_narrowest_mode (type_mode
);
496 if (GET_MODE_SIZE (type_mode
) <= GET_MODE_SIZE (mode
))
499 if (len
< (optimize_bb_for_size_p (gimple_bb (m_switch
)) ? 2 : 32))
502 FOR_EACH_VEC_SAFE_ELT (m_constructors
[num
], i
, elt
)
506 if (TREE_CODE (elt
->value
) != INTEGER_CST
)
509 cst
= wi::to_wide (elt
->value
);
512 unsigned int prec
= GET_MODE_BITSIZE (mode
);
513 if (prec
> HOST_BITS_PER_WIDE_INT
)
516 if (sign
>= 0 && cst
== wi::zext (cst
, prec
))
518 if (sign
== 0 && cst
== wi::sext (cst
, prec
))
523 if (sign
<= 0 && cst
== wi::sext (cst
, prec
))
532 if (!GET_MODE_WIDER_MODE (mode
).exists (&mode
)
533 || GET_MODE_SIZE (mode
) >= GET_MODE_SIZE (type_mode
))
539 sign
= TYPE_UNSIGNED (type
) ? 1 : -1;
540 smaller_type
= lang_hooks
.types
.type_for_mode (mode
, sign
>= 0);
541 if (GET_MODE_SIZE (type_mode
)
542 <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type
)))
548 /* Create an appropriate array type and declaration and assemble a static
549 array variable. Also create a load statement that initializes
550 the variable in question with a value from the static array. SWTCH is
551 the switch statement being converted, NUM is the index to
552 arrays of constructors, default values and target SSA names
553 for this particular array. ARR_INDEX_TYPE is the type of the index
554 of the new array, PHI is the phi node of the final BB that corresponds
555 to the value that will be loaded from the created array. TIDX
556 is an ssa name of a temporary variable holding the index for loads from the
560 switch_conversion::build_one_array (int num
, tree arr_index_type
,
561 gphi
*phi
, tree tidx
)
565 gimple_stmt_iterator gsi
= gsi_for_stmt (m_switch
);
566 location_t loc
= gimple_location (m_switch
);
568 gcc_assert (m_default_values
[num
]);
570 name
= copy_ssa_name (PHI_RESULT (phi
));
571 m_target_inbound_names
[num
] = name
;
573 cst
= contains_same_values_p (m_constructors
[num
]);
575 load
= gimple_build_assign (name
, cst
);
578 tree array_type
, ctor
, decl
, value_type
, fetch
, default_type
;
580 default_type
= TREE_TYPE (m_default_values
[num
]);
581 value_type
= array_value_type (default_type
, num
);
582 array_type
= build_array_type (value_type
, arr_index_type
);
583 if (default_type
!= value_type
)
586 constructor_elt
*elt
;
588 FOR_EACH_VEC_SAFE_ELT (m_constructors
[num
], i
, elt
)
589 elt
->value
= fold_convert (value_type
, elt
->value
);
591 ctor
= build_constructor (array_type
, m_constructors
[num
]);
592 TREE_CONSTANT (ctor
) = true;
593 TREE_STATIC (ctor
) = true;
595 decl
= build_decl (loc
, VAR_DECL
, NULL_TREE
, array_type
);
596 TREE_STATIC (decl
) = 1;
597 DECL_INITIAL (decl
) = ctor
;
599 DECL_NAME (decl
) = create_tmp_var_name ("CSWTCH");
600 DECL_ARTIFICIAL (decl
) = 1;
601 DECL_IGNORED_P (decl
) = 1;
602 TREE_CONSTANT (decl
) = 1;
603 TREE_READONLY (decl
) = 1;
604 DECL_IGNORED_P (decl
) = 1;
605 if (offloading_function_p (cfun
->decl
))
606 DECL_ATTRIBUTES (decl
)
607 = tree_cons (get_identifier ("omp declare target"), NULL_TREE
,
609 varpool_node::finalize_decl (decl
);
611 fetch
= build4 (ARRAY_REF
, value_type
, decl
, tidx
, NULL_TREE
,
613 if (default_type
!= value_type
)
615 fetch
= fold_convert (default_type
, fetch
);
616 fetch
= force_gimple_operand_gsi (&gsi
, fetch
, true, NULL_TREE
,
617 true, GSI_SAME_STMT
);
619 load
= gimple_build_assign (name
, fetch
);
622 gsi_insert_before (&gsi
, load
, GSI_SAME_STMT
);
624 m_arr_ref_last
= load
;
627 /* Builds and initializes static arrays initialized with values gathered from
628 the switch statement. Also creates statements that load values from
632 switch_conversion::build_arrays ()
635 tree tidx
, sub
, utype
;
637 gimple_stmt_iterator gsi
;
640 location_t loc
= gimple_location (m_switch
);
642 gsi
= gsi_for_stmt (m_switch
);
644 /* Make sure we do not generate arithmetics in a subrange. */
645 utype
= TREE_TYPE (m_index_expr
);
646 if (TREE_TYPE (utype
))
647 utype
= lang_hooks
.types
.type_for_mode (TYPE_MODE (TREE_TYPE (utype
)), 1);
649 utype
= lang_hooks
.types
.type_for_mode (TYPE_MODE (utype
), 1);
651 arr_index_type
= build_index_type (m_range_size
);
652 tidx
= make_ssa_name (utype
);
653 sub
= fold_build2_loc (loc
, MINUS_EXPR
, utype
,
654 fold_convert_loc (loc
, utype
, m_index_expr
),
655 fold_convert_loc (loc
, utype
, m_range_min
));
656 sub
= force_gimple_operand_gsi (&gsi
, sub
,
657 false, NULL
, true, GSI_SAME_STMT
);
658 stmt
= gimple_build_assign (tidx
, sub
);
660 gsi_insert_before (&gsi
, stmt
, GSI_SAME_STMT
);
662 m_arr_ref_first
= stmt
;
664 for (gpi
= gsi_start_phis (m_final_bb
), i
= 0;
665 !gsi_end_p (gpi
); gsi_next (&gpi
))
667 gphi
*phi
= gpi
.phi ();
668 if (!virtual_operand_p (gimple_phi_result (phi
)))
669 build_one_array (i
++, arr_index_type
, phi
, tidx
);
674 FOR_EACH_EDGE (e
, ei
, m_switch_bb
->succs
)
676 if (e
->dest
== m_final_bb
)
678 if (!m_default_case_nonstandard
679 || e
->dest
!= m_default_bb
)
681 e
= single_succ_edge (e
->dest
);
685 gcc_assert (e
&& e
->dest
== m_final_bb
);
686 m_target_vop
= PHI_ARG_DEF_FROM_EDGE (phi
, e
);
691 /* Generates and appropriately inserts loads of default values at the position
692 given by GSI. Returns the last inserted statement. */
695 switch_conversion::gen_def_assigns (gimple_stmt_iterator
*gsi
)
698 gassign
*assign
= NULL
;
700 for (i
= 0; i
< m_phi_count
; i
++)
702 tree name
= copy_ssa_name (m_target_inbound_names
[i
]);
703 m_target_outbound_names
[i
] = name
;
704 assign
= gimple_build_assign (name
, m_default_values
[i
]);
705 gsi_insert_before (gsi
, assign
, GSI_SAME_STMT
);
706 update_stmt (assign
);
711 /* Deletes the unused bbs and edges that now contain the switch statement and
712 its empty branch bbs. BBD is the now dead BB containing
713 the original switch statement, FINAL is the last BB of the converted
714 switch statement (in terms of succession). */
717 switch_conversion::prune_bbs (basic_block bbd
, basic_block final
,
718 basic_block default_bb
)
723 for (ei
= ei_start (bbd
->succs
); (e
= ei_safe_edge (ei
)); )
728 if (bb
!= final
&& bb
!= default_bb
)
729 delete_basic_block (bb
);
731 delete_basic_block (bbd
);
734 /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
735 from the basic block loading values from an array and E2F from the basic
736 block loading default values. BBF is the last switch basic block (see the
737 bbf description in the comment below). */
740 switch_conversion::fix_phi_nodes (edge e1f
, edge e2f
, basic_block bbf
)
745 for (gsi
= gsi_start_phis (bbf
), i
= 0;
746 !gsi_end_p (gsi
); gsi_next (&gsi
))
748 gphi
*phi
= gsi
.phi ();
749 tree inbound
, outbound
;
750 if (virtual_operand_p (gimple_phi_result (phi
)))
751 inbound
= outbound
= m_target_vop
;
754 inbound
= m_target_inbound_names
[i
];
755 outbound
= m_target_outbound_names
[i
++];
757 add_phi_arg (phi
, inbound
, e1f
, UNKNOWN_LOCATION
);
758 if (!m_default_case_nonstandard
)
759 add_phi_arg (phi
, outbound
, e2f
, UNKNOWN_LOCATION
);
763 /* Creates a check whether the switch expression value actually falls into the
764 range given by all the cases. If it does not, the temporaries are loaded
765 with default values instead. */
768 switch_conversion::gen_inbound_check ()
770 tree label_decl1
= create_artificial_label (UNKNOWN_LOCATION
);
771 tree label_decl2
= create_artificial_label (UNKNOWN_LOCATION
);
772 tree label_decl3
= create_artificial_label (UNKNOWN_LOCATION
);
773 glabel
*label1
, *label2
, *label3
;
779 gassign
*last_assign
= NULL
;
780 gimple_stmt_iterator gsi
;
781 basic_block bb0
, bb1
, bb2
, bbf
, bbd
;
782 edge e01
= NULL
, e02
, e21
, e1d
, e1f
, e2f
;
783 location_t loc
= gimple_location (m_switch
);
785 gcc_assert (m_default_values
);
787 bb0
= gimple_bb (m_switch
);
789 tidx
= gimple_assign_lhs (m_arr_ref_first
);
790 utype
= TREE_TYPE (tidx
);
792 /* (end of) block 0 */
793 gsi
= gsi_for_stmt (m_arr_ref_first
);
796 bound
= fold_convert_loc (loc
, utype
, m_range_size
);
797 cond_stmt
= gimple_build_cond (LE_EXPR
, tidx
, bound
, NULL_TREE
, NULL_TREE
);
798 gsi_insert_before (&gsi
, cond_stmt
, GSI_SAME_STMT
);
799 update_stmt (cond_stmt
);
802 if (!m_default_case_nonstandard
)
804 label2
= gimple_build_label (label_decl2
);
805 gsi_insert_before (&gsi
, label2
, GSI_SAME_STMT
);
806 last_assign
= gen_def_assigns (&gsi
);
810 label1
= gimple_build_label (label_decl1
);
811 gsi_insert_before (&gsi
, label1
, GSI_SAME_STMT
);
814 gsi
= gsi_start_bb (m_final_bb
);
815 label3
= gimple_build_label (label_decl3
);
816 gsi_insert_before (&gsi
, label3
, GSI_SAME_STMT
);
819 e02
= split_block (bb0
, cond_stmt
);
822 if (m_default_case_nonstandard
)
827 e01
->flags
= EDGE_TRUE_VALUE
;
828 e02
= make_edge (bb0
, bb2
, EDGE_FALSE_VALUE
);
829 edge e_default
= find_edge (bb1
, bb2
);
830 for (gphi_iterator gsi
= gsi_start_phis (bb2
);
831 !gsi_end_p (gsi
); gsi_next (&gsi
))
833 gphi
*phi
= gsi
.phi ();
834 tree arg
= PHI_ARG_DEF_FROM_EDGE (phi
, e_default
);
835 add_phi_arg (phi
, arg
, e02
,
836 gimple_phi_arg_location_from_edge (phi
, e_default
));
838 /* Partially fix the dominator tree, if it is available. */
839 if (dom_info_available_p (CDI_DOMINATORS
))
840 redirect_immediate_dominators (CDI_DOMINATORS
, bb1
, bb0
);
844 e21
= split_block (bb2
, last_assign
);
849 e1d
= split_block (bb1
, m_arr_ref_last
);
853 /* Flags and profiles of the edge for in-range values. */
854 if (!m_default_case_nonstandard
)
855 e01
= make_edge (bb0
, bb1
, EDGE_TRUE_VALUE
);
856 e01
->probability
= m_default_prob
.invert ();
858 /* Flags and profiles of the edge taking care of out-of-range values. */
859 e02
->flags
&= ~EDGE_FALLTHRU
;
860 e02
->flags
|= EDGE_FALSE_VALUE
;
861 e02
->probability
= m_default_prob
;
865 e1f
= make_edge (bb1
, bbf
, EDGE_FALLTHRU
);
866 e1f
->probability
= profile_probability::always ();
868 if (m_default_case_nonstandard
)
872 e2f
= make_edge (bb2
, bbf
, EDGE_FALLTHRU
);
873 e2f
->probability
= profile_probability::always ();
876 /* frequencies of the new BBs */
877 bb1
->count
= e01
->count ();
878 bb2
->count
= e02
->count ();
879 if (!m_default_case_nonstandard
)
880 bbf
->count
= e1f
->count () + e2f
->count ();
882 /* Tidy blocks that have become unreachable. */
883 prune_bbs (bbd
, m_final_bb
,
884 m_default_case_nonstandard
? m_default_bb
: NULL
);
886 /* Fixup the PHI nodes in bbF. */
887 fix_phi_nodes (e1f
, e2f
, bbf
);
889 /* Fix the dominator tree, if it is available. */
890 if (dom_info_available_p (CDI_DOMINATORS
))
892 vec
<basic_block
> bbs_to_fix_dom
;
894 set_immediate_dominator (CDI_DOMINATORS
, bb1
, bb0
);
895 if (!m_default_case_nonstandard
)
896 set_immediate_dominator (CDI_DOMINATORS
, bb2
, bb0
);
897 if (! get_immediate_dominator (CDI_DOMINATORS
, bbf
))
898 /* If bbD was the immediate dominator ... */
899 set_immediate_dominator (CDI_DOMINATORS
, bbf
, bb0
);
901 bbs_to_fix_dom
.create (3 + (bb2
!= bbf
));
902 bbs_to_fix_dom
.quick_push (bb0
);
903 bbs_to_fix_dom
.quick_push (bb1
);
905 bbs_to_fix_dom
.quick_push (bb2
);
906 bbs_to_fix_dom
.quick_push (bbf
);
908 iterate_fix_dominators (CDI_DOMINATORS
, bbs_to_fix_dom
, true);
909 bbs_to_fix_dom
.release ();
913 /* The following function is invoked on every switch statement (the current
914 one is given in SWTCH) and runs the individual phases of switch
915 conversion on it one after another until one fails or the conversion
916 is completed. On success, NULL is in m_reason, otherwise points
917 to a string with the reason why the conversion failed. */
920 switch_conversion::expand (gswitch
*swtch
)
922 /* Group case labels so that we get the right results from the heuristics
923 that decide on the code generation approach for this switch. */
924 m_cfg_altered
|= group_case_labels_stmt (swtch
);
926 /* If this switch is now a degenerate case with only a default label,
927 there is nothing left for us to do. */
928 if (gimple_switch_num_labels (swtch
) < 2)
930 m_reason
= "switch is a degenerate case";
936 /* No error markers should reach here (they should be filtered out
937 during gimplification). */
938 gcc_checking_assert (TREE_TYPE (m_index_expr
) != error_mark_node
);
940 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
941 gcc_checking_assert (!TREE_CONSTANT (m_index_expr
));
943 /* Prefer bit test if possible. */
944 if (tree_fits_uhwi_p (m_range_size
)
945 && bit_test_cluster::can_be_handled (tree_to_uhwi (m_range_size
), m_uniq
)
946 && bit_test_cluster::is_beneficial (m_count
, m_uniq
))
948 m_reason
= "expanding as bit test is preferable";
954 /* This will be expanded as a decision tree . */
955 m_reason
= "expanding as jumps is preferable";
959 /* If there is no common successor, we cannot do the transformation. */
962 m_reason
= "no common successor to all case label target blocks found";
966 /* Check the case label values are within reasonable range: */
969 gcc_assert (m_reason
);
973 /* For all the cases, see whether they are empty, the assignments they
974 represent constant and so on... */
975 if (!check_all_empty_except_final ())
977 gcc_assert (m_reason
);
980 if (!check_final_bb ())
982 gcc_assert (m_reason
);
986 /* At this point all checks have passed and we can proceed with the
989 create_temp_arrays ();
990 gather_default_values (m_default_case_nonstandard
991 ? gimple_switch_label (swtch
, 1)
992 : gimple_switch_default_label (swtch
));
993 build_constructors ();
995 build_arrays (); /* Build the static arrays and assignments. */
996 gen_inbound_check (); /* Build the bounds check. */
998 m_cfg_altered
= true;
1003 switch_conversion::~switch_conversion ()
1005 XDELETEVEC (m_constructors
);
1006 XDELETEVEC (m_default_values
);
1011 group_cluster::group_cluster (vec
<cluster
*> &clusters
,
1012 unsigned start
, unsigned end
)
1014 gcc_checking_assert (end
- start
+ 1 >= 1);
1015 m_prob
= profile_probability::never ();
1016 m_cases
.create (end
- start
+ 1);
1017 for (unsigned i
= start
; i
<= end
; i
++)
1019 m_cases
.quick_push (static_cast<simple_cluster
*> (clusters
[i
]));
1020 m_prob
+= clusters
[i
]->m_prob
;
1022 m_subtree_prob
= m_prob
;
1027 group_cluster::~group_cluster ()
1029 for (unsigned i
= 0; i
< m_cases
.length (); i
++)
1035 /* Dump content of a cluster. */
1038 group_cluster::dump (FILE *f
, bool details
)
1040 unsigned total_values
= 0;
1041 for (unsigned i
= 0; i
< m_cases
.length (); i
++)
1042 total_values
+= m_cases
[i
]->get_range (m_cases
[i
]->get_low (),
1043 m_cases
[i
]->get_high ());
1045 unsigned comparison_count
= 0;
1046 for (unsigned i
= 0; i
< m_cases
.length (); i
++)
1048 simple_cluster
*sc
= static_cast<simple_cluster
*> (m_cases
[i
]);
1049 comparison_count
+= sc
->m_range_p
? 2 : 1;
1052 unsigned HOST_WIDE_INT range
= get_range (get_low (), get_high ());
1053 fprintf (f
, "%s", get_type () == JUMP_TABLE
? "JT" : "BT");
1056 fprintf (f
, "(values:%d comparisons:%d range:" HOST_WIDE_INT_PRINT_DEC
1057 " density: %.2f%%)", total_values
, comparison_count
, range
,
1058 100.0f
* comparison_count
/ range
);
1061 PRINT_CASE (f
, get_low ());
1063 PRINT_CASE (f
, get_high ());
1067 /* Emit GIMPLE code to handle the cluster. */
1070 jump_table_cluster::emit (tree index_expr
, tree
,
1071 tree default_label_expr
, basic_block default_bb
)
1073 /* For jump table we just emit a new gswitch statement that will
1074 be latter lowered to jump table. */
1075 auto_vec
<tree
> labels
;
1076 labels
.create (m_cases
.length ());
1078 make_edge (m_case_bb
, default_bb
, 0);
1079 for (unsigned i
= 0; i
< m_cases
.length (); i
++)
1081 labels
.quick_push (unshare_expr (m_cases
[i
]->m_case_label_expr
));
1082 make_edge (m_case_bb
, m_cases
[i
]->m_case_bb
, 0);
1085 gswitch
*s
= gimple_build_switch (index_expr
,
1086 unshare_expr (default_label_expr
), labels
);
1087 gimple_stmt_iterator gsi
= gsi_start_bb (m_case_bb
);
1088 gsi_insert_after (&gsi
, s
, GSI_NEW_STMT
);
1091 /* Find jump tables of given CLUSTERS, where all members of the vector
1092 are of type simple_cluster. New clusters are returned. */
1095 jump_table_cluster::find_jump_tables (vec
<cluster
*> &clusters
)
1098 return clusters
.copy ();
1100 unsigned l
= clusters
.length ();
1101 auto_vec
<min_cluster_item
> min
;
1102 min
.reserve (l
+ 1);
1104 min
.quick_push (min_cluster_item (0, 0, 0));
1106 for (unsigned i
= 1; i
<= l
; i
++)
1108 /* Set minimal # of clusters with i-th item to infinite. */
1109 min
.quick_push (min_cluster_item (INT_MAX
, INT_MAX
, INT_MAX
));
1111 for (unsigned j
= 0; j
< i
; j
++)
1113 unsigned HOST_WIDE_INT s
= min
[j
].m_non_jt_cases
;
1114 if (i
- j
< case_values_threshold ())
1117 /* Prefer clusters with smaller number of numbers covered. */
1118 if ((min
[j
].m_count
+ 1 < min
[i
].m_count
1119 || (min
[j
].m_count
+ 1 == min
[i
].m_count
1120 && s
< min
[i
].m_non_jt_cases
))
1121 && can_be_handled (clusters
, j
, i
- 1))
1122 min
[i
] = min_cluster_item (min
[j
].m_count
+ 1, j
, s
);
1127 if (min
[l
].m_count
== INT_MAX
)
1128 return clusters
.copy ();
1130 vec
<cluster
*> output
;
1133 /* Find and build the clusters. */
1136 int start
= min
[end
].m_start
;
1138 /* Do not allow clusters with small number of cases. */
1139 if (is_beneficial (clusters
, start
, end
- 1))
1140 output
.safe_push (new jump_table_cluster (clusters
, start
, end
- 1));
1142 for (int i
= end
- 1; i
>= start
; i
--)
1143 output
.safe_push (clusters
[i
]);
1155 /* Return true when cluster starting at START and ending at END (inclusive)
1156 can build a jump-table. */
1159 jump_table_cluster::can_be_handled (const vec
<cluster
*> &clusters
,
1160 unsigned start
, unsigned end
)
1162 /* If the switch is relatively small such that the cost of one
1163 indirect jump on the target are higher than the cost of a
1164 decision tree, go with the decision tree.
1166 If range of values is much bigger than number of values,
1167 or if it is too large to represent in a HOST_WIDE_INT,
1168 make a sequence of conditional branches instead of a dispatch.
1170 The definition of "much bigger" depends on whether we are
1171 optimizing for size or for speed. */
1172 if (!flag_jump_tables
)
1175 unsigned HOST_WIDE_INT max_ratio
= optimize_insn_for_size_p () ? 3 : 8;
1177 unsigned HOST_WIDE_INT range
= get_range (clusters
[start
]->get_low (),
1178 clusters
[end
]->get_high ());
1179 /* Check overflow. */
1183 unsigned HOST_WIDE_INT comparison_count
= 0;
1184 for (unsigned i
= start
; i
<= end
; i
++)
1186 simple_cluster
*sc
= static_cast<simple_cluster
*> (clusters
[i
]);
1187 comparison_count
+= sc
->m_range_p
? 2 : 1;
1190 return range
<= max_ratio
* comparison_count
;
1193 /* Return true if cluster starting at START and ending at END (inclusive)
1194 is profitable transformation. */
1197 jump_table_cluster::is_beneficial (const vec
<cluster
*> &,
1198 unsigned start
, unsigned end
)
1200 return end
- start
+ 1 >= case_values_threshold ();
1203 /* Find bit tests of given CLUSTERS, where all members of the vector
1204 are of type simple_cluster. New clusters are returned. */
1207 bit_test_cluster::find_bit_tests (vec
<cluster
*> &clusters
)
1209 vec
<cluster
*> output
;
1212 unsigned l
= clusters
.length ();
1213 auto_vec
<min_cluster_item
> min
;
1214 min
.reserve (l
+ 1);
1216 min
.quick_push (min_cluster_item (0, 0, 0));
1218 for (unsigned i
= 1; i
<= l
; i
++)
1220 /* Set minimal # of clusters with i-th item to infinite. */
1221 min
.quick_push (min_cluster_item (INT_MAX
, INT_MAX
, INT_MAX
));
1223 for (unsigned j
= 0; j
< i
; j
++)
1225 if (min
[j
].m_count
+ 1 < min
[i
].m_count
1226 && can_be_handled (clusters
, j
, i
- 1))
1227 min
[i
] = min_cluster_item (min
[j
].m_count
+ 1, j
, INT_MAX
);
1232 if (min
[l
].m_count
== INT_MAX
)
1233 return clusters
.copy ();
1235 /* Find and build the clusters. */
1238 int start
= min
[end
].m_start
;
1240 if (is_beneficial (clusters
, start
, end
- 1))
1241 output
.safe_push (new bit_test_cluster (clusters
, start
, end
- 1));
1243 for (int i
= end
- 1; i
>= start
; i
--)
1244 output
.safe_push (clusters
[i
]);
1256 /* Return true when RANGE of case values with UNIQ labels
1257 can build a bit test. */
1260 bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range
,
1263 /* Check overflow. */
1267 if (range
>= GET_MODE_BITSIZE (word_mode
))
1273 /* Return true when cluster starting at START and ending at END (inclusive)
1274 can build a bit test. */
1277 bit_test_cluster::can_be_handled (const vec
<cluster
*> &clusters
,
1278 unsigned start
, unsigned end
)
1280 unsigned HOST_WIDE_INT range
= get_range (clusters
[start
]->get_low (),
1281 clusters
[end
]->get_high ());
1282 auto_bitmap dest_bbs
;
1284 for (unsigned i
= start
; i
<= end
; i
++)
1286 simple_cluster
*sc
= static_cast<simple_cluster
*> (clusters
[i
]);
1287 bitmap_set_bit (dest_bbs
, sc
->m_case_bb
->index
);
1290 return can_be_handled (range
, bitmap_count_bits (dest_bbs
));
1293 /* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1297 bit_test_cluster::is_beneficial (unsigned count
, unsigned uniq
)
1299 return (((uniq
== 1 && count
>= 3)
1300 || (uniq
== 2 && count
>= 5)
1301 || (uniq
== 3 && count
>= 6)));
1304 /* Return true if cluster starting at START and ending at END (inclusive)
1305 is profitable transformation. */
1308 bit_test_cluster::is_beneficial (const vec
<cluster
*> &clusters
,
1309 unsigned start
, unsigned end
)
1311 auto_bitmap dest_bbs
;
1313 for (unsigned i
= start
; i
<= end
; i
++)
1315 simple_cluster
*sc
= static_cast<simple_cluster
*> (clusters
[i
]);
1316 bitmap_set_bit (dest_bbs
, sc
->m_case_bb
->index
);
1319 unsigned uniq
= bitmap_count_bits (dest_bbs
);
1320 unsigned count
= end
- start
+ 1;
1321 return is_beneficial (count
, uniq
);
1324 /* Comparison function for qsort to order bit tests by decreasing
1325 probability of execution. */
1328 case_bit_test::cmp (const void *p1
, const void *p2
)
1330 const struct case_bit_test
*const d1
= (const struct case_bit_test
*) p1
;
1331 const struct case_bit_test
*const d2
= (const struct case_bit_test
*) p2
;
1333 if (d2
->bits
!= d1
->bits
)
1334 return d2
->bits
- d1
->bits
;
1336 /* Stabilize the sort. */
1337 return (LABEL_DECL_UID (CASE_LABEL (d2
->label
))
1338 - LABEL_DECL_UID (CASE_LABEL (d1
->label
)));
1341 /* Expand a switch statement by a short sequence of bit-wise
1342 comparisons. "switch(x)" is effectively converted into
1343 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1346 INDEX_EXPR is the value being switched on.
1348 MINVAL is the lowest case value of in the case nodes,
1349 and RANGE is highest value minus MINVAL. MINVAL and RANGE
1350 are not guaranteed to be of the same type as INDEX_EXPR
1351 (the gimplifier doesn't change the type of case label values,
1352 and MINVAL and RANGE are derived from those values).
1353 MAXVAL is MINVAL + RANGE.
1355 There *MUST* be max_case_bit_tests or less unique case
1359 bit_test_cluster::emit (tree index_expr
, tree index_type
,
1360 tree
, basic_block default_bb
)
1362 struct case_bit_test test
[m_max_case_bit_tests
] = { {} };
1363 unsigned int i
, j
, k
;
1366 tree unsigned_index_type
= unsigned_type_for (index_type
);
1368 gimple_stmt_iterator gsi
;
1369 gassign
*shift_stmt
;
1371 tree idx
, tmp
, csui
;
1372 tree word_type_node
= lang_hooks
.types
.type_for_mode (word_mode
, 1);
1373 tree word_mode_zero
= fold_convert (word_type_node
, integer_zero_node
);
1374 tree word_mode_one
= fold_convert (word_type_node
, integer_one_node
);
1375 int prec
= TYPE_PRECISION (word_type_node
);
1376 wide_int wone
= wi::one (prec
);
1378 tree minval
= get_low ();
1379 tree maxval
= get_high ();
1380 tree range
= int_const_binop (MINUS_EXPR
, maxval
, minval
);
1382 /* Go through all case labels, and collect the case labels, profile
1383 counts, and other information we need to build the branch tests. */
1385 for (i
= 0; i
< m_cases
.length (); i
++)
1387 unsigned int lo
, hi
;
1388 simple_cluster
*n
= static_cast<simple_cluster
*> (m_cases
[i
]);
1389 for (k
= 0; k
< count
; k
++)
1390 if (n
->m_case_bb
== test
[k
].target_bb
)
1395 gcc_checking_assert (count
< m_max_case_bit_tests
);
1396 test
[k
].mask
= wi::zero (prec
);
1397 test
[k
].target_bb
= n
->m_case_bb
;
1398 test
[k
].label
= n
->m_case_label_expr
;
1405 lo
= tree_to_uhwi (int_const_binop (MINUS_EXPR
, n
->get_low (), minval
));
1406 if (n
->get_high () == NULL_TREE
)
1409 hi
= tree_to_uhwi (int_const_binop (MINUS_EXPR
, n
->get_high (),
1412 for (j
= lo
; j
<= hi
; j
++)
1413 test
[k
].mask
|= wi::lshift (wone
, j
);
1416 qsort (test
, count
, sizeof (*test
), case_bit_test::cmp
);
1418 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
1419 the minval subtractions, but it might make the mask constants more
1420 expensive. So, compare the costs. */
1421 if (compare_tree_int (minval
, 0) > 0
1422 && compare_tree_int (maxval
, GET_MODE_BITSIZE (word_mode
)) < 0)
1425 HOST_WIDE_INT m
= tree_to_uhwi (minval
);
1426 rtx reg
= gen_raw_REG (word_mode
, 10000);
1427 bool speed_p
= optimize_insn_for_speed_p ();
1428 cost_diff
= set_rtx_cost (gen_rtx_PLUS (word_mode
, reg
,
1429 GEN_INT (-m
)), speed_p
);
1430 for (i
= 0; i
< count
; i
++)
1432 rtx r
= immed_wide_int_const (test
[i
].mask
, word_mode
);
1433 cost_diff
+= set_src_cost (gen_rtx_AND (word_mode
, reg
, r
),
1434 word_mode
, speed_p
);
1435 r
= immed_wide_int_const (wi::lshift (test
[i
].mask
, m
), word_mode
);
1436 cost_diff
-= set_src_cost (gen_rtx_AND (word_mode
, reg
, r
),
1437 word_mode
, speed_p
);
1441 for (i
= 0; i
< count
; i
++)
1442 test
[i
].mask
= wi::lshift (test
[i
].mask
, m
);
1443 minval
= build_zero_cst (TREE_TYPE (minval
));
1448 /* Now build the test-and-branch code. */
1450 gsi
= gsi_last_bb (m_case_bb
);
1452 /* idx = (unsigned)x - minval. */
1453 idx
= fold_convert (unsigned_index_type
, index_expr
);
1454 idx
= fold_build2 (MINUS_EXPR
, unsigned_index_type
, idx
,
1455 fold_convert (unsigned_index_type
, minval
));
1456 idx
= force_gimple_operand_gsi (&gsi
, idx
,
1457 /*simple=*/true, NULL_TREE
,
1458 /*before=*/true, GSI_SAME_STMT
);
1460 /* if (idx > range) goto default */
1461 range
= force_gimple_operand_gsi (&gsi
,
1462 fold_convert (unsigned_index_type
, range
),
1463 /*simple=*/true, NULL_TREE
,
1464 /*before=*/true, GSI_SAME_STMT
);
1465 tmp
= fold_build2 (GT_EXPR
, boolean_type_node
, idx
, range
);
1466 basic_block new_bb
= hoist_edge_and_branch_if_true (&gsi
, tmp
, default_bb
);
1467 gsi
= gsi_last_bb (new_bb
);
1469 /* csui = (1 << (word_mode) idx) */
1470 csui
= make_ssa_name (word_type_node
);
1471 tmp
= fold_build2 (LSHIFT_EXPR
, word_type_node
, word_mode_one
,
1472 fold_convert (word_type_node
, idx
));
1473 tmp
= force_gimple_operand_gsi (&gsi
, tmp
,
1474 /*simple=*/false, NULL_TREE
,
1475 /*before=*/true, GSI_SAME_STMT
);
1476 shift_stmt
= gimple_build_assign (csui
, tmp
);
1477 gsi_insert_before (&gsi
, shift_stmt
, GSI_SAME_STMT
);
1478 update_stmt (shift_stmt
);
1480 /* for each unique set of cases:
1481 if (const & csui) goto target */
1482 for (k
= 0; k
< count
; k
++)
1484 tmp
= wide_int_to_tree (word_type_node
, test
[k
].mask
);
1485 tmp
= fold_build2 (BIT_AND_EXPR
, word_type_node
, csui
, tmp
);
1486 tmp
= force_gimple_operand_gsi (&gsi
, tmp
,
1487 /*simple=*/true, NULL_TREE
,
1488 /*before=*/true, GSI_SAME_STMT
);
1489 tmp
= fold_build2 (NE_EXPR
, boolean_type_node
, tmp
, word_mode_zero
);
1490 new_bb
= hoist_edge_and_branch_if_true (&gsi
, tmp
, test
[k
].target_bb
);
1491 gsi
= gsi_last_bb (new_bb
);
1494 /* We should have removed all edges now. */
1495 gcc_assert (EDGE_COUNT (gsi_bb (gsi
)->succs
) == 0);
1497 /* If nothing matched, go to the default label. */
1498 make_edge (gsi_bb (gsi
), default_bb
, EDGE_FALLTHRU
);
1501 /* Split the basic block at the statement pointed to by GSIP, and insert
1502 a branch to the target basic block of E_TRUE conditional on tree
1505 It is assumed that there is already an edge from the to-be-split
1506 basic block to E_TRUE->dest block. This edge is removed, and the
1507 profile information on the edge is re-used for the new conditional
1510 The CFG is updated. The dominator tree will not be valid after
1511 this transformation, but the immediate dominators are updated if
1512 UPDATE_DOMINATORS is true.
1514 Returns the newly created basic block. */
1517 bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator
*gsip
,
1518 tree cond
, basic_block case_bb
)
1523 basic_block new_bb
, split_bb
= gsi_bb (*gsip
);
1525 edge e_true
= make_edge (split_bb
, case_bb
, EDGE_TRUE_VALUE
);
1526 gcc_assert (e_true
->src
== split_bb
);
1528 tmp
= force_gimple_operand_gsi (gsip
, cond
, /*simple=*/true, NULL
,
1529 /*before=*/true, GSI_SAME_STMT
);
1530 cond_stmt
= gimple_build_cond_from_tree (tmp
, NULL_TREE
, NULL_TREE
);
1531 gsi_insert_before (gsip
, cond_stmt
, GSI_SAME_STMT
);
1533 e_false
= split_block (split_bb
, cond_stmt
);
1534 new_bb
= e_false
->dest
;
1535 redirect_edge_pred (e_true
, split_bb
);
1537 e_false
->flags
&= ~EDGE_FALLTHRU
;
1538 e_false
->flags
|= EDGE_FALSE_VALUE
;
1539 e_false
->probability
= e_true
->probability
.invert ();
1540 new_bb
->count
= e_false
->count ();
1545 /* Compute the number of case labels that correspond to each outgoing edge of
1546 switch statement. Record this information in the aux field of the edge. */
1549 switch_decision_tree::compute_cases_per_edge ()
1551 basic_block bb
= gimple_bb (m_switch
);
1552 reset_out_edges_aux ();
1553 int ncases
= gimple_switch_num_labels (m_switch
);
1554 for (int i
= ncases
- 1; i
>= 1; --i
)
1556 tree elt
= gimple_switch_label (m_switch
, i
);
1557 tree lab
= CASE_LABEL (elt
);
1558 basic_block case_bb
= label_to_block_fn (cfun
, lab
);
1559 edge case_edge
= find_edge (bb
, case_bb
);
1560 case_edge
->aux
= (void *) ((intptr_t) (case_edge
->aux
) + 1);
1564 /* Analyze switch statement and return true when the statement is expanded
1565 as decision tree. */
1568 switch_decision_tree::analyze_switch_statement ()
1570 unsigned l
= gimple_switch_num_labels (m_switch
);
1571 basic_block bb
= gimple_bb (m_switch
);
1572 auto_vec
<cluster
*> clusters
;
1573 clusters
.create (l
- 1);
1575 tree default_label
= CASE_LABEL (gimple_switch_default_label (m_switch
));
1576 basic_block default_bb
= label_to_block_fn (cfun
, default_label
);
1577 m_case_bbs
.reserve (l
);
1578 m_case_bbs
.quick_push (default_bb
);
1580 compute_cases_per_edge ();
1582 for (unsigned i
= 1; i
< l
; i
++)
1584 tree elt
= gimple_switch_label (m_switch
, i
);
1585 tree lab
= CASE_LABEL (elt
);
1586 basic_block case_bb
= label_to_block_fn (cfun
, lab
);
1587 edge case_edge
= find_edge (bb
, case_bb
);
1588 tree low
= CASE_LOW (elt
);
1589 tree high
= CASE_HIGH (elt
);
1591 profile_probability p
1592 = case_edge
->probability
.apply_scale (1, (intptr_t) (case_edge
->aux
));
1593 clusters
.quick_push (new simple_cluster (low
, high
, elt
, case_bb
, p
));
1594 m_case_bbs
.quick_push (case_bb
);
1597 reset_out_edges_aux ();
1599 /* Find jump table clusters. */
1600 vec
<cluster
*> output
= jump_table_cluster::find_jump_tables (clusters
);
1602 /* Find jump table clusters. */
1603 vec
<cluster
*> output2
;
1604 auto_vec
<cluster
*> tmp
;
1608 for (unsigned i
= 0; i
< output
.length (); i
++)
1610 cluster
*c
= output
[i
];
1611 if (c
->get_type () != SIMPLE_CASE
)
1613 if (!tmp
.is_empty ())
1615 vec
<cluster
*> n
= bit_test_cluster::find_bit_tests (tmp
);
1616 output2
.safe_splice (n
);
1620 output2
.safe_push (c
);
1626 /* We still can have a temporary vector to test. */
1627 if (!tmp
.is_empty ())
1629 vec
<cluster
*> n
= bit_test_cluster::find_bit_tests (tmp
);
1630 output2
.safe_splice (n
);
1636 fprintf (dump_file
, ";; GIMPLE switch case clusters: ");
1637 for (unsigned i
= 0; i
< output2
.length (); i
++)
1638 output2
[i
]->dump (dump_file
, dump_flags
& TDF_DETAILS
);
1639 fprintf (dump_file
, "\n");
1644 bool expanded
= try_switch_expansion (output2
);
1646 for (unsigned i
= 0; i
< output2
.length (); i
++)
1654 /* Attempt to expand CLUSTERS as a decision tree. Return true when
1658 switch_decision_tree::try_switch_expansion (vec
<cluster
*> &clusters
)
1660 tree index_expr
= gimple_switch_index (m_switch
);
1661 tree index_type
= TREE_TYPE (index_expr
);
1662 basic_block bb
= gimple_bb (m_switch
);
1664 if (gimple_switch_num_labels (m_switch
) == 1)
1667 /* Find the default case target label. */
1668 tree default_label_expr
= CASE_LABEL (gimple_switch_default_label (m_switch
));
1669 m_default_bb
= label_to_block_fn (cfun
, default_label_expr
);
1670 edge default_edge
= find_edge (bb
, m_default_bb
);
1672 /* Do the insertion of a case label into m_case_list. The labels are
1673 fed to us in descending order from the sorted vector of case labels used
1674 in the tree part of the middle end. So the list we construct is
1675 sorted in ascending order. */
1677 for (int i
= clusters
.length () - 1; i
>= 0; i
--)
1679 case_tree_node
*r
= m_case_list
;
1680 m_case_list
= m_case_node_pool
.allocate ();
1681 m_case_list
->m_right
= r
;
1682 m_case_list
->m_c
= clusters
[i
];
1685 record_phi_operand_mapping ();
1687 /* Split basic block that contains the gswitch statement. */
1688 gimple_stmt_iterator gsi
= gsi_last_bb (bb
);
1690 if (gsi_end_p (gsi
))
1691 e
= split_block_after_labels (bb
);
1695 e
= split_block (bb
, gsi_stmt (gsi
));
1697 bb
= split_edge (e
);
1699 /* Create new basic blocks for non-case clusters where specific expansion
1701 for (unsigned i
= 0; i
< clusters
.length (); i
++)
1702 if (clusters
[i
]->get_type () != SIMPLE_CASE
)
1704 clusters
[i
]->m_case_bb
= create_empty_bb (bb
);
1705 clusters
[i
]->m_case_bb
->loop_father
= bb
->loop_father
;
1708 /* Do not do an extra work for a single cluster. */
1709 if (clusters
.length () == 1
1710 && clusters
[0]->get_type () != SIMPLE_CASE
)
1711 clusters
[0]->emit (index_expr
, index_type
,
1712 gimple_switch_default_label (m_switch
), m_default_bb
);
1715 emit (bb
, index_expr
, default_edge
->probability
, index_type
);
1717 /* Emit cluster-specific switch handling. */
1718 for (unsigned i
= 0; i
< clusters
.length (); i
++)
1719 if (clusters
[i
]->get_type () != SIMPLE_CASE
)
1720 clusters
[i
]->emit (index_expr
, index_type
,
1721 gimple_switch_default_label (m_switch
),
1725 fix_phi_operands_for_edges ();
1730 /* Before switch transformation, record all SSA_NAMEs defined in switch BB
1731 and used in a label basic block. */
1734 switch_decision_tree::record_phi_operand_mapping ()
1736 basic_block switch_bb
= gimple_bb (m_switch
);
1737 /* Record all PHI nodes that have to be fixed after conversion. */
1738 for (unsigned i
= 0; i
< m_case_bbs
.length (); i
++)
1741 basic_block bb
= m_case_bbs
[i
];
1742 for (gsi
= gsi_start_phis (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
1744 gphi
*phi
= gsi
.phi ();
1746 for (unsigned i
= 0; i
< gimple_phi_num_args (phi
); i
++)
1748 basic_block phi_src_bb
= gimple_phi_arg_edge (phi
, i
)->src
;
1749 if (phi_src_bb
== switch_bb
)
1751 tree def
= gimple_phi_arg_def (phi
, i
);
1752 tree result
= gimple_phi_result (phi
);
1753 m_phi_mapping
.put (result
, def
);
1761 /* Append new operands to PHI statements that were introduced due to
1762 addition of new edges to case labels. */
1765 switch_decision_tree::fix_phi_operands_for_edges ()
1769 for (unsigned i
= 0; i
< m_case_bbs
.length (); i
++)
1771 basic_block bb
= m_case_bbs
[i
];
1772 for (gsi
= gsi_start_phis (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
1774 gphi
*phi
= gsi
.phi ();
1775 for (unsigned j
= 0; j
< gimple_phi_num_args (phi
); j
++)
1777 tree def
= gimple_phi_arg_def (phi
, j
);
1778 if (def
== NULL_TREE
)
1780 edge e
= gimple_phi_arg_edge (phi
, j
);
1782 = m_phi_mapping
.get (gimple_phi_result (phi
));
1783 gcc_assert (definition
);
1784 add_phi_arg (phi
, *definition
, e
, UNKNOWN_LOCATION
);
1791 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1792 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1794 We generate a binary decision tree to select the appropriate target
1798 switch_decision_tree::emit (basic_block bb
, tree index_expr
,
1799 profile_probability default_prob
, tree index_type
)
1801 balance_case_nodes (&m_case_list
, NULL
);
1804 dump_function_to_file (current_function_decl
, dump_file
, dump_flags
);
1805 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1807 int indent_step
= ceil_log2 (TYPE_PRECISION (index_type
)) + 2;
1808 fprintf (dump_file
, ";; Expanding GIMPLE switch as decision tree:\n");
1809 gcc_assert (m_case_list
!= NULL
);
1810 dump_case_nodes (dump_file
, m_case_list
, indent_step
, 0);
1813 bb
= emit_case_nodes (bb
, index_expr
, m_case_list
, default_prob
, index_type
);
1816 emit_jump (bb
, m_default_bb
);
1818 /* Remove all edges and do just an edge that will reach default_bb. */
1819 bb
= gimple_bb (m_switch
);
1820 gimple_stmt_iterator gsi
= gsi_last_bb (bb
);
1821 gsi_remove (&gsi
, true);
1823 delete_basic_block (bb
);
1826 /* Take an ordered list of case nodes
1827 and transform them into a near optimal binary tree,
1828 on the assumption that any target code selection value is as
1829 likely as any other.
1831 The transformation is performed by splitting the ordered
1832 list into two equal sections plus a pivot. The parts are
1833 then attached to the pivot as left and right branches. Each
1834 branch is then transformed recursively. */
1837 switch_decision_tree::balance_case_nodes (case_tree_node
**head
,
1838 case_tree_node
*parent
)
1847 case_tree_node
**npp
;
1848 case_tree_node
*left
;
1850 /* Count the number of entries on branch. Also count the ranges. */
1854 if (!tree_int_cst_equal (np
->m_c
->get_low (), np
->m_c
->get_high ()))
1863 /* Split this list if it is long enough for that to help. */
1867 /* If there are just three nodes, split at the middle one. */
1869 npp
= &(*npp
)->m_right
;
1872 /* Find the place in the list that bisects the list's total cost,
1873 where ranges count as 2.
1874 Here I gets half the total cost. */
1875 i
= (i
+ ranges
+ 1) / 2;
1878 /* Skip nodes while their cost does not reach that amount. */
1879 if (!tree_int_cst_equal ((*npp
)->m_c
->get_low (),
1880 (*npp
)->m_c
->get_high ()))
1885 npp
= &(*npp
)->m_right
;
1890 np
->m_parent
= parent
;
1893 /* Optimize each of the two split parts. */
1894 balance_case_nodes (&np
->m_left
, np
);
1895 balance_case_nodes (&np
->m_right
, np
);
1896 np
->m_c
->m_subtree_prob
= np
->m_c
->m_prob
;
1897 np
->m_c
->m_subtree_prob
+= np
->m_left
->m_c
->m_subtree_prob
;
1898 np
->m_c
->m_subtree_prob
+= np
->m_right
->m_c
->m_subtree_prob
;
1902 /* Else leave this branch as one level,
1903 but fill in `parent' fields. */
1905 np
->m_parent
= parent
;
1906 np
->m_c
->m_subtree_prob
= np
->m_c
->m_prob
;
1907 for (; np
->m_right
; np
= np
->m_right
)
1909 np
->m_right
->m_parent
= np
;
1910 (*head
)->m_c
->m_subtree_prob
+= np
->m_right
->m_c
->m_subtree_prob
;
1916 /* Dump ROOT, a list or tree of case nodes, to file. */
1919 switch_decision_tree::dump_case_nodes (FILE *f
, case_tree_node
*root
,
1920 int indent_step
, int indent_level
)
1926 dump_case_nodes (f
, root
->m_left
, indent_step
, indent_level
);
1929 fprintf (f
, "%*s", indent_step
* indent_level
, "");
1930 root
->m_c
->dump (f
);
1931 root
->m_c
->m_prob
.dump (f
);
1934 dump_case_nodes (f
, root
->m_right
, indent_step
, indent_level
);
1938 /* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1941 switch_decision_tree::emit_jump (basic_block bb
, basic_block case_bb
)
1943 edge e
= single_succ_edge (bb
);
1944 redirect_edge_succ (e
, case_bb
);
1947 /* Generate code to compare OP0 with OP1 so that the condition codes are
1948 set and to jump to LABEL_BB if the condition is true.
1949 COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
1950 PROB is the probability of jumping to LABEL_BB. */
1953 switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb
, tree op0
,
1954 tree op1
, tree_code comparison
,
1955 basic_block label_bb
,
1956 profile_probability prob
)
1958 // TODO: it's once called with lhs != index.
1959 op1
= fold_convert (TREE_TYPE (op0
), op1
);
1961 gcond
*cond
= gimple_build_cond (comparison
, op0
, op1
, NULL_TREE
, NULL_TREE
);
1962 gimple_stmt_iterator gsi
= gsi_last_bb (bb
);
1963 gsi_insert_after (&gsi
, cond
, GSI_NEW_STMT
);
1965 gcc_assert (single_succ_p (bb
));
1967 /* Make a new basic block where false branch will take place. */
1968 edge false_edge
= split_block (bb
, cond
);
1969 false_edge
->flags
= EDGE_FALSE_VALUE
;
1970 false_edge
->probability
= prob
.invert ();
1972 edge true_edge
= make_edge (bb
, label_bb
, EDGE_TRUE_VALUE
);
1973 true_edge
->probability
= prob
;
1975 return false_edge
->dest
;
1978 /* Emit step-by-step code to select a case for the value of INDEX.
1979 The thus generated decision tree follows the form of the
1980 case-node binary tree NODE, whose nodes represent test conditions.
1981 DEFAULT_PROB is probability of cases leading to default BB.
1982 INDEX_TYPE is the type of the index of the switch. */
1985 switch_decision_tree::emit_case_nodes (basic_block bb
, tree index
,
1986 case_tree_node
*node
,
1987 profile_probability default_prob
,
1990 /* If node is null, we are done. */
1994 /* Branch to a label where we will handle it later. */
1995 basic_block test_bb
= split_edge (single_succ_edge (bb
));
1996 redirect_edge_succ (single_pred_edge (test_bb
),
1997 single_succ_edge (bb
)->dest
);
1999 profile_probability probability
2001 ? node
->m_right
->m_c
->m_subtree_prob
: profile_probability::never ());
2002 probability
= ((probability
+ default_prob
.apply_scale (1, 2))
2003 / (node
->m_c
->m_subtree_prob
+ default_prob
));
2004 bb
= emit_cmp_and_jump_insns (bb
, index
, node
->m_c
->get_high (), GT_EXPR
,
2005 test_bb
, probability
);
2006 default_prob
= default_prob
.apply_scale (1, 2);
2008 /* Value belongs to this node or to the left-hand subtree. */
2009 probability
= node
->m_c
->m_prob
/
2010 (node
->m_c
->m_subtree_prob
+ default_prob
);
2011 bb
= emit_cmp_and_jump_insns (bb
, index
, node
->m_c
->get_low (), GE_EXPR
,
2012 node
->m_c
->m_case_bb
, probability
);
2014 /* Handle the left-hand subtree. */
2015 bb
= emit_case_nodes (bb
, index
, node
->m_left
,
2016 default_prob
, index_type
);
2018 /* If the left-hand subtree fell through,
2019 don't let it fall into the right-hand subtree. */
2021 emit_jump (bb
, m_default_bb
);
2023 bb
= emit_case_nodes (test_bb
, index
, node
->m_right
,
2024 default_prob
, index_type
);
2029 /* The main function of the pass scans statements for switches and invokes
2030 process_switch on them. */
2034 const pass_data pass_data_convert_switch
=
2036 GIMPLE_PASS
, /* type */
2037 "switchconv", /* name */
2038 OPTGROUP_NONE
, /* optinfo_flags */
2039 TV_TREE_SWITCH_CONVERSION
, /* tv_id */
2040 ( PROP_cfg
| PROP_ssa
), /* properties_required */
2041 0, /* properties_provided */
2042 0, /* properties_destroyed */
2043 0, /* todo_flags_start */
2044 TODO_update_ssa
, /* todo_flags_finish */
2047 class pass_convert_switch
: public gimple_opt_pass
2050 pass_convert_switch (gcc::context
*ctxt
)
2051 : gimple_opt_pass (pass_data_convert_switch
, ctxt
)
2054 /* opt_pass methods: */
2055 virtual bool gate (function
*) { return flag_tree_switch_conversion
!= 0; }
2056 virtual unsigned int execute (function
*);
2058 }; // class pass_convert_switch
2061 pass_convert_switch::execute (function
*fun
)
2064 bool cfg_altered
= false;
2066 FOR_EACH_BB_FN (bb
, fun
)
2068 gimple
*stmt
= last_stmt (bb
);
2069 if (stmt
&& gimple_code (stmt
) == GIMPLE_SWITCH
)
2073 expanded_location loc
= expand_location (gimple_location (stmt
));
2075 fprintf (dump_file
, "beginning to process the following "
2076 "SWITCH statement (%s:%d) : ------- \n",
2077 loc
.file
, loc
.line
);
2078 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
2079 putc ('\n', dump_file
);
2082 switch_conversion sconv
;
2083 sconv
.expand (as_a
<gswitch
*> (stmt
));
2084 cfg_altered
|= sconv
.m_cfg_altered
;
2085 if (!sconv
.m_reason
)
2089 fputs ("Switch converted\n", dump_file
);
2090 fputs ("--------------------------------\n", dump_file
);
2093 /* Make no effort to update the post-dominator tree.
2094 It is actually not that hard for the transformations
2095 we have performed, but it is not supported
2096 by iterate_fix_dominators. */
2097 free_dominance_info (CDI_POST_DOMINATORS
);
2103 fputs ("Bailing out - ", dump_file
);
2104 fputs (sconv
.m_reason
, dump_file
);
2105 fputs ("\n--------------------------------\n", dump_file
);
2111 return cfg_altered
? TODO_cleanup_cfg
: 0;;
2117 make_pass_convert_switch (gcc::context
*ctxt
)
2119 return new pass_convert_switch (ctxt
);
2122 /* The main function of the pass scans statements for switches and invokes
2123 process_switch on them. */
2127 template <bool O0
> class pass_lower_switch
: public gimple_opt_pass
2130 pass_lower_switch (gcc::context
*ctxt
) : gimple_opt_pass (data
, ctxt
) {}
2132 static const pass_data data
;
2136 return new pass_lower_switch
<O0
> (m_ctxt
);
2142 return !O0
|| !optimize
;
2145 virtual unsigned int execute (function
*fun
);
2146 }; // class pass_lower_switch
2149 const pass_data pass_lower_switch
<O0
>::data
= {
2150 GIMPLE_PASS
, /* type */
2151 O0
? "switchlower_O0" : "switchlower", /* name */
2152 OPTGROUP_NONE
, /* optinfo_flags */
2153 TV_TREE_SWITCH_LOWERING
, /* tv_id */
2154 ( PROP_cfg
| PROP_ssa
), /* properties_required */
2155 0, /* properties_provided */
2156 0, /* properties_destroyed */
2157 0, /* todo_flags_start */
2158 TODO_update_ssa
| TODO_cleanup_cfg
, /* todo_flags_finish */
2163 pass_lower_switch
<O0
>::execute (function
*fun
)
2166 bool expanded
= false;
2168 auto_vec
<gimple
*> switch_statements
;
2169 switch_statements
.create (1);
2171 FOR_EACH_BB_FN (bb
, fun
)
2173 gimple
*stmt
= last_stmt (bb
);
2174 if (stmt
&& gimple_code (stmt
) == GIMPLE_SWITCH
)
2175 switch_statements
.safe_push (stmt
);
2178 for (unsigned i
= 0; i
< switch_statements
.length (); i
++)
2180 gimple
*stmt
= switch_statements
[i
];
2183 expanded_location loc
= expand_location (gimple_location (stmt
));
2185 fprintf (dump_file
, "beginning to process the following "
2186 "SWITCH statement (%s:%d) : ------- \n",
2187 loc
.file
, loc
.line
);
2188 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
2189 putc ('\n', dump_file
);
2192 gswitch
*swtch
= dyn_cast
<gswitch
*> (stmt
);
2195 switch_decision_tree
dt (swtch
);
2196 expanded
|= dt
.analyze_switch_statement ();
2202 free_dominance_info (CDI_DOMINATORS
);
2203 free_dominance_info (CDI_POST_DOMINATORS
);
2204 mark_virtual_operands_for_renaming (cfun
);
2213 make_pass_lower_switch_O0 (gcc::context
*ctxt
)
2215 return new pass_lower_switch
<true> (ctxt
);
2218 make_pass_lower_switch (gcc::context
*ctxt
)
2220 return new pass_lower_switch
<false> (ctxt
);