PR tree-optimization/84740
[official-gcc.git] / gcc / tree-switch-conversion.c
blob2da7068345cd1bddee0d632d6ef727a384685987
1 /* Lower GIMPLE_SWITCH expressions to something more efficient than
2 a jump table.
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
10 later version.
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
15 for more details.
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
20 02110-1301, USA. */
22 /* This file handles the lowering of GIMPLE_SWITCH to an indexed
23 load, or a series of bit-test-and-branch expressions. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "backend.h"
29 #include "insn-codes.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "cfghooks.h"
34 #include "tree-pass.h"
35 #include "ssa.h"
36 #include "optabs-tree.h"
37 #include "cgraph.h"
38 #include "gimple-pretty-print.h"
39 #include "params.h"
40 #include "fold-const.h"
41 #include "varasm.h"
42 #include "stor-layout.h"
43 #include "cfganal.h"
44 #include "gimplify.h"
45 #include "gimple-iterator.h"
46 #include "gimplify-me.h"
47 #include "tree-cfg.h"
48 #include "cfgloop.h"
49 #include "alloc-pool.h"
50 #include "target.h"
51 #include "tree-into-ssa.h"
53 /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
54 type in the GIMPLE type system that is language-independent? */
55 #include "langhooks.h"
58 /* Maximum number of case bit tests.
59 FIXME: This should be derived from PARAM_CASE_VALUES_THRESHOLD and
60 targetm.case_values_threshold(), or be its own param. */
61 #define MAX_CASE_BIT_TESTS 3
63 /* Track whether or not we have altered the CFG and thus may need to
64 cleanup the CFG when complete. */
65 bool cfg_altered;
67 /* Split the basic block at the statement pointed to by GSIP, and insert
68 a branch to the target basic block of E_TRUE conditional on tree
69 expression COND.
71 It is assumed that there is already an edge from the to-be-split
72 basic block to E_TRUE->dest block. This edge is removed, and the
73 profile information on the edge is re-used for the new conditional
74 jump.
76 The CFG is updated. The dominator tree will not be valid after
77 this transformation, but the immediate dominators are updated if
78 UPDATE_DOMINATORS is true.
80 Returns the newly created basic block. */
82 static basic_block
83 hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
84 tree cond, edge e_true,
85 bool update_dominators)
87 tree tmp;
88 gcond *cond_stmt;
89 edge e_false;
90 basic_block new_bb, split_bb = gsi_bb (*gsip);
91 bool dominated_e_true = false;
93 gcc_assert (e_true->src == split_bb);
95 if (update_dominators
96 && get_immediate_dominator (CDI_DOMINATORS, e_true->dest) == split_bb)
97 dominated_e_true = true;
99 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
100 /*before=*/true, GSI_SAME_STMT);
101 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
102 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
104 e_false = split_block (split_bb, cond_stmt);
105 new_bb = e_false->dest;
106 redirect_edge_pred (e_true, split_bb);
108 e_true->flags &= ~EDGE_FALLTHRU;
109 e_true->flags |= EDGE_TRUE_VALUE;
111 e_false->flags &= ~EDGE_FALLTHRU;
112 e_false->flags |= EDGE_FALSE_VALUE;
113 e_false->probability = e_true->probability.invert ();
114 new_bb->count = e_false->count ();
116 if (update_dominators)
118 if (dominated_e_true)
119 set_immediate_dominator (CDI_DOMINATORS, e_true->dest, split_bb);
120 set_immediate_dominator (CDI_DOMINATORS, e_false->dest, split_bb);
123 return new_bb;
127 /* Return true if a switch should be expanded as a bit test.
128 RANGE is the difference between highest and lowest case.
129 UNIQ is number of unique case node targets, not counting the default case.
130 COUNT is the number of comparisons needed, not counting the default case. */
132 static bool
133 expand_switch_using_bit_tests_p (tree range,
134 unsigned int uniq,
135 unsigned int count, bool speed_p)
137 return (((uniq == 1 && count >= 3)
138 || (uniq == 2 && count >= 5)
139 || (uniq == 3 && count >= 6))
140 && lshift_cheap_p (speed_p)
141 && compare_tree_int (range, GET_MODE_BITSIZE (word_mode)) < 0
142 && compare_tree_int (range, 0) > 0);
145 /* Implement switch statements with bit tests
147 A GIMPLE switch statement can be expanded to a short sequence of bit-wise
148 comparisons. "switch(x)" is converted into "if ((1 << (x-MINVAL)) & CST)"
149 where CST and MINVAL are integer constants. This is better than a series
150 of compare-and-banch insns in some cases, e.g. we can implement:
152 if ((x==4) || (x==6) || (x==9) || (x==11))
154 as a single bit test:
156 if ((1<<x) & ((1<<4)|(1<<6)|(1<<9)|(1<<11)))
158 This transformation is only applied if the number of case targets is small,
159 if CST constains at least 3 bits, and "1 << x" is cheap. The bit tests are
160 performed in "word_mode".
162 The following example shows the code the transformation generates:
164 int bar(int x)
166 switch (x)
168 case '0': case '1': case '2': case '3': case '4':
169 case '5': case '6': case '7': case '8': case '9':
170 case 'A': case 'B': case 'C': case 'D': case 'E':
171 case 'F':
172 return 1;
174 return 0;
179 bar (int x)
181 tmp1 = x - 48;
182 if (tmp1 > (70 - 48)) goto L2;
183 tmp2 = 1 << tmp1;
184 tmp3 = 0b11111100000001111111111;
185 if ((tmp2 & tmp3) != 0) goto L1 ; else goto L2;
187 return 1;
189 return 0;
192 TODO: There are still some improvements to this transformation that could
193 be implemented:
195 * A narrower mode than word_mode could be used if that is cheaper, e.g.
196 for x86_64 where a narrower-mode shift may result in smaller code.
198 * The compounded constant could be shifted rather than the one. The
199 test would be either on the sign bit or on the least significant bit,
200 depending on the direction of the shift. On some machines, the test
201 for the branch would be free if the bit to test is already set by the
202 shift operation.
204 This transformation was contributed by Roger Sayle, see this e-mail:
205 http://gcc.gnu.org/ml/gcc-patches/2003-01/msg01950.html
208 /* A case_bit_test represents a set of case nodes that may be
209 selected from using a bit-wise comparison. HI and LO hold
210 the integer to be tested against, TARGET_EDGE contains the
211 edge to the basic block to jump to upon success and BITS
212 counts the number of case nodes handled by this test,
213 typically the number of bits set in HI:LO. The LABEL field
214 is used to quickly identify all cases in this set without
215 looking at label_to_block for every case label. */
217 struct case_bit_test
219 wide_int mask;
220 edge target_edge;
221 tree label;
222 int bits;
225 /* Comparison function for qsort to order bit tests by decreasing
226 probability of execution. Our best guess comes from a measured
227 profile. If the profile counts are equal, break even on the
228 number of case nodes, i.e. the node with the most cases gets
229 tested first.
231 TODO: Actually this currently runs before a profile is available.
232 Therefore the case-as-bit-tests transformation should be done
233 later in the pass pipeline, or something along the lines of
234 "Efficient and effective branch reordering using profile data"
235 (Yang et. al., 2002) should be implemented (although, how good
236 is a paper is called "Efficient and effective ..." when the
237 latter is implied by the former, but oh well...). */
239 static int
240 case_bit_test_cmp (const void *p1, const void *p2)
242 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
243 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
245 if (d2->target_edge->count () < d1->target_edge->count ())
246 return -1;
247 if (d2->target_edge->count () > d1->target_edge->count ())
248 return 1;
249 if (d2->bits != d1->bits)
250 return d2->bits - d1->bits;
252 /* Stabilize the sort. */
253 return LABEL_DECL_UID (d2->label) - LABEL_DECL_UID (d1->label);
256 /* Expand a switch statement by a short sequence of bit-wise
257 comparisons. "switch(x)" is effectively converted into
258 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
259 integer constants.
261 INDEX_EXPR is the value being switched on.
263 MINVAL is the lowest case value of in the case nodes,
264 and RANGE is highest value minus MINVAL. MINVAL and RANGE
265 are not guaranteed to be of the same type as INDEX_EXPR
266 (the gimplifier doesn't change the type of case label values,
267 and MINVAL and RANGE are derived from those values).
268 MAXVAL is MINVAL + RANGE.
270 There *MUST* be MAX_CASE_BIT_TESTS or less unique case
271 node targets. */
273 static void
274 emit_case_bit_tests (gswitch *swtch, tree index_expr,
275 tree minval, tree range, tree maxval)
277 struct case_bit_test test[MAX_CASE_BIT_TESTS] = { {} };
278 unsigned int i, j, k;
279 unsigned int count;
281 basic_block switch_bb = gimple_bb (swtch);
282 basic_block default_bb, new_default_bb, new_bb;
283 edge default_edge;
284 bool update_dom = dom_info_available_p (CDI_DOMINATORS);
286 vec<basic_block> bbs_to_fix_dom = vNULL;
288 tree index_type = TREE_TYPE (index_expr);
289 tree unsigned_index_type = unsigned_type_for (index_type);
290 unsigned int branch_num = gimple_switch_num_labels (swtch);
292 gimple_stmt_iterator gsi;
293 gassign *shift_stmt;
295 tree idx, tmp, csui;
296 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
297 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
298 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
299 int prec = TYPE_PRECISION (word_type_node);
300 wide_int wone = wi::one (prec);
302 /* Get the edge for the default case. */
303 tmp = gimple_switch_default_label (swtch);
304 default_bb = label_to_block (CASE_LABEL (tmp));
305 default_edge = find_edge (switch_bb, default_bb);
307 /* Go through all case labels, and collect the case labels, profile
308 counts, and other information we need to build the branch tests. */
309 count = 0;
310 for (i = 1; i < branch_num; i++)
312 unsigned int lo, hi;
313 tree cs = gimple_switch_label (swtch, i);
314 tree label = CASE_LABEL (cs);
315 edge e = find_edge (switch_bb, label_to_block (label));
316 for (k = 0; k < count; k++)
317 if (e == test[k].target_edge)
318 break;
320 if (k == count)
322 gcc_checking_assert (count < MAX_CASE_BIT_TESTS);
323 test[k].mask = wi::zero (prec);
324 test[k].target_edge = e;
325 test[k].label = label;
326 test[k].bits = 1;
327 count++;
329 else
330 test[k].bits++;
332 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR,
333 CASE_LOW (cs), minval));
334 if (CASE_HIGH (cs) == NULL_TREE)
335 hi = lo;
336 else
337 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR,
338 CASE_HIGH (cs), minval));
340 for (j = lo; j <= hi; j++)
341 test[k].mask |= wi::lshift (wone, j);
344 qsort (test, count, sizeof (*test), case_bit_test_cmp);
346 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
347 the minval subtractions, but it might make the mask constants more
348 expensive. So, compare the costs. */
349 if (compare_tree_int (minval, 0) > 0
350 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
352 int cost_diff;
353 HOST_WIDE_INT m = tree_to_uhwi (minval);
354 rtx reg = gen_raw_REG (word_mode, 10000);
355 bool speed_p = optimize_bb_for_speed_p (gimple_bb (swtch));
356 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
357 GEN_INT (-m)), speed_p);
358 for (i = 0; i < count; i++)
360 rtx r = immed_wide_int_const (test[i].mask, word_mode);
361 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
362 word_mode, speed_p);
363 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
364 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
365 word_mode, speed_p);
367 if (cost_diff > 0)
369 for (i = 0; i < count; i++)
370 test[i].mask = wi::lshift (test[i].mask, m);
371 minval = build_zero_cst (TREE_TYPE (minval));
372 range = maxval;
376 /* We generate two jumps to the default case label.
377 Split the default edge, so that we don't have to do any PHI node
378 updating. */
379 new_default_bb = split_edge (default_edge);
381 if (update_dom)
383 bbs_to_fix_dom.create (10);
384 bbs_to_fix_dom.quick_push (switch_bb);
385 bbs_to_fix_dom.quick_push (default_bb);
386 bbs_to_fix_dom.quick_push (new_default_bb);
389 /* Now build the test-and-branch code. */
391 gsi = gsi_last_bb (switch_bb);
393 /* idx = (unsigned)x - minval. */
394 idx = fold_convert (unsigned_index_type, index_expr);
395 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
396 fold_convert (unsigned_index_type, minval));
397 idx = force_gimple_operand_gsi (&gsi, idx,
398 /*simple=*/true, NULL_TREE,
399 /*before=*/true, GSI_SAME_STMT);
401 /* if (idx > range) goto default */
402 range = force_gimple_operand_gsi (&gsi,
403 fold_convert (unsigned_index_type, range),
404 /*simple=*/true, NULL_TREE,
405 /*before=*/true, GSI_SAME_STMT);
406 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
407 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_edge, update_dom);
408 if (update_dom)
409 bbs_to_fix_dom.quick_push (new_bb);
410 gcc_assert (gimple_bb (swtch) == new_bb);
411 gsi = gsi_last_bb (new_bb);
413 /* Any blocks dominated by the GIMPLE_SWITCH, but that are not successors
414 of NEW_BB, are still immediately dominated by SWITCH_BB. Make it so. */
415 if (update_dom)
417 vec<basic_block> dom_bbs;
418 basic_block dom_son;
420 dom_bbs = get_dominated_by (CDI_DOMINATORS, new_bb);
421 FOR_EACH_VEC_ELT (dom_bbs, i, dom_son)
423 edge e = find_edge (new_bb, dom_son);
424 if (e && single_pred_p (e->dest))
425 continue;
426 set_immediate_dominator (CDI_DOMINATORS, dom_son, switch_bb);
427 bbs_to_fix_dom.safe_push (dom_son);
429 dom_bbs.release ();
432 /* csui = (1 << (word_mode) idx) */
433 csui = make_ssa_name (word_type_node);
434 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
435 fold_convert (word_type_node, idx));
436 tmp = force_gimple_operand_gsi (&gsi, tmp,
437 /*simple=*/false, NULL_TREE,
438 /*before=*/true, GSI_SAME_STMT);
439 shift_stmt = gimple_build_assign (csui, tmp);
440 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
441 update_stmt (shift_stmt);
443 /* for each unique set of cases:
444 if (const & csui) goto target */
445 for (k = 0; k < count; k++)
447 tmp = wide_int_to_tree (word_type_node, test[k].mask);
448 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
449 tmp = force_gimple_operand_gsi (&gsi, tmp,
450 /*simple=*/true, NULL_TREE,
451 /*before=*/true, GSI_SAME_STMT);
452 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
453 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_edge,
454 update_dom);
455 if (update_dom)
456 bbs_to_fix_dom.safe_push (new_bb);
457 gcc_assert (gimple_bb (swtch) == new_bb);
458 gsi = gsi_last_bb (new_bb);
461 /* We should have removed all edges now. */
462 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
464 /* If nothing matched, go to the default label. */
465 make_edge (gsi_bb (gsi), new_default_bb, EDGE_FALLTHRU);
467 /* The GIMPLE_SWITCH is now redundant. */
468 gsi_remove (&gsi, true);
470 if (update_dom)
472 /* Fix up the dominator tree. */
473 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
474 bbs_to_fix_dom.release ();
479 Switch initialization conversion
481 The following pass changes simple initializations of scalars in a switch
482 statement into initializations from a static array. Obviously, the values
483 must be constant and known at compile time and a default branch must be
484 provided. For example, the following code:
486 int a,b;
488 switch (argc)
490 case 1:
491 case 2:
492 a_1 = 8;
493 b_1 = 6;
494 break;
495 case 3:
496 a_2 = 9;
497 b_2 = 5;
498 break;
499 case 12:
500 a_3 = 10;
501 b_3 = 4;
502 break;
503 default:
504 a_4 = 16;
505 b_4 = 1;
506 break;
508 a_5 = PHI <a_1, a_2, a_3, a_4>
509 b_5 = PHI <b_1, b_2, b_3, b_4>
512 is changed into:
514 static const int = CSWTCH01[] = {6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 4};
515 static const int = CSWTCH02[] = {8, 8, 9, 16, 16, 16, 16, 16, 16, 16,
516 16, 16, 10};
518 if (((unsigned) argc) - 1 < 11)
520 a_6 = CSWTCH02[argc - 1];
521 b_6 = CSWTCH01[argc - 1];
523 else
525 a_7 = 16;
526 b_7 = 1;
528 a_5 = PHI <a_6, a_7>
529 b_b = PHI <b_6, b_7>
531 There are further constraints. Specifically, the range of values across all
532 case labels must not be bigger than SWITCH_CONVERSION_BRANCH_RATIO (default
533 eight) times the number of the actual switch branches.
535 This transformation was contributed by Martin Jambor, see this e-mail:
536 http://gcc.gnu.org/ml/gcc-patches/2008-07/msg00011.html */
538 /* The main structure of the pass. */
539 struct switch_conv_info
541 /* The expression used to decide the switch branch. */
542 tree index_expr;
544 /* The following integer constants store the minimum and maximum value
545 covered by the case labels. */
546 tree range_min;
547 tree range_max;
549 /* The difference between the above two numbers. Stored here because it
550 is used in all the conversion heuristics, as well as for some of the
551 transformation, and it is expensive to re-compute it all the time. */
552 tree range_size;
554 /* Basic block that contains the actual GIMPLE_SWITCH. */
555 basic_block switch_bb;
557 /* Basic block that is the target of the default case. */
558 basic_block default_bb;
560 /* The single successor block of all branches out of the GIMPLE_SWITCH,
561 if such a block exists. Otherwise NULL. */
562 basic_block final_bb;
564 /* The probability of the default edge in the replaced switch. */
565 profile_probability default_prob;
567 /* The count of the default edge in the replaced switch. */
568 profile_count default_count;
570 /* Combined count of all other (non-default) edges in the replaced switch. */
571 profile_count other_count;
573 /* Number of phi nodes in the final bb (that we'll be replacing). */
574 int phi_count;
576 /* Array of default values, in the same order as phi nodes. */
577 tree *default_values;
579 /* Constructors of new static arrays. */
580 vec<constructor_elt, va_gc> **constructors;
582 /* Array of ssa names that are initialized with a value from a new static
583 array. */
584 tree *target_inbound_names;
586 /* Array of ssa names that are initialized with the default value if the
587 switch expression is out of range. */
588 tree *target_outbound_names;
590 /* VOP SSA_NAME. */
591 tree target_vop;
593 /* The first load statement that loads a temporary from a new static array.
595 gimple *arr_ref_first;
597 /* The last load statement that loads a temporary from a new static array. */
598 gimple *arr_ref_last;
600 /* String reason why the case wasn't a good candidate that is written to the
601 dump file, if there is one. */
602 const char *reason;
604 /* True if default case is not used for any value between range_min and
605 range_max inclusive. */
606 bool contiguous_range;
608 /* True if default case does not have the required shape for other case
609 labels. */
610 bool default_case_nonstandard;
612 /* Parameters for expand_switch_using_bit_tests. Should be computed
613 the same way as in expand_case. */
614 unsigned int uniq;
615 unsigned int count;
618 /* Collect information about GIMPLE_SWITCH statement SWTCH into INFO. */
620 static void
621 collect_switch_conv_info (gswitch *swtch, struct switch_conv_info *info)
623 unsigned int branch_num = gimple_switch_num_labels (swtch);
624 tree min_case, max_case;
625 unsigned int count, i;
626 edge e, e_default, e_first;
627 edge_iterator ei;
628 basic_block first;
630 memset (info, 0, sizeof (*info));
632 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
633 is a default label which is the first in the vector.
634 Collect the bits we can deduce from the CFG. */
635 info->index_expr = gimple_switch_index (swtch);
636 info->switch_bb = gimple_bb (swtch);
637 info->default_bb
638 = label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
639 e_default = find_edge (info->switch_bb, info->default_bb);
640 info->default_prob = e_default->probability;
641 info->default_count = e_default->count ();
642 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
643 if (e != e_default)
644 info->other_count += e->count ();
646 /* Get upper and lower bounds of case values, and the covered range. */
647 min_case = gimple_switch_label (swtch, 1);
648 max_case = gimple_switch_label (swtch, branch_num - 1);
650 info->range_min = CASE_LOW (min_case);
651 if (CASE_HIGH (max_case) != NULL_TREE)
652 info->range_max = CASE_HIGH (max_case);
653 else
654 info->range_max = CASE_LOW (max_case);
656 info->contiguous_range = true;
657 tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : info->range_min;
658 for (i = 2; i < branch_num; i++)
660 tree elt = gimple_switch_label (swtch, i);
661 if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
663 info->contiguous_range = false;
664 break;
666 last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
669 if (info->contiguous_range)
671 first = label_to_block (CASE_LABEL (gimple_switch_label (swtch, 1)));
672 e_first = find_edge (info->switch_bb, first);
674 else
676 first = info->default_bb;
677 e_first = e_default;
680 /* See if there is one common successor block for all branch
681 targets. If it exists, record it in FINAL_BB.
682 Start with the destination of the first non-default case
683 if the range is contiguous and default case otherwise as
684 guess or its destination in case it is a forwarder block. */
685 if (! single_pred_p (e_first->dest))
686 info->final_bb = e_first->dest;
687 else if (single_succ_p (e_first->dest)
688 && ! single_pred_p (single_succ (e_first->dest)))
689 info->final_bb = single_succ (e_first->dest);
690 /* Require that all switch destinations are either that common
691 FINAL_BB or a forwarder to it, except for the default
692 case if contiguous range. */
693 if (info->final_bb)
694 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
696 if (e->dest == info->final_bb)
697 continue;
699 if (single_pred_p (e->dest)
700 && single_succ_p (e->dest)
701 && single_succ (e->dest) == info->final_bb)
702 continue;
704 if (e == e_default && info->contiguous_range)
706 info->default_case_nonstandard = true;
707 continue;
710 info->final_bb = NULL;
711 break;
714 info->range_size
715 = int_const_binop (MINUS_EXPR, info->range_max, info->range_min);
717 /* Get a count of the number of case labels. Single-valued case labels
718 simply count as one, but a case range counts double, since it may
719 require two compares if it gets lowered as a branching tree. */
720 count = 0;
721 for (i = 1; i < branch_num; i++)
723 tree elt = gimple_switch_label (swtch, i);
724 count++;
725 if (CASE_HIGH (elt)
726 && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
727 count++;
729 info->count = count;
731 /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
732 block. Assume a CFG cleanup would have already removed degenerate
733 switch statements, this allows us to just use EDGE_COUNT. */
734 info->uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
737 /* Checks whether the range given by individual case statements of the SWTCH
738 switch statement isn't too big and whether the number of branches actually
739 satisfies the size of the new array. */
741 static bool
742 check_range (struct switch_conv_info *info)
744 gcc_assert (info->range_size);
745 if (!tree_fits_uhwi_p (info->range_size))
747 info->reason = "index range way too large or otherwise unusable";
748 return false;
751 if (tree_to_uhwi (info->range_size)
752 > ((unsigned) info->count * SWITCH_CONVERSION_BRANCH_RATIO))
754 info->reason = "the maximum range-branch ratio exceeded";
755 return false;
758 return true;
761 /* Checks whether all but the FINAL_BB basic blocks are empty. */
763 static bool
764 check_all_empty_except_final (struct switch_conv_info *info)
766 edge e, e_default = find_edge (info->switch_bb, info->default_bb);
767 edge_iterator ei;
769 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
771 if (e->dest == info->final_bb)
772 continue;
774 if (!empty_block_p (e->dest))
776 if (info->contiguous_range && e == e_default)
778 info->default_case_nonstandard = true;
779 continue;
782 info->reason = "bad case - a non-final BB not empty";
783 return false;
787 return true;
790 /* This function checks whether all required values in phi nodes in final_bb
791 are constants. Required values are those that correspond to a basic block
792 which is a part of the examined switch statement. It returns true if the
793 phi nodes are OK, otherwise false. */
795 static bool
796 check_final_bb (gswitch *swtch, struct switch_conv_info *info)
798 gphi_iterator gsi;
800 info->phi_count = 0;
801 for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
803 gphi *phi = gsi.phi ();
804 unsigned int i;
806 if (virtual_operand_p (gimple_phi_result (phi)))
807 continue;
809 info->phi_count++;
811 for (i = 0; i < gimple_phi_num_args (phi); i++)
813 basic_block bb = gimple_phi_arg_edge (phi, i)->src;
815 if (bb == info->switch_bb
816 || (single_pred_p (bb)
817 && single_pred (bb) == info->switch_bb
818 && (!info->default_case_nonstandard
819 || empty_block_p (bb))))
821 tree reloc, val;
822 const char *reason = NULL;
824 val = gimple_phi_arg_def (phi, i);
825 if (!is_gimple_ip_invariant (val))
826 reason = "non-invariant value from a case";
827 else
829 reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
830 if ((flag_pic && reloc != null_pointer_node)
831 || (!flag_pic && reloc == NULL_TREE))
833 if (reloc)
834 reason
835 = "value from a case would need runtime relocations";
836 else
837 reason
838 = "value from a case is not a valid initializer";
841 if (reason)
843 /* For contiguous range, we can allow non-constant
844 or one that needs relocation, as long as it is
845 only reachable from the default case. */
846 if (bb == info->switch_bb)
847 bb = info->final_bb;
848 if (!info->contiguous_range || bb != info->default_bb)
850 info->reason = reason;
851 return false;
854 unsigned int branch_num = gimple_switch_num_labels (swtch);
855 for (unsigned int i = 1; i < branch_num; i++)
857 tree lab = CASE_LABEL (gimple_switch_label (swtch, i));
858 if (label_to_block (lab) == bb)
860 info->reason = reason;
861 return false;
864 info->default_case_nonstandard = true;
870 return true;
873 /* The following function allocates default_values, target_{in,out}_names and
874 constructors arrays. The last one is also populated with pointers to
875 vectors that will become constructors of new arrays. */
877 static void
878 create_temp_arrays (struct switch_conv_info *info)
880 int i;
882 info->default_values = XCNEWVEC (tree, info->phi_count * 3);
883 /* ??? Macros do not support multi argument templates in their
884 argument list. We create a typedef to work around that problem. */
885 typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
886 info->constructors = XCNEWVEC (vec_constructor_elt_gc, info->phi_count);
887 info->target_inbound_names = info->default_values + info->phi_count;
888 info->target_outbound_names = info->target_inbound_names + info->phi_count;
889 for (i = 0; i < info->phi_count; i++)
890 vec_alloc (info->constructors[i], tree_to_uhwi (info->range_size) + 1);
893 /* Free the arrays created by create_temp_arrays(). The vectors that are
894 created by that function are not freed here, however, because they have
895 already become constructors and must be preserved. */
897 static void
898 free_temp_arrays (struct switch_conv_info *info)
900 XDELETEVEC (info->constructors);
901 XDELETEVEC (info->default_values);
904 /* Populate the array of default values in the order of phi nodes.
905 DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
906 if the range is non-contiguous or the default case has standard
907 structure, otherwise it is the first non-default case instead. */
909 static void
910 gather_default_values (tree default_case, struct switch_conv_info *info)
912 gphi_iterator gsi;
913 basic_block bb = label_to_block (CASE_LABEL (default_case));
914 edge e;
915 int i = 0;
917 gcc_assert (CASE_LOW (default_case) == NULL_TREE
918 || info->default_case_nonstandard);
920 if (bb == info->final_bb)
921 e = find_edge (info->switch_bb, bb);
922 else
923 e = single_succ_edge (bb);
925 for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
927 gphi *phi = gsi.phi ();
928 if (virtual_operand_p (gimple_phi_result (phi)))
929 continue;
930 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
931 gcc_assert (val);
932 info->default_values[i++] = val;
936 /* The following function populates the vectors in the constructors array with
937 future contents of the static arrays. The vectors are populated in the
938 order of phi nodes. SWTCH is the switch statement being converted. */
940 static void
941 build_constructors (gswitch *swtch, struct switch_conv_info *info)
943 unsigned i, branch_num = gimple_switch_num_labels (swtch);
944 tree pos = info->range_min;
945 tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
947 for (i = 1; i < branch_num; i++)
949 tree cs = gimple_switch_label (swtch, i);
950 basic_block bb = label_to_block (CASE_LABEL (cs));
951 edge e;
952 tree high;
953 gphi_iterator gsi;
954 int j;
956 if (bb == info->final_bb)
957 e = find_edge (info->switch_bb, bb);
958 else
959 e = single_succ_edge (bb);
960 gcc_assert (e);
962 while (tree_int_cst_lt (pos, CASE_LOW (cs)))
964 int k;
965 gcc_assert (!info->contiguous_range);
966 for (k = 0; k < info->phi_count; k++)
968 constructor_elt elt;
970 elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
971 elt.value
972 = unshare_expr_without_location (info->default_values[k]);
973 info->constructors[k]->quick_push (elt);
976 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
978 gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
980 j = 0;
981 if (CASE_HIGH (cs))
982 high = CASE_HIGH (cs);
983 else
984 high = CASE_LOW (cs);
985 for (gsi = gsi_start_phis (info->final_bb);
986 !gsi_end_p (gsi); gsi_next (&gsi))
988 gphi *phi = gsi.phi ();
989 if (virtual_operand_p (gimple_phi_result (phi)))
990 continue;
991 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
992 tree low = CASE_LOW (cs);
993 pos = CASE_LOW (cs);
997 constructor_elt elt;
999 elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
1000 elt.value = unshare_expr_without_location (val);
1001 info->constructors[j]->quick_push (elt);
1003 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
1004 } while (!tree_int_cst_lt (high, pos)
1005 && tree_int_cst_lt (low, pos));
1006 j++;
1011 /* If all values in the constructor vector are the same, return the value.
1012 Otherwise return NULL_TREE. Not supposed to be called for empty
1013 vectors. */
1015 static tree
1016 constructor_contains_same_values_p (vec<constructor_elt, va_gc> *vec)
1018 unsigned int i;
1019 tree prev = NULL_TREE;
1020 constructor_elt *elt;
1022 FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
1024 if (!prev)
1025 prev = elt->value;
1026 else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
1027 return NULL_TREE;
1029 return prev;
1032 /* Return type which should be used for array elements, either TYPE's
1033 main variant or, for integral types, some smaller integral type
1034 that can still hold all the constants. */
1036 static tree
1037 array_value_type (gswitch *swtch, tree type, int num,
1038 struct switch_conv_info *info)
1040 unsigned int i, len = vec_safe_length (info->constructors[num]);
1041 constructor_elt *elt;
1042 int sign = 0;
1043 tree smaller_type;
1045 /* Types with alignments greater than their size can reach here, e.g. out of
1046 SRA. We couldn't use these as an array component type so get back to the
1047 main variant first, which, for our purposes, is fine for other types as
1048 well. */
1050 type = TYPE_MAIN_VARIANT (type);
1052 if (!INTEGRAL_TYPE_P (type))
1053 return type;
1055 scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
1056 scalar_int_mode mode = get_narrowest_mode (type_mode);
1057 if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
1058 return type;
1060 if (len < (optimize_bb_for_size_p (gimple_bb (swtch)) ? 2 : 32))
1061 return type;
1063 FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
1065 wide_int cst;
1067 if (TREE_CODE (elt->value) != INTEGER_CST)
1068 return type;
1070 cst = wi::to_wide (elt->value);
1071 while (1)
1073 unsigned int prec = GET_MODE_BITSIZE (mode);
1074 if (prec > HOST_BITS_PER_WIDE_INT)
1075 return type;
1077 if (sign >= 0 && cst == wi::zext (cst, prec))
1079 if (sign == 0 && cst == wi::sext (cst, prec))
1080 break;
1081 sign = 1;
1082 break;
1084 if (sign <= 0 && cst == wi::sext (cst, prec))
1086 sign = -1;
1087 break;
1090 if (sign == 1)
1091 sign = 0;
1093 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
1094 || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
1095 return type;
1099 if (sign == 0)
1100 sign = TYPE_UNSIGNED (type) ? 1 : -1;
1101 smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
1102 if (GET_MODE_SIZE (type_mode)
1103 <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
1104 return type;
1106 return smaller_type;
1109 /* Create an appropriate array type and declaration and assemble a static array
1110 variable. Also create a load statement that initializes the variable in
1111 question with a value from the static array. SWTCH is the switch statement
1112 being converted, NUM is the index to arrays of constructors, default values
1113 and target SSA names for this particular array. ARR_INDEX_TYPE is the type
1114 of the index of the new array, PHI is the phi node of the final BB that
1115 corresponds to the value that will be loaded from the created array. TIDX
1116 is an ssa name of a temporary variable holding the index for loads from the
1117 new array. */
1119 static void
1120 build_one_array (gswitch *swtch, int num, tree arr_index_type,
1121 gphi *phi, tree tidx, struct switch_conv_info *info)
1123 tree name, cst;
1124 gimple *load;
1125 gimple_stmt_iterator gsi = gsi_for_stmt (swtch);
1126 location_t loc = gimple_location (swtch);
1128 gcc_assert (info->default_values[num]);
1130 name = copy_ssa_name (PHI_RESULT (phi));
1131 info->target_inbound_names[num] = name;
1133 cst = constructor_contains_same_values_p (info->constructors[num]);
1134 if (cst)
1135 load = gimple_build_assign (name, cst);
1136 else
1138 tree array_type, ctor, decl, value_type, fetch, default_type;
1140 default_type = TREE_TYPE (info->default_values[num]);
1141 value_type = array_value_type (swtch, default_type, num, info);
1142 array_type = build_array_type (value_type, arr_index_type);
1143 if (default_type != value_type)
1145 unsigned int i;
1146 constructor_elt *elt;
1148 FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
1149 elt->value = fold_convert (value_type, elt->value);
1151 ctor = build_constructor (array_type, info->constructors[num]);
1152 TREE_CONSTANT (ctor) = true;
1153 TREE_STATIC (ctor) = true;
1155 decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
1156 TREE_STATIC (decl) = 1;
1157 DECL_INITIAL (decl) = ctor;
1159 DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
1160 DECL_ARTIFICIAL (decl) = 1;
1161 DECL_IGNORED_P (decl) = 1;
1162 TREE_CONSTANT (decl) = 1;
1163 TREE_READONLY (decl) = 1;
1164 DECL_IGNORED_P (decl) = 1;
1165 varpool_node::finalize_decl (decl);
1167 fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
1168 NULL_TREE);
1169 if (default_type != value_type)
1171 fetch = fold_convert (default_type, fetch);
1172 fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
1173 true, GSI_SAME_STMT);
1175 load = gimple_build_assign (name, fetch);
1178 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1179 update_stmt (load);
1180 info->arr_ref_last = load;
1183 /* Builds and initializes static arrays initialized with values gathered from
1184 the SWTCH switch statement. Also creates statements that load values from
1185 them. */
1187 static void
1188 build_arrays (gswitch *swtch, struct switch_conv_info *info)
1190 tree arr_index_type;
1191 tree tidx, sub, utype;
1192 gimple *stmt;
1193 gimple_stmt_iterator gsi;
1194 gphi_iterator gpi;
1195 int i;
1196 location_t loc = gimple_location (swtch);
1198 gsi = gsi_for_stmt (swtch);
1200 /* Make sure we do not generate arithmetics in a subrange. */
1201 utype = TREE_TYPE (info->index_expr);
1202 if (TREE_TYPE (utype))
1203 utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
1204 else
1205 utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
1207 arr_index_type = build_index_type (info->range_size);
1208 tidx = make_ssa_name (utype);
1209 sub = fold_build2_loc (loc, MINUS_EXPR, utype,
1210 fold_convert_loc (loc, utype, info->index_expr),
1211 fold_convert_loc (loc, utype, info->range_min));
1212 sub = force_gimple_operand_gsi (&gsi, sub,
1213 false, NULL, true, GSI_SAME_STMT);
1214 stmt = gimple_build_assign (tidx, sub);
1216 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1217 update_stmt (stmt);
1218 info->arr_ref_first = stmt;
1220 for (gpi = gsi_start_phis (info->final_bb), i = 0;
1221 !gsi_end_p (gpi); gsi_next (&gpi))
1223 gphi *phi = gpi.phi ();
1224 if (!virtual_operand_p (gimple_phi_result (phi)))
1225 build_one_array (swtch, i++, arr_index_type, phi, tidx, info);
1226 else
1228 edge e;
1229 edge_iterator ei;
1230 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
1232 if (e->dest == info->final_bb)
1233 break;
1234 if (!info->default_case_nonstandard
1235 || e->dest != info->default_bb)
1237 e = single_succ_edge (e->dest);
1238 break;
1241 gcc_assert (e && e->dest == info->final_bb);
1242 info->target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
1247 /* Generates and appropriately inserts loads of default values at the position
1248 given by BSI. Returns the last inserted statement. */
1250 static gassign *
1251 gen_def_assigns (gimple_stmt_iterator *gsi, struct switch_conv_info *info)
1253 int i;
1254 gassign *assign = NULL;
1256 for (i = 0; i < info->phi_count; i++)
1258 tree name = copy_ssa_name (info->target_inbound_names[i]);
1259 info->target_outbound_names[i] = name;
1260 assign = gimple_build_assign (name, info->default_values[i]);
1261 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
1262 update_stmt (assign);
1264 return assign;
1267 /* Deletes the unused bbs and edges that now contain the switch statement and
1268 its empty branch bbs. BBD is the now dead BB containing the original switch
1269 statement, FINAL is the last BB of the converted switch statement (in terms
1270 of succession). */
1272 static void
1273 prune_bbs (basic_block bbd, basic_block final, basic_block default_bb)
1275 edge_iterator ei;
1276 edge e;
1278 for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
1280 basic_block bb;
1281 bb = e->dest;
1282 remove_edge (e);
1283 if (bb != final && bb != default_bb)
1284 delete_basic_block (bb);
1286 delete_basic_block (bbd);
1289 /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
1290 from the basic block loading values from an array and E2F from the basic
1291 block loading default values. BBF is the last switch basic block (see the
1292 bbf description in the comment below). */
1294 static void
1295 fix_phi_nodes (edge e1f, edge e2f, basic_block bbf,
1296 struct switch_conv_info *info)
1298 gphi_iterator gsi;
1299 int i;
1301 for (gsi = gsi_start_phis (bbf), i = 0;
1302 !gsi_end_p (gsi); gsi_next (&gsi))
1304 gphi *phi = gsi.phi ();
1305 tree inbound, outbound;
1306 if (virtual_operand_p (gimple_phi_result (phi)))
1307 inbound = outbound = info->target_vop;
1308 else
1310 inbound = info->target_inbound_names[i];
1311 outbound = info->target_outbound_names[i++];
1313 add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
1314 if (!info->default_case_nonstandard)
1315 add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
1319 /* Creates a check whether the switch expression value actually falls into the
1320 range given by all the cases. If it does not, the temporaries are loaded
1321 with default values instead. SWTCH is the switch statement being converted.
1323 bb0 is the bb with the switch statement, however, we'll end it with a
1324 condition instead.
1326 bb1 is the bb to be used when the range check went ok. It is derived from
1327 the switch BB
1329 bb2 is the bb taken when the expression evaluated outside of the range
1330 covered by the created arrays. It is populated by loads of default
1331 values.
1333 bbF is a fall through for both bb1 and bb2 and contains exactly what
1334 originally followed the switch statement.
1336 bbD contains the switch statement (in the end). It is unreachable but we
1337 still need to strip off its edges.
1340 static void
1341 gen_inbound_check (gswitch *swtch, struct switch_conv_info *info)
1343 tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
1344 tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
1345 tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
1346 glabel *label1, *label2, *label3;
1347 tree utype, tidx;
1348 tree bound;
1350 gcond *cond_stmt;
1352 gassign *last_assign = NULL;
1353 gimple_stmt_iterator gsi;
1354 basic_block bb0, bb1, bb2, bbf, bbd;
1355 edge e01 = NULL, e02, e21, e1d, e1f, e2f;
1356 location_t loc = gimple_location (swtch);
1358 gcc_assert (info->default_values);
1360 bb0 = gimple_bb (swtch);
1362 tidx = gimple_assign_lhs (info->arr_ref_first);
1363 utype = TREE_TYPE (tidx);
1365 /* (end of) block 0 */
1366 gsi = gsi_for_stmt (info->arr_ref_first);
1367 gsi_next (&gsi);
1369 bound = fold_convert_loc (loc, utype, info->range_size);
1370 cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
1371 gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
1372 update_stmt (cond_stmt);
1374 /* block 2 */
1375 if (!info->default_case_nonstandard)
1377 label2 = gimple_build_label (label_decl2);
1378 gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
1379 last_assign = gen_def_assigns (&gsi, info);
1382 /* block 1 */
1383 label1 = gimple_build_label (label_decl1);
1384 gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
1386 /* block F */
1387 gsi = gsi_start_bb (info->final_bb);
1388 label3 = gimple_build_label (label_decl3);
1389 gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
1391 /* cfg fix */
1392 e02 = split_block (bb0, cond_stmt);
1393 bb2 = e02->dest;
1395 if (info->default_case_nonstandard)
1397 bb1 = bb2;
1398 bb2 = info->default_bb;
1399 e01 = e02;
1400 e01->flags = EDGE_TRUE_VALUE;
1401 e02 = make_edge (bb0, bb2, EDGE_FALSE_VALUE);
1402 edge e_default = find_edge (bb1, bb2);
1403 for (gphi_iterator gsi = gsi_start_phis (bb2);
1404 !gsi_end_p (gsi); gsi_next (&gsi))
1406 gphi *phi = gsi.phi ();
1407 tree arg = PHI_ARG_DEF_FROM_EDGE (phi, e_default);
1408 add_phi_arg (phi, arg, e02,
1409 gimple_phi_arg_location_from_edge (phi, e_default));
1411 /* Partially fix the dominator tree, if it is available. */
1412 if (dom_info_available_p (CDI_DOMINATORS))
1413 redirect_immediate_dominators (CDI_DOMINATORS, bb1, bb0);
1415 else
1417 e21 = split_block (bb2, last_assign);
1418 bb1 = e21->dest;
1419 remove_edge (e21);
1422 e1d = split_block (bb1, info->arr_ref_last);
1423 bbd = e1d->dest;
1424 remove_edge (e1d);
1426 /* flags and profiles of the edge for in-range values */
1427 if (!info->default_case_nonstandard)
1428 e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
1429 e01->probability = info->default_prob.invert ();
1431 /* flags and profiles of the edge taking care of out-of-range values */
1432 e02->flags &= ~EDGE_FALLTHRU;
1433 e02->flags |= EDGE_FALSE_VALUE;
1434 e02->probability = info->default_prob;
1436 bbf = info->final_bb;
1438 e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
1439 e1f->probability = profile_probability::always ();
1441 if (info->default_case_nonstandard)
1442 e2f = NULL;
1443 else
1445 e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
1446 e2f->probability = profile_probability::always ();
1449 /* frequencies of the new BBs */
1450 bb1->count = e01->count ();
1451 bb2->count = e02->count ();
1452 if (!info->default_case_nonstandard)
1453 bbf->count = e1f->count () + e2f->count ();
1455 /* Tidy blocks that have become unreachable. */
1456 prune_bbs (bbd, info->final_bb,
1457 info->default_case_nonstandard ? info->default_bb : NULL);
1459 /* Fixup the PHI nodes in bbF. */
1460 fix_phi_nodes (e1f, e2f, bbf, info);
1462 /* Fix the dominator tree, if it is available. */
1463 if (dom_info_available_p (CDI_DOMINATORS))
1465 vec<basic_block> bbs_to_fix_dom;
1467 set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
1468 if (!info->default_case_nonstandard)
1469 set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
1470 if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
1471 /* If bbD was the immediate dominator ... */
1472 set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
1474 bbs_to_fix_dom.create (3 + (bb2 != bbf));
1475 bbs_to_fix_dom.quick_push (bb0);
1476 bbs_to_fix_dom.quick_push (bb1);
1477 if (bb2 != bbf)
1478 bbs_to_fix_dom.quick_push (bb2);
1479 bbs_to_fix_dom.quick_push (bbf);
1481 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
1482 bbs_to_fix_dom.release ();
1486 /* The following function is invoked on every switch statement (the current one
1487 is given in SWTCH) and runs the individual phases of switch conversion on it
1488 one after another until one fails or the conversion is completed.
1489 Returns NULL on success, or a pointer to a string with the reason why the
1490 conversion failed. */
1492 static const char *
1493 process_switch (gswitch *swtch)
1495 struct switch_conv_info info;
1497 /* Group case labels so that we get the right results from the heuristics
1498 that decide on the code generation approach for this switch. */
1499 cfg_altered |= group_case_labels_stmt (swtch);
1501 /* If this switch is now a degenerate case with only a default label,
1502 there is nothing left for us to do. */
1503 if (gimple_switch_num_labels (swtch) < 2)
1504 return "switch is a degenerate case";
1506 collect_switch_conv_info (swtch, &info);
1508 /* No error markers should reach here (they should be filtered out
1509 during gimplification). */
1510 gcc_checking_assert (TREE_TYPE (info.index_expr) != error_mark_node);
1512 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
1513 gcc_checking_assert (! TREE_CONSTANT (info.index_expr));
1515 if (info.uniq <= MAX_CASE_BIT_TESTS)
1517 if (expand_switch_using_bit_tests_p (info.range_size,
1518 info.uniq, info.count,
1519 optimize_bb_for_speed_p
1520 (gimple_bb (swtch))))
1522 if (dump_file)
1523 fputs (" expanding as bit test is preferable\n", dump_file);
1524 emit_case_bit_tests (swtch, info.index_expr, info.range_min,
1525 info.range_size, info.range_max);
1526 loops_state_set (LOOPS_NEED_FIXUP);
1527 return NULL;
1530 if (info.uniq <= 2)
1531 /* This will be expanded as a decision tree in stmt.c:expand_case. */
1532 return " expanding as jumps is preferable";
1535 /* If there is no common successor, we cannot do the transformation. */
1536 if (! info.final_bb)
1537 return "no common successor to all case label target blocks found";
1539 /* Check the case label values are within reasonable range: */
1540 if (!check_range (&info))
1542 gcc_assert (info.reason);
1543 return info.reason;
1546 /* For all the cases, see whether they are empty, the assignments they
1547 represent constant and so on... */
1548 if (! check_all_empty_except_final (&info))
1550 gcc_assert (info.reason);
1551 return info.reason;
1553 if (!check_final_bb (swtch, &info))
1555 gcc_assert (info.reason);
1556 return info.reason;
1559 /* At this point all checks have passed and we can proceed with the
1560 transformation. */
1562 create_temp_arrays (&info);
1563 gather_default_values (info.default_case_nonstandard
1564 ? gimple_switch_label (swtch, 1)
1565 : gimple_switch_default_label (swtch), &info);
1566 if (info.phi_count)
1567 build_constructors (swtch, &info);
1569 build_arrays (swtch, &info); /* Build the static arrays and assignments. */
1570 gen_inbound_check (swtch, &info); /* Build the bounds check. */
1572 /* Cleanup: */
1573 free_temp_arrays (&info);
1574 return NULL;
1577 /* The main function of the pass scans statements for switches and invokes
1578 process_switch on them. */
1580 namespace {
1582 const pass_data pass_data_convert_switch =
1584 GIMPLE_PASS, /* type */
1585 "switchconv", /* name */
1586 OPTGROUP_NONE, /* optinfo_flags */
1587 TV_TREE_SWITCH_CONVERSION, /* tv_id */
1588 ( PROP_cfg | PROP_ssa ), /* properties_required */
1589 0, /* properties_provided */
1590 0, /* properties_destroyed */
1591 0, /* todo_flags_start */
1592 TODO_update_ssa, /* todo_flags_finish */
1595 class pass_convert_switch : public gimple_opt_pass
1597 public:
1598 pass_convert_switch (gcc::context *ctxt)
1599 : gimple_opt_pass (pass_data_convert_switch, ctxt)
1602 /* opt_pass methods: */
1603 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
1604 virtual unsigned int execute (function *);
1606 }; // class pass_convert_switch
1608 unsigned int
1609 pass_convert_switch::execute (function *fun)
1611 basic_block bb;
1613 cfg_altered = false;
1614 FOR_EACH_BB_FN (bb, fun)
1616 const char *failure_reason;
1617 gimple *stmt = last_stmt (bb);
1618 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
1620 if (dump_file)
1622 expanded_location loc = expand_location (gimple_location (stmt));
1624 fprintf (dump_file, "beginning to process the following "
1625 "SWITCH statement (%s:%d) : ------- \n",
1626 loc.file, loc.line);
1627 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1628 putc ('\n', dump_file);
1631 failure_reason = process_switch (as_a <gswitch *> (stmt));
1632 if (! failure_reason)
1634 cfg_altered = true;
1635 if (dump_file)
1637 fputs ("Switch converted\n", dump_file);
1638 fputs ("--------------------------------\n", dump_file);
1641 /* Make no effort to update the post-dominator tree. It is actually not
1642 that hard for the transformations we have performed, but it is not
1643 supported by iterate_fix_dominators. */
1644 free_dominance_info (CDI_POST_DOMINATORS);
1646 else
1648 if (dump_file)
1650 fputs ("Bailing out - ", dump_file);
1651 fputs (failure_reason, dump_file);
1652 fputs ("\n--------------------------------\n", dump_file);
1658 return cfg_altered ? TODO_cleanup_cfg : 0;
1661 } // anon namespace
1663 gimple_opt_pass *
1664 make_pass_convert_switch (gcc::context *ctxt)
1666 return new pass_convert_switch (ctxt);
1669 struct case_node
1671 case_node *left; /* Left son in binary tree. */
1672 case_node *right; /* Right son in binary tree;
1673 also node chain. */
1674 case_node *parent; /* Parent of node in binary tree. */
1675 tree low; /* Lowest index value for this label. */
1676 tree high; /* Highest index value for this label. */
1677 basic_block case_bb; /* Label to jump to when node matches. */
1678 tree case_label; /* Label to jump to when node matches. */
1679 profile_probability prob; /* Probability of taking this case. */
1680 profile_probability subtree_prob; /* Probability of reaching subtree
1681 rooted at this node. */
1684 typedef case_node *case_node_ptr;
1686 static basic_block emit_case_nodes (basic_block, tree, case_node_ptr,
1687 basic_block, tree, profile_probability,
1688 tree, hash_map<tree, tree> *);
1689 static bool node_has_low_bound (case_node_ptr, tree);
1690 static bool node_has_high_bound (case_node_ptr, tree);
1691 static bool node_is_bounded (case_node_ptr, tree);
1693 /* Return the smallest number of different values for which it is best to use a
1694 jump-table instead of a tree of conditional branches. */
1696 static unsigned int
1697 case_values_threshold (void)
1699 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
1701 if (threshold == 0)
1702 threshold = targetm.case_values_threshold ();
1704 return threshold;
1707 /* Reset the aux field of all outgoing edges of basic block BB. */
1709 static inline void
1710 reset_out_edges_aux (basic_block bb)
1712 edge e;
1713 edge_iterator ei;
1714 FOR_EACH_EDGE (e, ei, bb->succs)
1715 e->aux = (void *) 0;
1718 /* Compute the number of case labels that correspond to each outgoing edge of
1719 STMT. Record this information in the aux field of the edge. */
1721 static inline void
1722 compute_cases_per_edge (gswitch *stmt)
1724 basic_block bb = gimple_bb (stmt);
1725 reset_out_edges_aux (bb);
1726 int ncases = gimple_switch_num_labels (stmt);
1727 for (int i = ncases - 1; i >= 1; --i)
1729 tree elt = gimple_switch_label (stmt, i);
1730 tree lab = CASE_LABEL (elt);
1731 basic_block case_bb = label_to_block_fn (cfun, lab);
1732 edge case_edge = find_edge (bb, case_bb);
1733 case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
1737 /* Do the insertion of a case label into case_list. The labels are
1738 fed to us in descending order from the sorted vector of case labels used
1739 in the tree part of the middle end. So the list we construct is
1740 sorted in ascending order.
1742 LABEL is the case label to be inserted. LOW and HIGH are the bounds
1743 against which the index is compared to jump to LABEL and PROB is the
1744 estimated probability LABEL is reached from the switch statement. */
1746 static case_node *
1747 add_case_node (case_node *head, tree low, tree high, basic_block case_bb,
1748 tree case_label, profile_probability prob,
1749 object_allocator<case_node> &case_node_pool)
1751 case_node *r;
1753 gcc_checking_assert (low);
1754 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
1756 /* Add this label to the chain. */
1757 r = case_node_pool.allocate ();
1758 r->low = low;
1759 r->high = high;
1760 r->case_bb = case_bb;
1761 r->case_label = case_label;
1762 r->parent = r->left = NULL;
1763 r->prob = prob;
1764 r->subtree_prob = prob;
1765 r->right = head;
1766 return r;
1769 /* Dump ROOT, a list or tree of case nodes, to file. */
1771 static void
1772 dump_case_nodes (FILE *f, case_node *root, int indent_step, int indent_level)
1774 if (root == 0)
1775 return;
1776 indent_level++;
1778 dump_case_nodes (f, root->left, indent_step, indent_level);
1780 fputs (";; ", f);
1781 fprintf (f, "%*s", indent_step * indent_level, "");
1782 print_dec (wi::to_wide (root->low), f, TYPE_SIGN (TREE_TYPE (root->low)));
1783 if (!tree_int_cst_equal (root->low, root->high))
1785 fprintf (f, " ... ");
1786 print_dec (wi::to_wide (root->high), f,
1787 TYPE_SIGN (TREE_TYPE (root->high)));
1789 fputs ("\n", f);
1791 dump_case_nodes (f, root->right, indent_step, indent_level);
1794 /* Take an ordered list of case nodes
1795 and transform them into a near optimal binary tree,
1796 on the assumption that any target code selection value is as
1797 likely as any other.
1799 The transformation is performed by splitting the ordered
1800 list into two equal sections plus a pivot. The parts are
1801 then attached to the pivot as left and right branches. Each
1802 branch is then transformed recursively. */
1804 static void
1805 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
1807 case_node_ptr np;
1809 np = *head;
1810 if (np)
1812 int i = 0;
1813 int ranges = 0;
1814 case_node_ptr *npp;
1815 case_node_ptr left;
1817 /* Count the number of entries on branch. Also count the ranges. */
1819 while (np)
1821 if (!tree_int_cst_equal (np->low, np->high))
1822 ranges++;
1824 i++;
1825 np = np->right;
1828 if (i > 2)
1830 /* Split this list if it is long enough for that to help. */
1831 npp = head;
1832 left = *npp;
1834 /* If there are just three nodes, split at the middle one. */
1835 if (i == 3)
1836 npp = &(*npp)->right;
1837 else
1839 /* Find the place in the list that bisects the list's total cost,
1840 where ranges count as 2.
1841 Here I gets half the total cost. */
1842 i = (i + ranges + 1) / 2;
1843 while (1)
1845 /* Skip nodes while their cost does not reach that amount. */
1846 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
1847 i--;
1848 i--;
1849 if (i <= 0)
1850 break;
1851 npp = &(*npp)->right;
1854 *head = np = *npp;
1855 *npp = 0;
1856 np->parent = parent;
1857 np->left = left;
1859 /* Optimize each of the two split parts. */
1860 balance_case_nodes (&np->left, np);
1861 balance_case_nodes (&np->right, np);
1862 np->subtree_prob = np->prob;
1863 np->subtree_prob += np->left->subtree_prob;
1864 np->subtree_prob += np->right->subtree_prob;
1866 else
1868 /* Else leave this branch as one level,
1869 but fill in `parent' fields. */
1870 np = *head;
1871 np->parent = parent;
1872 np->subtree_prob = np->prob;
1873 for (; np->right; np = np->right)
1875 np->right->parent = np;
1876 (*head)->subtree_prob += np->right->subtree_prob;
1882 /* Return true if a switch should be expanded as a decision tree.
1883 RANGE is the difference between highest and lowest case.
1884 UNIQ is number of unique case node targets, not counting the default case.
1885 COUNT is the number of comparisons needed, not counting the default case. */
1887 static bool
1888 expand_switch_as_decision_tree_p (tree range,
1889 unsigned int uniq ATTRIBUTE_UNUSED,
1890 unsigned int count)
1892 int max_ratio;
1894 /* If neither casesi or tablejump is available, or flag_jump_tables
1895 over-ruled us, we really have no choice. */
1896 if (!targetm.have_casesi () && !targetm.have_tablejump ())
1897 return true;
1898 if (!flag_jump_tables)
1899 return true;
1900 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
1901 if (flag_pic)
1902 return true;
1903 #endif
1905 /* If the switch is relatively small such that the cost of one
1906 indirect jump on the target are higher than the cost of a
1907 decision tree, go with the decision tree.
1909 If range of values is much bigger than number of values,
1910 or if it is too large to represent in a HOST_WIDE_INT,
1911 make a sequence of conditional branches instead of a dispatch.
1913 The definition of "much bigger" depends on whether we are
1914 optimizing for size or for speed. If the former, the maximum
1915 ratio range/count = 3, because this was found to be the optimal
1916 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
1917 10 is much older, and was probably selected after an extensive
1918 benchmarking investigation on numerous platforms. Or maybe it
1919 just made sense to someone at some point in the history of GCC,
1920 who knows... */
1921 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
1922 if (count < case_values_threshold () || !tree_fits_uhwi_p (range)
1923 || compare_tree_int (range, max_ratio * count) > 0)
1924 return true;
1926 return false;
1929 static void
1930 fix_phi_operands_for_edge (edge e, hash_map<tree, tree> *phi_mapping)
1932 basic_block bb = e->dest;
1933 gphi_iterator gsi;
1934 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1936 gphi *phi = gsi.phi ();
1938 tree *definition = phi_mapping->get (gimple_phi_result (phi));
1939 if (definition)
1940 add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
1945 /* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1947 static void
1948 emit_jump (basic_block bb, basic_block case_bb,
1949 hash_map<tree, tree> *phi_mapping)
1951 edge e = single_succ_edge (bb);
1952 redirect_edge_succ (e, case_bb);
1953 fix_phi_operands_for_edge (e, phi_mapping);
1956 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1957 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1958 DEFAULT_PROB is the estimated probability that it jumps to
1959 DEFAULT_LABEL.
1961 We generate a binary decision tree to select the appropriate target
1962 code. */
1964 static void
1965 emit_case_decision_tree (gswitch *s, tree index_expr, tree index_type,
1966 case_node_ptr case_list, basic_block default_bb,
1967 tree default_label, profile_probability default_prob,
1968 hash_map<tree, tree> *phi_mapping)
1970 balance_case_nodes (&case_list, NULL);
1972 if (dump_file)
1973 dump_function_to_file (current_function_decl, dump_file, dump_flags);
1974 if (dump_file && (dump_flags & TDF_DETAILS))
1976 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1977 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1978 dump_case_nodes (dump_file, case_list, indent_step, 0);
1981 basic_block bb = gimple_bb (s);
1982 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1983 edge e;
1984 if (gsi_end_p (gsi))
1985 e = split_block_after_labels (bb);
1986 else
1988 gsi_prev (&gsi);
1989 e = split_block (bb, gsi_stmt (gsi));
1991 bb = split_edge (e);
1993 bb = emit_case_nodes (bb, index_expr, case_list, default_bb, default_label,
1994 default_prob, index_type, phi_mapping);
1996 if (bb)
1997 emit_jump (bb, default_bb, phi_mapping);
1999 /* Remove all edges and do just an edge that will reach default_bb. */
2000 gsi = gsi_last_bb (gimple_bb (s));
2001 gsi_remove (&gsi, true);
2004 static void
2005 record_phi_operand_mapping (const vec<basic_block> bbs, basic_block switch_bb,
2006 hash_map <tree, tree> *map)
2008 /* Record all PHI nodes that have to be fixed after conversion. */
2009 for (unsigned i = 0; i < bbs.length (); i++)
2011 basic_block bb = bbs[i];
2013 gphi_iterator gsi;
2014 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2016 gphi *phi = gsi.phi ();
2018 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
2020 basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
2021 if (phi_src_bb == switch_bb)
2023 tree def = gimple_phi_arg_def (phi, i);
2024 tree result = gimple_phi_result (phi);
2025 map->put (result, def);
2026 break;
2033 /* Attempt to expand gimple switch STMT to a decision tree. */
2035 static bool
2036 try_switch_expansion (gswitch *stmt)
2038 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
2039 basic_block default_bb;
2040 unsigned int count, uniq;
2041 int i;
2042 int ncases = gimple_switch_num_labels (stmt);
2043 tree index_expr = gimple_switch_index (stmt);
2044 tree index_type = TREE_TYPE (index_expr);
2045 tree elt;
2046 basic_block bb = gimple_bb (stmt);
2048 hash_map<tree, tree> phi_mapping;
2049 auto_vec<basic_block> case_bbs;
2051 /* A list of case labels; it is first built as a list and it may then
2052 be rearranged into a nearly balanced binary tree. */
2053 case_node *case_list = 0;
2055 /* A pool for case nodes. */
2056 object_allocator<case_node> case_node_pool ("struct case_node pool");
2058 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
2059 expressions being INTEGER_CST. */
2060 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
2062 if (ncases == 1)
2063 return false;
2065 /* Find the default case target label. */
2066 tree default_label = CASE_LABEL (gimple_switch_default_label (stmt));
2067 default_bb = label_to_block_fn (cfun, default_label);
2068 edge default_edge = find_edge (bb, default_bb);
2069 profile_probability default_prob = default_edge->probability;
2070 case_bbs.safe_push (default_bb);
2072 /* Get upper and lower bounds of case values. */
2073 elt = gimple_switch_label (stmt, 1);
2074 minval = fold_convert (index_type, CASE_LOW (elt));
2075 elt = gimple_switch_label (stmt, ncases - 1);
2076 if (CASE_HIGH (elt))
2077 maxval = fold_convert (index_type, CASE_HIGH (elt));
2078 else
2079 maxval = fold_convert (index_type, CASE_LOW (elt));
2081 /* Compute span of values. */
2082 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
2084 /* Listify the labels queue and gather some numbers to decide
2085 how to expand this switch. */
2086 uniq = 0;
2087 count = 0;
2088 hash_set<tree> seen_labels;
2089 compute_cases_per_edge (stmt);
2091 for (i = ncases - 1; i >= 1; --i)
2093 elt = gimple_switch_label (stmt, i);
2094 tree low = CASE_LOW (elt);
2095 gcc_assert (low);
2096 tree high = CASE_HIGH (elt);
2097 gcc_assert (!high || tree_int_cst_lt (low, high));
2098 tree lab = CASE_LABEL (elt);
2100 /* Count the elements.
2101 A range counts double, since it requires two compares. */
2102 count++;
2103 if (high)
2104 count++;
2106 /* If we have not seen this label yet, then increase the
2107 number of unique case node targets seen. */
2108 if (!seen_labels.add (lab))
2109 uniq++;
2111 /* The bounds on the case range, LOW and HIGH, have to be converted
2112 to case's index type TYPE. Note that the original type of the
2113 case index in the source code is usually "lost" during
2114 gimplification due to type promotion, but the case labels retain the
2115 original type. Make sure to drop overflow flags. */
2116 low = fold_convert (index_type, low);
2117 if (TREE_OVERFLOW (low))
2118 low = wide_int_to_tree (index_type, wi::to_wide (low));
2120 /* The canonical from of a case label in GIMPLE is that a simple case
2121 has an empty CASE_HIGH. For the casesi and tablejump expanders,
2122 the back ends want simple cases to have high == low. */
2123 if (!high)
2124 high = low;
2125 high = fold_convert (index_type, high);
2126 if (TREE_OVERFLOW (high))
2127 high = wide_int_to_tree (index_type, wi::to_wide (high));
2129 basic_block case_bb = label_to_block_fn (cfun, lab);
2130 edge case_edge = find_edge (bb, case_bb);
2131 case_list = add_case_node (
2132 case_list, low, high, case_bb, lab,
2133 case_edge->probability.apply_scale (1, (intptr_t) (case_edge->aux)),
2134 case_node_pool);
2136 case_bbs.safe_push (case_bb);
2138 reset_out_edges_aux (bb);
2139 record_phi_operand_mapping (case_bbs, bb, &phi_mapping);
2141 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
2142 destination, such as one with a default case only.
2143 It also removes cases that are out of range for the switch
2144 type, so we should never get a zero here. */
2145 gcc_assert (count > 0);
2147 /* Decide how to expand this switch.
2148 The two options at this point are a dispatch table (casesi or
2149 tablejump) or a decision tree. */
2151 if (expand_switch_as_decision_tree_p (range, uniq, count))
2153 emit_case_decision_tree (stmt, index_expr, index_type, case_list,
2154 default_bb, default_label, default_prob,
2155 &phi_mapping);
2156 return true;
2159 return false;
2162 /* The main function of the pass scans statements for switches and invokes
2163 process_switch on them. */
2165 namespace {
2167 const pass_data pass_data_lower_switch =
2169 GIMPLE_PASS, /* type */
2170 "switchlower", /* name */
2171 OPTGROUP_NONE, /* optinfo_flags */
2172 TV_TREE_SWITCH_LOWERING, /* tv_id */
2173 ( PROP_cfg | PROP_ssa ), /* properties_required */
2174 0, /* properties_provided */
2175 0, /* properties_destroyed */
2176 0, /* todo_flags_start */
2177 TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
2180 class pass_lower_switch : public gimple_opt_pass
2182 public:
2183 pass_lower_switch (gcc::context *ctxt)
2184 : gimple_opt_pass (pass_data_lower_switch, ctxt)
2187 /* opt_pass methods: */
2188 virtual bool gate (function *) { return true; }
2189 virtual unsigned int execute (function *);
2191 }; // class pass_lower_switch
2193 unsigned int
2194 pass_lower_switch::execute (function *fun)
2196 basic_block bb;
2197 bool expanded = false;
2199 FOR_EACH_BB_FN (bb, fun)
2201 gimple *stmt = last_stmt (bb);
2202 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2204 if (dump_file)
2206 expanded_location loc = expand_location (gimple_location (stmt));
2208 fprintf (dump_file, "beginning to process the following "
2209 "SWITCH statement (%s:%d) : ------- \n",
2210 loc.file, loc.line);
2211 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2212 putc ('\n', dump_file);
2215 expanded |= try_switch_expansion (as_a<gswitch *> (stmt));
2219 if (expanded)
2221 free_dominance_info (CDI_DOMINATORS);
2222 free_dominance_info (CDI_POST_DOMINATORS);
2223 mark_virtual_operands_for_renaming (cfun);
2226 return 0;
2229 } // anon namespace
2231 gimple_opt_pass *
2232 make_pass_lower_switch (gcc::context *ctxt)
2234 return new pass_lower_switch (ctxt);
2237 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE.
2238 PROB is the probability of jumping to LABEL. */
2239 static basic_block
2240 do_jump_if_equal (basic_block bb, tree op0, tree op1, basic_block label_bb,
2241 profile_probability prob, hash_map<tree, tree> *phi_mapping)
2243 gcond *cond = gimple_build_cond (EQ_EXPR, op0, op1, NULL_TREE, NULL_TREE);
2244 gimple_stmt_iterator gsi = gsi_last_bb (bb);
2245 gsi_insert_before (&gsi, cond, GSI_SAME_STMT);
2247 gcc_assert (single_succ_p (bb));
2249 /* Make a new basic block where false branch will take place. */
2250 edge false_edge = split_block (bb, cond);
2251 false_edge->flags = EDGE_FALSE_VALUE;
2252 false_edge->probability = prob.invert ();
2254 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2255 fix_phi_operands_for_edge (true_edge, phi_mapping);
2256 true_edge->probability = prob;
2258 return false_edge->dest;
2261 /* Generate code to compare X with Y so that the condition codes are
2262 set and to jump to LABEL if the condition is true. If X is a
2263 constant and Y is not a constant, then the comparison is swapped to
2264 ensure that the comparison RTL has the canonical form.
2266 UNSIGNEDP nonzero says that X and Y are unsigned; this matters if they
2267 need to be widened. UNSIGNEDP is also used to select the proper
2268 branch condition code.
2270 If X and Y have mode BLKmode, then SIZE specifies the size of both X and Y.
2272 MODE is the mode of the inputs (in case they are const_int).
2274 COMPARISON is the rtl operator to compare with (EQ, NE, GT, etc.).
2275 It will be potentially converted into an unsigned variant based on
2276 UNSIGNEDP to select a proper jump instruction.
2278 PROB is the probability of jumping to LABEL. */
2280 static basic_block
2281 emit_cmp_and_jump_insns (basic_block bb, tree op0, tree op1,
2282 tree_code comparison, basic_block label_bb,
2283 profile_probability prob,
2284 hash_map<tree, tree> *phi_mapping)
2286 gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
2287 gimple_stmt_iterator gsi = gsi_last_bb (bb);
2288 gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
2290 gcc_assert (single_succ_p (bb));
2292 /* Make a new basic block where false branch will take place. */
2293 edge false_edge = split_block (bb, cond);
2294 false_edge->flags = EDGE_FALSE_VALUE;
2295 false_edge->probability = prob.invert ();
2297 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2298 fix_phi_operands_for_edge (true_edge, phi_mapping);
2299 true_edge->probability = prob;
2301 return false_edge->dest;
2304 /* Computes the conditional probability of jumping to a target if the branch
2305 instruction is executed.
2306 TARGET_PROB is the estimated probability of jumping to a target relative
2307 to some basic block BB.
2308 BASE_PROB is the probability of reaching the branch instruction relative
2309 to the same basic block BB. */
2311 static inline profile_probability
2312 conditional_probability (profile_probability target_prob,
2313 profile_probability base_prob)
2315 return target_prob / base_prob;
2318 /* Emit step-by-step code to select a case for the value of INDEX.
2319 The thus generated decision tree follows the form of the
2320 case-node binary tree NODE, whose nodes represent test conditions.
2321 INDEX_TYPE is the type of the index of the switch.
2323 Care is taken to prune redundant tests from the decision tree
2324 by detecting any boundary conditions already checked by
2325 emitted rtx. (See node_has_high_bound, node_has_low_bound
2326 and node_is_bounded, above.)
2328 Where the test conditions can be shown to be redundant we emit
2329 an unconditional jump to the target code. As a further
2330 optimization, the subordinates of a tree node are examined to
2331 check for bounded nodes. In this case conditional and/or
2332 unconditional jumps as a result of the boundary check for the
2333 current node are arranged to target the subordinates associated
2334 code for out of bound conditions on the current node.
2336 We can assume that when control reaches the code generated here,
2337 the index value has already been compared with the parents
2338 of this node, and determined to be on the same side of each parent
2339 as this node is. Thus, if this node tests for the value 51,
2340 and a parent tested for 52, we don't need to consider
2341 the possibility of a value greater than 51. If another parent
2342 tests for the value 50, then this node need not test anything. */
2344 static basic_block
2345 emit_case_nodes (basic_block bb, tree index, case_node_ptr node,
2346 basic_block default_bb, tree default_label,
2347 profile_probability default_prob, tree index_type,
2348 hash_map<tree, tree> *phi_mapping)
2350 /* If INDEX has an unsigned type, we must make unsigned branches. */
2351 profile_probability probability;
2352 profile_probability prob = node->prob, subtree_prob = node->subtree_prob;
2354 /* See if our parents have already tested everything for us.
2355 If they have, emit an unconditional jump for this node. */
2356 if (node_is_bounded (node, index_type))
2358 emit_jump (bb, node->case_bb, phi_mapping);
2359 return NULL;
2362 else if (tree_int_cst_equal (node->low, node->high))
2364 probability = conditional_probability (prob, subtree_prob + default_prob);
2365 /* Node is single valued. First see if the index expression matches
2366 this node and then check our children, if any. */
2367 bb = do_jump_if_equal (bb, index, node->low, node->case_bb, probability,
2368 phi_mapping);
2369 /* Since this case is taken at this point, reduce its weight from
2370 subtree_weight. */
2371 subtree_prob -= prob;
2372 if (node->right != 0 && node->left != 0)
2374 /* This node has children on both sides.
2375 Dispatch to one side or the other
2376 by comparing the index value with this node's value.
2377 If one subtree is bounded, check that one first,
2378 so we can avoid real branches in the tree. */
2380 if (node_is_bounded (node->right, index_type))
2382 probability
2383 = conditional_probability (node->right->prob,
2384 subtree_prob + default_prob);
2385 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2386 node->right->case_bb, probability,
2387 phi_mapping);
2388 bb = emit_case_nodes (bb, index, node->left, default_bb,
2389 default_label, default_prob, index_type,
2390 phi_mapping);
2393 else if (node_is_bounded (node->left, index_type))
2395 probability
2396 = conditional_probability (node->left->prob,
2397 subtree_prob + default_prob);
2398 bb = emit_cmp_and_jump_insns (bb, index, node->high, LT_EXPR,
2399 node->left->case_bb, probability,
2400 phi_mapping);
2401 bb = emit_case_nodes (bb, index, node->right, default_bb,
2402 default_label, default_prob, index_type,
2403 phi_mapping);
2406 /* If both children are single-valued cases with no
2407 children, finish up all the work. This way, we can save
2408 one ordered comparison. */
2409 else if (tree_int_cst_equal (node->right->low, node->right->high)
2410 && node->right->left == 0 && node->right->right == 0
2411 && tree_int_cst_equal (node->left->low, node->left->high)
2412 && node->left->left == 0 && node->left->right == 0)
2414 /* Neither node is bounded. First distinguish the two sides;
2415 then emit the code for one side at a time. */
2417 /* See if the value matches what the right hand side
2418 wants. */
2419 probability
2420 = conditional_probability (node->right->prob,
2421 subtree_prob + default_prob);
2422 bb = do_jump_if_equal (bb, index, node->right->low,
2423 node->right->case_bb, probability,
2424 phi_mapping);
2426 /* See if the value matches what the left hand side
2427 wants. */
2428 probability
2429 = conditional_probability (node->left->prob,
2430 subtree_prob + default_prob);
2431 bb = do_jump_if_equal (bb, index, node->left->low,
2432 node->left->case_bb, probability,
2433 phi_mapping);
2436 else
2438 /* Neither node is bounded. First distinguish the two sides;
2439 then emit the code for one side at a time. */
2441 basic_block test_bb = split_edge (single_succ_edge (bb));
2442 redirect_edge_succ (single_pred_edge (test_bb),
2443 single_succ_edge (bb)->dest);
2445 /* The default label could be reached either through the right
2446 subtree or the left subtree. Divide the probability
2447 equally. */
2448 probability
2449 = conditional_probability (node->right->subtree_prob
2450 + default_prob.apply_scale (1, 2),
2451 subtree_prob + default_prob);
2452 /* See if the value is on the right. */
2453 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2454 test_bb, probability, phi_mapping);
2455 default_prob = default_prob.apply_scale (1, 2);
2457 /* Value must be on the left.
2458 Handle the left-hand subtree. */
2459 bb = emit_case_nodes (bb, index, node->left, default_bb,
2460 default_label, default_prob, index_type,
2461 phi_mapping);
2462 /* If left-hand subtree does nothing,
2463 go to default. */
2465 if (bb && default_bb)
2466 emit_jump (bb, default_bb, phi_mapping);
2468 /* Code branches here for the right-hand subtree. */
2469 bb = emit_case_nodes (test_bb, index, node->right, default_bb,
2470 default_label, default_prob, index_type,
2471 phi_mapping);
2474 else if (node->right != 0 && node->left == 0)
2476 /* Here we have a right child but no left so we issue a conditional
2477 branch to default and process the right child.
2479 Omit the conditional branch to default if the right child
2480 does not have any children and is single valued; it would
2481 cost too much space to save so little time. */
2483 if (node->right->right || node->right->left
2484 || !tree_int_cst_equal (node->right->low, node->right->high))
2486 if (!node_has_low_bound (node, index_type))
2488 probability
2489 = conditional_probability (default_prob.apply_scale (1, 2),
2490 subtree_prob + default_prob);
2491 bb = emit_cmp_and_jump_insns (bb, index, node->high, LT_EXPR,
2492 default_bb, probability,
2493 phi_mapping);
2494 default_prob = default_prob.apply_scale (1, 2);
2497 bb = emit_case_nodes (bb, index, node->right, default_bb,
2498 default_label, default_prob, index_type,
2499 phi_mapping);
2501 else
2503 probability
2504 = conditional_probability (node->right->subtree_prob,
2505 subtree_prob + default_prob);
2506 /* We cannot process node->right normally
2507 since we haven't ruled out the numbers less than
2508 this node's value. So handle node->right explicitly. */
2509 bb = do_jump_if_equal (bb, index, node->right->low,
2510 node->right->case_bb, probability,
2511 phi_mapping);
2515 else if (node->right == 0 && node->left != 0)
2517 /* Just one subtree, on the left. */
2518 if (node->left->left || node->left->right
2519 || !tree_int_cst_equal (node->left->low, node->left->high))
2521 if (!node_has_high_bound (node, index_type))
2523 probability
2524 = conditional_probability (default_prob.apply_scale (1, 2),
2525 subtree_prob + default_prob);
2526 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2527 default_bb, probability,
2528 phi_mapping);
2529 default_prob = default_prob.apply_scale (1, 2);
2532 bb = emit_case_nodes (bb, index, node->left, default_bb,
2533 default_label, default_prob, index_type,
2534 phi_mapping);
2536 else
2538 probability
2539 = conditional_probability (node->left->subtree_prob,
2540 subtree_prob + default_prob);
2541 /* We cannot process node->left normally
2542 since we haven't ruled out the numbers less than
2543 this node's value. So handle node->left explicitly. */
2544 do_jump_if_equal (bb, index, node->left->low, node->left->case_bb,
2545 probability, phi_mapping);
2549 else
2551 /* Node is a range. These cases are very similar to those for a single
2552 value, except that we do not start by testing whether this node
2553 is the one to branch to. */
2555 if (node->right != 0 && node->left != 0)
2557 /* Node has subtrees on both sides.
2558 If the right-hand subtree is bounded,
2559 test for it first, since we can go straight there.
2560 Otherwise, we need to make a branch in the control structure,
2561 then handle the two subtrees. */
2562 basic_block test_bb = NULL;
2564 if (node_is_bounded (node->right, index_type))
2566 /* Right hand node is fully bounded so we can eliminate any
2567 testing and branch directly to the target code. */
2568 probability
2569 = conditional_probability (node->right->subtree_prob,
2570 subtree_prob + default_prob);
2571 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2572 node->right->case_bb, probability,
2573 phi_mapping);
2575 else
2577 /* Right hand node requires testing.
2578 Branch to a label where we will handle it later. */
2580 test_bb = split_edge (single_succ_edge (bb));
2581 redirect_edge_succ (single_pred_edge (test_bb),
2582 single_succ_edge (bb)->dest);
2584 probability
2585 = conditional_probability (node->right->subtree_prob
2586 + default_prob.apply_scale (1, 2),
2587 subtree_prob + default_prob);
2588 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2589 test_bb, probability, phi_mapping);
2590 default_prob = default_prob.apply_scale (1, 2);
2593 /* Value belongs to this node or to the left-hand subtree. */
2595 probability
2596 = conditional_probability (prob, subtree_prob + default_prob);
2597 bb = emit_cmp_and_jump_insns (bb, index, node->low, GE_EXPR,
2598 node->case_bb, probability,
2599 phi_mapping);
2601 /* Handle the left-hand subtree. */
2602 bb = emit_case_nodes (bb, index, node->left, default_bb,
2603 default_label, default_prob, index_type,
2604 phi_mapping);
2606 /* If right node had to be handled later, do that now. */
2607 if (test_bb)
2609 /* If the left-hand subtree fell through,
2610 don't let it fall into the right-hand subtree. */
2611 if (bb && default_bb)
2612 emit_jump (bb, default_bb, phi_mapping);
2614 bb = emit_case_nodes (test_bb, index, node->right, default_bb,
2615 default_label, default_prob, index_type,
2616 phi_mapping);
2620 else if (node->right != 0 && node->left == 0)
2622 /* Deal with values to the left of this node,
2623 if they are possible. */
2624 if (!node_has_low_bound (node, index_type))
2626 probability
2627 = conditional_probability (default_prob.apply_scale (1, 2),
2628 subtree_prob + default_prob);
2629 bb = emit_cmp_and_jump_insns (bb, index, node->low, LT_EXPR,
2630 default_bb, probability,
2631 phi_mapping);
2632 default_prob = default_prob.apply_scale (1, 2);
2635 /* Value belongs to this node or to the right-hand subtree. */
2637 probability
2638 = conditional_probability (prob, subtree_prob + default_prob);
2639 bb = emit_cmp_and_jump_insns (bb, index, node->high, LE_EXPR,
2640 node->case_bb, probability,
2641 phi_mapping);
2643 bb = emit_case_nodes (bb, index, node->right, default_bb,
2644 default_label, default_prob, index_type,
2645 phi_mapping);
2648 else if (node->right == 0 && node->left != 0)
2650 /* Deal with values to the right of this node,
2651 if they are possible. */
2652 if (!node_has_high_bound (node, index_type))
2654 probability
2655 = conditional_probability (default_prob.apply_scale (1, 2),
2656 subtree_prob + default_prob);
2657 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2658 default_bb, probability,
2659 phi_mapping);
2660 default_prob = default_prob.apply_scale (1, 2);
2663 /* Value belongs to this node or to the left-hand subtree. */
2665 probability
2666 = conditional_probability (prob, subtree_prob + default_prob);
2667 bb = emit_cmp_and_jump_insns (bb, index, node->low, GE_EXPR,
2668 node->case_bb, probability,
2669 phi_mapping);
2671 bb = emit_case_nodes (bb, index, node->left, default_bb,
2672 default_label, default_prob, index_type,
2673 phi_mapping);
2676 else
2678 /* Node has no children so we check low and high bounds to remove
2679 redundant tests. Only one of the bounds can exist,
2680 since otherwise this node is bounded--a case tested already. */
2681 bool high_bound = node_has_high_bound (node, index_type);
2682 bool low_bound = node_has_low_bound (node, index_type);
2684 if (!high_bound && low_bound)
2686 probability
2687 = conditional_probability (default_prob,
2688 subtree_prob + default_prob);
2689 bb = emit_cmp_and_jump_insns (bb, index, node->high, GT_EXPR,
2690 default_bb, probability,
2691 phi_mapping);
2694 else if (!low_bound && high_bound)
2696 probability
2697 = conditional_probability (default_prob,
2698 subtree_prob + default_prob);
2699 bb = emit_cmp_and_jump_insns (bb, index, node->low, LT_EXPR,
2700 default_bb, probability,
2701 phi_mapping);
2703 else if (!low_bound && !high_bound)
2705 tree lhs, rhs;
2706 generate_range_test (bb, index, node->low, node->high,
2707 &lhs, &rhs);
2708 probability
2709 = conditional_probability (default_prob,
2710 subtree_prob + default_prob);
2711 bb = emit_cmp_and_jump_insns (bb, lhs, rhs, GT_EXPR,
2712 default_bb, probability,
2713 phi_mapping);
2716 emit_jump (bb, node->case_bb, phi_mapping);
2717 return NULL;
2721 return bb;
2724 /* Search the parent sections of the case node tree
2725 to see if a test for the lower bound of NODE would be redundant.
2726 INDEX_TYPE is the type of the index expression.
2728 The instructions to generate the case decision tree are
2729 output in the same order as nodes are processed so it is
2730 known that if a parent node checks the range of the current
2731 node minus one that the current node is bounded at its lower
2732 span. Thus the test would be redundant. */
2734 static bool
2735 node_has_low_bound (case_node_ptr node, tree index_type)
2737 tree low_minus_one;
2738 case_node_ptr pnode;
2740 /* If the lower bound of this node is the lowest value in the index type,
2741 we need not test it. */
2743 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
2744 return true;
2746 /* If this node has a left branch, the value at the left must be less
2747 than that at this node, so it cannot be bounded at the bottom and
2748 we need not bother testing any further. */
2750 if (node->left)
2751 return false;
2753 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low), node->low,
2754 build_int_cst (TREE_TYPE (node->low), 1));
2756 /* If the subtraction above overflowed, we can't verify anything.
2757 Otherwise, look for a parent that tests our value - 1. */
2759 if (!tree_int_cst_lt (low_minus_one, node->low))
2760 return false;
2762 for (pnode = node->parent; pnode; pnode = pnode->parent)
2763 if (tree_int_cst_equal (low_minus_one, pnode->high))
2764 return true;
2766 return false;
2769 /* Search the parent sections of the case node tree
2770 to see if a test for the upper bound of NODE would be redundant.
2771 INDEX_TYPE is the type of the index expression.
2773 The instructions to generate the case decision tree are
2774 output in the same order as nodes are processed so it is
2775 known that if a parent node checks the range of the current
2776 node plus one that the current node is bounded at its upper
2777 span. Thus the test would be redundant. */
2779 static bool
2780 node_has_high_bound (case_node_ptr node, tree index_type)
2782 tree high_plus_one;
2783 case_node_ptr pnode;
2785 /* If there is no upper bound, obviously no test is needed. */
2787 if (TYPE_MAX_VALUE (index_type) == NULL)
2788 return true;
2790 /* If the upper bound of this node is the highest value in the type
2791 of the index expression, we need not test against it. */
2793 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
2794 return true;
2796 /* If this node has a right branch, the value at the right must be greater
2797 than that at this node, so it cannot be bounded at the top and
2798 we need not bother testing any further. */
2800 if (node->right)
2801 return false;
2803 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high), node->high,
2804 build_int_cst (TREE_TYPE (node->high), 1));
2806 /* If the addition above overflowed, we can't verify anything.
2807 Otherwise, look for a parent that tests our value + 1. */
2809 if (!tree_int_cst_lt (node->high, high_plus_one))
2810 return false;
2812 for (pnode = node->parent; pnode; pnode = pnode->parent)
2813 if (tree_int_cst_equal (high_plus_one, pnode->low))
2814 return true;
2816 return false;
2819 /* Search the parent sections of the
2820 case node tree to see if both tests for the upper and lower
2821 bounds of NODE would be redundant. */
2823 static bool
2824 node_is_bounded (case_node_ptr node, tree index_type)
2826 return (node_has_low_bound (node, index_type)
2827 && node_has_high_bound (node, index_type));