* include/bits/alloc_traits.h (__alloctr_rebind): Remove.
[official-gcc.git] / gcc / tree-switch-conversion.c
blob2f9ad27d31acc9708572fb52eafb30871d7946f9
1 /* Lower GIMPLE_SWITCH expressions to something more efficient than
2 a jump table.
3 Copyright (C) 2006-2015 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 "tm.h"
29 #include "params.h"
30 #include "flags.h"
31 #include "alias.h"
32 #include "symtab.h"
33 #include "tree.h"
34 #include "fold-const.h"
35 #include "varasm.h"
36 #include "stor-layout.h"
37 #include "predict.h"
38 #include "hard-reg-set.h"
39 #include "function.h"
40 #include "dominance.h"
41 #include "cfg.h"
42 #include "cfganal.h"
43 #include "basic-block.h"
44 #include "tree-ssa-alias.h"
45 #include "internal-fn.h"
46 #include "gimple-expr.h"
47 #include "gimple.h"
48 #include "gimplify.h"
49 #include "gimple-iterator.h"
50 #include "gimplify-me.h"
51 #include "gimple-ssa.h"
52 #include "cgraph.h"
53 #include "tree-cfg.h"
54 #include "tree-phinodes.h"
55 #include "stringpool.h"
56 #include "tree-ssanames.h"
57 #include "tree-pass.h"
58 #include "gimple-pretty-print.h"
59 #include "cfgloop.h"
61 /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
62 type in the GIMPLE type system that is language-independent? */
63 #include "langhooks.h"
65 /* Need to include expr.h and optabs.h for lshift_cheap_p. */
66 #include "rtl.h"
67 #include "insn-config.h"
68 #include "expmed.h"
69 #include "dojump.h"
70 #include "explow.h"
71 #include "calls.h"
72 #include "emit-rtl.h"
73 #include "stmt.h"
74 #include "expr.h"
75 #include "insn-codes.h"
76 #include "optabs.h"
78 /* Maximum number of case bit tests.
79 FIXME: This should be derived from PARAM_CASE_VALUES_THRESHOLD and
80 targetm.case_values_threshold(), or be its own param. */
81 #define MAX_CASE_BIT_TESTS 3
83 /* Split the basic block at the statement pointed to by GSIP, and insert
84 a branch to the target basic block of E_TRUE conditional on tree
85 expression COND.
87 It is assumed that there is already an edge from the to-be-split
88 basic block to E_TRUE->dest block. This edge is removed, and the
89 profile information on the edge is re-used for the new conditional
90 jump.
92 The CFG is updated. The dominator tree will not be valid after
93 this transformation, but the immediate dominators are updated if
94 UPDATE_DOMINATORS is true.
96 Returns the newly created basic block. */
98 static basic_block
99 hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
100 tree cond, edge e_true,
101 bool update_dominators)
103 tree tmp;
104 gcond *cond_stmt;
105 edge e_false;
106 basic_block new_bb, split_bb = gsi_bb (*gsip);
107 bool dominated_e_true = false;
109 gcc_assert (e_true->src == split_bb);
111 if (update_dominators
112 && get_immediate_dominator (CDI_DOMINATORS, e_true->dest) == split_bb)
113 dominated_e_true = true;
115 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
116 /*before=*/true, GSI_SAME_STMT);
117 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
118 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
120 e_false = split_block (split_bb, cond_stmt);
121 new_bb = e_false->dest;
122 redirect_edge_pred (e_true, split_bb);
124 e_true->flags &= ~EDGE_FALLTHRU;
125 e_true->flags |= EDGE_TRUE_VALUE;
127 e_false->flags &= ~EDGE_FALLTHRU;
128 e_false->flags |= EDGE_FALSE_VALUE;
129 e_false->probability = REG_BR_PROB_BASE - e_true->probability;
130 e_false->count = split_bb->count - e_true->count;
131 new_bb->count = e_false->count;
133 if (update_dominators)
135 if (dominated_e_true)
136 set_immediate_dominator (CDI_DOMINATORS, e_true->dest, split_bb);
137 set_immediate_dominator (CDI_DOMINATORS, e_false->dest, split_bb);
140 return new_bb;
144 /* Return true if a switch should be expanded as a bit test.
145 RANGE is the difference between highest and lowest case.
146 UNIQ is number of unique case node targets, not counting the default case.
147 COUNT is the number of comparisons needed, not counting the default case. */
149 static bool
150 expand_switch_using_bit_tests_p (tree range,
151 unsigned int uniq,
152 unsigned int count, bool speed_p)
154 return (((uniq == 1 && count >= 3)
155 || (uniq == 2 && count >= 5)
156 || (uniq == 3 && count >= 6))
157 && lshift_cheap_p (speed_p)
158 && compare_tree_int (range, GET_MODE_BITSIZE (word_mode)) < 0
159 && compare_tree_int (range, 0) > 0);
162 /* Implement switch statements with bit tests
164 A GIMPLE switch statement can be expanded to a short sequence of bit-wise
165 comparisons. "switch(x)" is converted into "if ((1 << (x-MINVAL)) & CST)"
166 where CST and MINVAL are integer constants. This is better than a series
167 of compare-and-banch insns in some cases, e.g. we can implement:
169 if ((x==4) || (x==6) || (x==9) || (x==11))
171 as a single bit test:
173 if ((1<<x) & ((1<<4)|(1<<6)|(1<<9)|(1<<11)))
175 This transformation is only applied if the number of case targets is small,
176 if CST constains at least 3 bits, and "1 << x" is cheap. The bit tests are
177 performed in "word_mode".
179 The following example shows the code the transformation generates:
181 int bar(int x)
183 switch (x)
185 case '0': case '1': case '2': case '3': case '4':
186 case '5': case '6': case '7': case '8': case '9':
187 case 'A': case 'B': case 'C': case 'D': case 'E':
188 case 'F':
189 return 1;
191 return 0;
196 bar (int x)
198 tmp1 = x - 48;
199 if (tmp1 > (70 - 48)) goto L2;
200 tmp2 = 1 << tmp1;
201 tmp3 = 0b11111100000001111111111;
202 if ((tmp2 & tmp3) != 0) goto L1 ; else goto L2;
204 return 1;
206 return 0;
209 TODO: There are still some improvements to this transformation that could
210 be implemented:
212 * A narrower mode than word_mode could be used if that is cheaper, e.g.
213 for x86_64 where a narrower-mode shift may result in smaller code.
215 * The compounded constant could be shifted rather than the one. The
216 test would be either on the sign bit or on the least significant bit,
217 depending on the direction of the shift. On some machines, the test
218 for the branch would be free if the bit to test is already set by the
219 shift operation.
221 This transformation was contributed by Roger Sayle, see this e-mail:
222 http://gcc.gnu.org/ml/gcc-patches/2003-01/msg01950.html
225 /* A case_bit_test represents a set of case nodes that may be
226 selected from using a bit-wise comparison. HI and LO hold
227 the integer to be tested against, TARGET_EDGE contains the
228 edge to the basic block to jump to upon success and BITS
229 counts the number of case nodes handled by this test,
230 typically the number of bits set in HI:LO. The LABEL field
231 is used to quickly identify all cases in this set without
232 looking at label_to_block for every case label. */
234 struct case_bit_test
236 wide_int mask;
237 edge target_edge;
238 tree label;
239 int bits;
242 /* Comparison function for qsort to order bit tests by decreasing
243 probability of execution. Our best guess comes from a measured
244 profile. If the profile counts are equal, break even on the
245 number of case nodes, i.e. the node with the most cases gets
246 tested first.
248 TODO: Actually this currently runs before a profile is available.
249 Therefore the case-as-bit-tests transformation should be done
250 later in the pass pipeline, or something along the lines of
251 "Efficient and effective branch reordering using profile data"
252 (Yang et. al., 2002) should be implemented (although, how good
253 is a paper is called "Efficient and effective ..." when the
254 latter is implied by the former, but oh well...). */
256 static int
257 case_bit_test_cmp (const void *p1, const void *p2)
259 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
260 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
262 if (d2->target_edge->count != d1->target_edge->count)
263 return d2->target_edge->count - d1->target_edge->count;
264 if (d2->bits != d1->bits)
265 return d2->bits - d1->bits;
267 /* Stabilize the sort. */
268 return LABEL_DECL_UID (d2->label) - LABEL_DECL_UID (d1->label);
271 /* Expand a switch statement by a short sequence of bit-wise
272 comparisons. "switch(x)" is effectively converted into
273 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
274 integer constants.
276 INDEX_EXPR is the value being switched on.
278 MINVAL is the lowest case value of in the case nodes,
279 and RANGE is highest value minus MINVAL. MINVAL and RANGE
280 are not guaranteed to be of the same type as INDEX_EXPR
281 (the gimplifier doesn't change the type of case label values,
282 and MINVAL and RANGE are derived from those values).
283 MAXVAL is MINVAL + RANGE.
285 There *MUST* be MAX_CASE_BIT_TESTS or less unique case
286 node targets. */
288 static void
289 emit_case_bit_tests (gswitch *swtch, tree index_expr,
290 tree minval, tree range, tree maxval)
292 struct case_bit_test test[MAX_CASE_BIT_TESTS];
293 unsigned int i, j, k;
294 unsigned int count;
296 basic_block switch_bb = gimple_bb (swtch);
297 basic_block default_bb, new_default_bb, new_bb;
298 edge default_edge;
299 bool update_dom = dom_info_available_p (CDI_DOMINATORS);
301 vec<basic_block> bbs_to_fix_dom = vNULL;
303 tree index_type = TREE_TYPE (index_expr);
304 tree unsigned_index_type = unsigned_type_for (index_type);
305 unsigned int branch_num = gimple_switch_num_labels (swtch);
307 gimple_stmt_iterator gsi;
308 gassign *shift_stmt;
310 tree idx, tmp, csui;
311 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
312 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
313 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
314 int prec = TYPE_PRECISION (word_type_node);
315 wide_int wone = wi::one (prec);
317 memset (&test, 0, sizeof (test));
319 /* Get the edge for the default case. */
320 tmp = gimple_switch_default_label (swtch);
321 default_bb = label_to_block (CASE_LABEL (tmp));
322 default_edge = find_edge (switch_bb, default_bb);
324 /* Go through all case labels, and collect the case labels, profile
325 counts, and other information we need to build the branch tests. */
326 count = 0;
327 for (i = 1; i < branch_num; i++)
329 unsigned int lo, hi;
330 tree cs = gimple_switch_label (swtch, i);
331 tree label = CASE_LABEL (cs);
332 edge e = find_edge (switch_bb, label_to_block (label));
333 for (k = 0; k < count; k++)
334 if (e == test[k].target_edge)
335 break;
337 if (k == count)
339 gcc_checking_assert (count < MAX_CASE_BIT_TESTS);
340 test[k].mask = wi::zero (prec);
341 test[k].target_edge = e;
342 test[k].label = label;
343 test[k].bits = 1;
344 count++;
346 else
347 test[k].bits++;
349 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR,
350 CASE_LOW (cs), minval));
351 if (CASE_HIGH (cs) == NULL_TREE)
352 hi = lo;
353 else
354 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR,
355 CASE_HIGH (cs), minval));
357 for (j = lo; j <= hi; j++)
358 test[k].mask |= wi::lshift (wone, j);
361 qsort (test, count, sizeof (*test), case_bit_test_cmp);
363 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
364 the minval subtractions, but it might make the mask constants more
365 expensive. So, compare the costs. */
366 if (compare_tree_int (minval, 0) > 0
367 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
369 int cost_diff;
370 HOST_WIDE_INT m = tree_to_uhwi (minval);
371 rtx reg = gen_raw_REG (word_mode, 10000);
372 bool speed_p = optimize_bb_for_speed_p (gimple_bb (swtch));
373 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
374 GEN_INT (-m)), speed_p);
375 for (i = 0; i < count; i++)
377 rtx r = immed_wide_int_const (test[i].mask, word_mode);
378 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r), speed_p);
379 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
380 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r), speed_p);
382 if (cost_diff > 0)
384 for (i = 0; i < count; i++)
385 test[i].mask = wi::lshift (test[i].mask, m);
386 minval = build_zero_cst (TREE_TYPE (minval));
387 range = maxval;
391 /* We generate two jumps to the default case label.
392 Split the default edge, so that we don't have to do any PHI node
393 updating. */
394 new_default_bb = split_edge (default_edge);
396 if (update_dom)
398 bbs_to_fix_dom.create (10);
399 bbs_to_fix_dom.quick_push (switch_bb);
400 bbs_to_fix_dom.quick_push (default_bb);
401 bbs_to_fix_dom.quick_push (new_default_bb);
404 /* Now build the test-and-branch code. */
406 gsi = gsi_last_bb (switch_bb);
408 /* idx = (unsigned)x - minval. */
409 idx = fold_convert (unsigned_index_type, index_expr);
410 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
411 fold_convert (unsigned_index_type, minval));
412 idx = force_gimple_operand_gsi (&gsi, idx,
413 /*simple=*/true, NULL_TREE,
414 /*before=*/true, GSI_SAME_STMT);
416 /* if (idx > range) goto default */
417 range = force_gimple_operand_gsi (&gsi,
418 fold_convert (unsigned_index_type, range),
419 /*simple=*/true, NULL_TREE,
420 /*before=*/true, GSI_SAME_STMT);
421 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
422 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_edge, update_dom);
423 if (update_dom)
424 bbs_to_fix_dom.quick_push (new_bb);
425 gcc_assert (gimple_bb (swtch) == new_bb);
426 gsi = gsi_last_bb (new_bb);
428 /* Any blocks dominated by the GIMPLE_SWITCH, but that are not successors
429 of NEW_BB, are still immediately dominated by SWITCH_BB. Make it so. */
430 if (update_dom)
432 vec<basic_block> dom_bbs;
433 basic_block dom_son;
435 dom_bbs = get_dominated_by (CDI_DOMINATORS, new_bb);
436 FOR_EACH_VEC_ELT (dom_bbs, i, dom_son)
438 edge e = find_edge (new_bb, dom_son);
439 if (e && single_pred_p (e->dest))
440 continue;
441 set_immediate_dominator (CDI_DOMINATORS, dom_son, switch_bb);
442 bbs_to_fix_dom.safe_push (dom_son);
444 dom_bbs.release ();
447 /* csui = (1 << (word_mode) idx) */
448 csui = make_ssa_name (word_type_node);
449 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
450 fold_convert (word_type_node, idx));
451 tmp = force_gimple_operand_gsi (&gsi, tmp,
452 /*simple=*/false, NULL_TREE,
453 /*before=*/true, GSI_SAME_STMT);
454 shift_stmt = gimple_build_assign (csui, tmp);
455 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
456 update_stmt (shift_stmt);
458 /* for each unique set of cases:
459 if (const & csui) goto target */
460 for (k = 0; k < count; k++)
462 tmp = wide_int_to_tree (word_type_node, test[k].mask);
463 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
464 tmp = force_gimple_operand_gsi (&gsi, tmp,
465 /*simple=*/true, NULL_TREE,
466 /*before=*/true, GSI_SAME_STMT);
467 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
468 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_edge,
469 update_dom);
470 if (update_dom)
471 bbs_to_fix_dom.safe_push (new_bb);
472 gcc_assert (gimple_bb (swtch) == new_bb);
473 gsi = gsi_last_bb (new_bb);
476 /* We should have removed all edges now. */
477 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
479 /* If nothing matched, go to the default label. */
480 make_edge (gsi_bb (gsi), new_default_bb, EDGE_FALLTHRU);
482 /* The GIMPLE_SWITCH is now redundant. */
483 gsi_remove (&gsi, true);
485 if (update_dom)
487 /* Fix up the dominator tree. */
488 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
489 bbs_to_fix_dom.release ();
494 Switch initialization conversion
496 The following pass changes simple initializations of scalars in a switch
497 statement into initializations from a static array. Obviously, the values
498 must be constant and known at compile time and a default branch must be
499 provided. For example, the following code:
501 int a,b;
503 switch (argc)
505 case 1:
506 case 2:
507 a_1 = 8;
508 b_1 = 6;
509 break;
510 case 3:
511 a_2 = 9;
512 b_2 = 5;
513 break;
514 case 12:
515 a_3 = 10;
516 b_3 = 4;
517 break;
518 default:
519 a_4 = 16;
520 b_4 = 1;
521 break;
523 a_5 = PHI <a_1, a_2, a_3, a_4>
524 b_5 = PHI <b_1, b_2, b_3, b_4>
527 is changed into:
529 static const int = CSWTCH01[] = {6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 4};
530 static const int = CSWTCH02[] = {8, 8, 9, 16, 16, 16, 16, 16, 16, 16,
531 16, 16, 10};
533 if (((unsigned) argc) - 1 < 11)
535 a_6 = CSWTCH02[argc - 1];
536 b_6 = CSWTCH01[argc - 1];
538 else
540 a_7 = 16;
541 b_7 = 1;
543 a_5 = PHI <a_6, a_7>
544 b_b = PHI <b_6, b_7>
546 There are further constraints. Specifically, the range of values across all
547 case labels must not be bigger than SWITCH_CONVERSION_BRANCH_RATIO (default
548 eight) times the number of the actual switch branches.
550 This transformation was contributed by Martin Jambor, see this e-mail:
551 http://gcc.gnu.org/ml/gcc-patches/2008-07/msg00011.html */
553 /* The main structure of the pass. */
554 struct switch_conv_info
556 /* The expression used to decide the switch branch. */
557 tree index_expr;
559 /* The following integer constants store the minimum and maximum value
560 covered by the case labels. */
561 tree range_min;
562 tree range_max;
564 /* The difference between the above two numbers. Stored here because it
565 is used in all the conversion heuristics, as well as for some of the
566 transformation, and it is expensive to re-compute it all the time. */
567 tree range_size;
569 /* Basic block that contains the actual GIMPLE_SWITCH. */
570 basic_block switch_bb;
572 /* Basic block that is the target of the default case. */
573 basic_block default_bb;
575 /* The single successor block of all branches out of the GIMPLE_SWITCH,
576 if such a block exists. Otherwise NULL. */
577 basic_block final_bb;
579 /* The probability of the default edge in the replaced switch. */
580 int default_prob;
582 /* The count of the default edge in the replaced switch. */
583 gcov_type default_count;
585 /* Combined count of all other (non-default) edges in the replaced switch. */
586 gcov_type other_count;
588 /* Number of phi nodes in the final bb (that we'll be replacing). */
589 int phi_count;
591 /* Array of default values, in the same order as phi nodes. */
592 tree *default_values;
594 /* Constructors of new static arrays. */
595 vec<constructor_elt, va_gc> **constructors;
597 /* Array of ssa names that are initialized with a value from a new static
598 array. */
599 tree *target_inbound_names;
601 /* Array of ssa names that are initialized with the default value if the
602 switch expression is out of range. */
603 tree *target_outbound_names;
605 /* The first load statement that loads a temporary from a new static array.
607 gimple arr_ref_first;
609 /* The last load statement that loads a temporary from a new static array. */
610 gimple arr_ref_last;
612 /* String reason why the case wasn't a good candidate that is written to the
613 dump file, if there is one. */
614 const char *reason;
616 /* Parameters for expand_switch_using_bit_tests. Should be computed
617 the same way as in expand_case. */
618 unsigned int uniq;
619 unsigned int count;
622 /* Collect information about GIMPLE_SWITCH statement SWTCH into INFO. */
624 static void
625 collect_switch_conv_info (gswitch *swtch, struct switch_conv_info *info)
627 unsigned int branch_num = gimple_switch_num_labels (swtch);
628 tree min_case, max_case;
629 unsigned int count, i;
630 edge e, e_default;
631 edge_iterator ei;
633 memset (info, 0, sizeof (*info));
635 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
636 is a default label which is the first in the vector.
637 Collect the bits we can deduce from the CFG. */
638 info->index_expr = gimple_switch_index (swtch);
639 info->switch_bb = gimple_bb (swtch);
640 info->default_bb =
641 label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
642 e_default = find_edge (info->switch_bb, info->default_bb);
643 info->default_prob = e_default->probability;
644 info->default_count = e_default->count;
645 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
646 if (e != e_default)
647 info->other_count += e->count;
649 /* See if there is one common successor block for all branch
650 targets. If it exists, record it in FINAL_BB.
651 Start with the destination of the default case as guess
652 or its destination in case it is a forwarder block. */
653 if (! single_pred_p (e_default->dest))
654 info->final_bb = e_default->dest;
655 else if (single_succ_p (e_default->dest)
656 && ! single_pred_p (single_succ (e_default->dest)))
657 info->final_bb = single_succ (e_default->dest);
658 /* Require that all switch destinations are either that common
659 FINAL_BB or a forwarder to it. */
660 if (info->final_bb)
661 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
663 if (e->dest == info->final_bb)
664 continue;
666 if (single_pred_p (e->dest)
667 && single_succ_p (e->dest)
668 && single_succ (e->dest) == info->final_bb)
669 continue;
671 info->final_bb = NULL;
672 break;
675 /* Get upper and lower bounds of case values, and the covered range. */
676 min_case = gimple_switch_label (swtch, 1);
677 max_case = gimple_switch_label (swtch, branch_num - 1);
679 info->range_min = CASE_LOW (min_case);
680 if (CASE_HIGH (max_case) != NULL_TREE)
681 info->range_max = CASE_HIGH (max_case);
682 else
683 info->range_max = CASE_LOW (max_case);
685 info->range_size =
686 int_const_binop (MINUS_EXPR, info->range_max, info->range_min);
688 /* Get a count of the number of case labels. Single-valued case labels
689 simply count as one, but a case range counts double, since it may
690 require two compares if it gets lowered as a branching tree. */
691 count = 0;
692 for (i = 1; i < branch_num; i++)
694 tree elt = gimple_switch_label (swtch, i);
695 count++;
696 if (CASE_HIGH (elt)
697 && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
698 count++;
700 info->count = count;
702 /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
703 block. Assume a CFG cleanup would have already removed degenerate
704 switch statements, this allows us to just use EDGE_COUNT. */
705 info->uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
708 /* Checks whether the range given by individual case statements of the SWTCH
709 switch statement isn't too big and whether the number of branches actually
710 satisfies the size of the new array. */
712 static bool
713 check_range (struct switch_conv_info *info)
715 gcc_assert (info->range_size);
716 if (!tree_fits_uhwi_p (info->range_size))
718 info->reason = "index range way too large or otherwise unusable";
719 return false;
722 if (tree_to_uhwi (info->range_size)
723 > ((unsigned) info->count * SWITCH_CONVERSION_BRANCH_RATIO))
725 info->reason = "the maximum range-branch ratio exceeded";
726 return false;
729 return true;
732 /* Checks whether all but the FINAL_BB basic blocks are empty. */
734 static bool
735 check_all_empty_except_final (struct switch_conv_info *info)
737 edge e;
738 edge_iterator ei;
740 FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
742 if (e->dest == info->final_bb)
743 continue;
745 if (!empty_block_p (e->dest))
747 info->reason = "bad case - a non-final BB not empty";
748 return false;
752 return true;
755 /* This function checks whether all required values in phi nodes in final_bb
756 are constants. Required values are those that correspond to a basic block
757 which is a part of the examined switch statement. It returns true if the
758 phi nodes are OK, otherwise false. */
760 static bool
761 check_final_bb (struct switch_conv_info *info)
763 gphi_iterator gsi;
765 info->phi_count = 0;
766 for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
768 gphi *phi = gsi.phi ();
769 unsigned int i;
771 info->phi_count++;
773 for (i = 0; i < gimple_phi_num_args (phi); i++)
775 basic_block bb = gimple_phi_arg_edge (phi, i)->src;
777 if (bb == info->switch_bb
778 || (single_pred_p (bb) && single_pred (bb) == info->switch_bb))
780 tree reloc, val;
782 val = gimple_phi_arg_def (phi, i);
783 if (!is_gimple_ip_invariant (val))
785 info->reason = "non-invariant value from a case";
786 return false; /* Non-invariant argument. */
788 reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
789 if ((flag_pic && reloc != null_pointer_node)
790 || (!flag_pic && reloc == NULL_TREE))
792 if (reloc)
793 info->reason
794 = "value from a case would need runtime relocations";
795 else
796 info->reason
797 = "value from a case is not a valid initializer";
798 return false;
804 return true;
807 /* The following function allocates default_values, target_{in,out}_names and
808 constructors arrays. The last one is also populated with pointers to
809 vectors that will become constructors of new arrays. */
811 static void
812 create_temp_arrays (struct switch_conv_info *info)
814 int i;
816 info->default_values = XCNEWVEC (tree, info->phi_count * 3);
817 /* ??? Macros do not support multi argument templates in their
818 argument list. We create a typedef to work around that problem. */
819 typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
820 info->constructors = XCNEWVEC (vec_constructor_elt_gc, info->phi_count);
821 info->target_inbound_names = info->default_values + info->phi_count;
822 info->target_outbound_names = info->target_inbound_names + info->phi_count;
823 for (i = 0; i < info->phi_count; i++)
824 vec_alloc (info->constructors[i], tree_to_uhwi (info->range_size) + 1);
827 /* Free the arrays created by create_temp_arrays(). The vectors that are
828 created by that function are not freed here, however, because they have
829 already become constructors and must be preserved. */
831 static void
832 free_temp_arrays (struct switch_conv_info *info)
834 XDELETEVEC (info->constructors);
835 XDELETEVEC (info->default_values);
838 /* Populate the array of default values in the order of phi nodes.
839 DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch. */
841 static void
842 gather_default_values (tree default_case, struct switch_conv_info *info)
844 gphi_iterator gsi;
845 basic_block bb = label_to_block (CASE_LABEL (default_case));
846 edge e;
847 int i = 0;
849 gcc_assert (CASE_LOW (default_case) == NULL_TREE);
851 if (bb == info->final_bb)
852 e = find_edge (info->switch_bb, bb);
853 else
854 e = single_succ_edge (bb);
856 for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
858 gphi *phi = gsi.phi ();
859 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
860 gcc_assert (val);
861 info->default_values[i++] = val;
865 /* The following function populates the vectors in the constructors array with
866 future contents of the static arrays. The vectors are populated in the
867 order of phi nodes. SWTCH is the switch statement being converted. */
869 static void
870 build_constructors (gswitch *swtch, struct switch_conv_info *info)
872 unsigned i, branch_num = gimple_switch_num_labels (swtch);
873 tree pos = info->range_min;
875 for (i = 1; i < branch_num; i++)
877 tree cs = gimple_switch_label (swtch, i);
878 basic_block bb = label_to_block (CASE_LABEL (cs));
879 edge e;
880 tree high;
881 gphi_iterator gsi;
882 int j;
884 if (bb == info->final_bb)
885 e = find_edge (info->switch_bb, bb);
886 else
887 e = single_succ_edge (bb);
888 gcc_assert (e);
890 while (tree_int_cst_lt (pos, CASE_LOW (cs)))
892 int k;
893 for (k = 0; k < info->phi_count; k++)
895 constructor_elt elt;
897 elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
898 elt.value
899 = unshare_expr_without_location (info->default_values[k]);
900 info->constructors[k]->quick_push (elt);
903 pos = int_const_binop (PLUS_EXPR, pos,
904 build_int_cst (TREE_TYPE (pos), 1));
906 gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
908 j = 0;
909 if (CASE_HIGH (cs))
910 high = CASE_HIGH (cs);
911 else
912 high = CASE_LOW (cs);
913 for (gsi = gsi_start_phis (info->final_bb);
914 !gsi_end_p (gsi); gsi_next (&gsi))
916 gphi *phi = gsi.phi ();
917 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
918 tree low = CASE_LOW (cs);
919 pos = CASE_LOW (cs);
923 constructor_elt elt;
925 elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
926 elt.value = unshare_expr_without_location (val);
927 info->constructors[j]->quick_push (elt);
929 pos = int_const_binop (PLUS_EXPR, pos,
930 build_int_cst (TREE_TYPE (pos), 1));
931 } while (!tree_int_cst_lt (high, pos)
932 && tree_int_cst_lt (low, pos));
933 j++;
938 /* If all values in the constructor vector are the same, return the value.
939 Otherwise return NULL_TREE. Not supposed to be called for empty
940 vectors. */
942 static tree
943 constructor_contains_same_values_p (vec<constructor_elt, va_gc> *vec)
945 unsigned int i;
946 tree prev = NULL_TREE;
947 constructor_elt *elt;
949 FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
951 if (!prev)
952 prev = elt->value;
953 else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
954 return NULL_TREE;
956 return prev;
959 /* Return type which should be used for array elements, either TYPE,
960 or for integral type some smaller integral type that can still hold
961 all the constants. */
963 static tree
964 array_value_type (gswitch *swtch, tree type, int num,
965 struct switch_conv_info *info)
967 unsigned int i, len = vec_safe_length (info->constructors[num]);
968 constructor_elt *elt;
969 machine_mode mode;
970 int sign = 0;
971 tree smaller_type;
973 if (!INTEGRAL_TYPE_P (type))
974 return type;
976 mode = GET_CLASS_NARROWEST_MODE (GET_MODE_CLASS (TYPE_MODE (type)));
977 if (GET_MODE_SIZE (TYPE_MODE (type)) <= GET_MODE_SIZE (mode))
978 return type;
980 if (len < (optimize_bb_for_size_p (gimple_bb (swtch)) ? 2 : 32))
981 return type;
983 FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
985 wide_int cst;
987 if (TREE_CODE (elt->value) != INTEGER_CST)
988 return type;
990 cst = elt->value;
991 while (1)
993 unsigned int prec = GET_MODE_BITSIZE (mode);
994 if (prec > HOST_BITS_PER_WIDE_INT)
995 return type;
997 if (sign >= 0 && cst == wi::zext (cst, prec))
999 if (sign == 0 && cst == wi::sext (cst, prec))
1000 break;
1001 sign = 1;
1002 break;
1004 if (sign <= 0 && cst == wi::sext (cst, prec))
1006 sign = -1;
1007 break;
1010 if (sign == 1)
1011 sign = 0;
1013 mode = GET_MODE_WIDER_MODE (mode);
1014 if (mode == VOIDmode
1015 || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (TYPE_MODE (type)))
1016 return type;
1020 if (sign == 0)
1021 sign = TYPE_UNSIGNED (type) ? 1 : -1;
1022 smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
1023 if (GET_MODE_SIZE (TYPE_MODE (type))
1024 <= GET_MODE_SIZE (TYPE_MODE (smaller_type)))
1025 return type;
1027 return smaller_type;
1030 /* Create an appropriate array type and declaration and assemble a static array
1031 variable. Also create a load statement that initializes the variable in
1032 question with a value from the static array. SWTCH is the switch statement
1033 being converted, NUM is the index to arrays of constructors, default values
1034 and target SSA names for this particular array. ARR_INDEX_TYPE is the type
1035 of the index of the new array, PHI is the phi node of the final BB that
1036 corresponds to the value that will be loaded from the created array. TIDX
1037 is an ssa name of a temporary variable holding the index for loads from the
1038 new array. */
1040 static void
1041 build_one_array (gswitch *swtch, int num, tree arr_index_type,
1042 gphi *phi, tree tidx, struct switch_conv_info *info)
1044 tree name, cst;
1045 gimple load;
1046 gimple_stmt_iterator gsi = gsi_for_stmt (swtch);
1047 location_t loc = gimple_location (swtch);
1049 gcc_assert (info->default_values[num]);
1051 name = copy_ssa_name (PHI_RESULT (phi));
1052 info->target_inbound_names[num] = name;
1054 cst = constructor_contains_same_values_p (info->constructors[num]);
1055 if (cst)
1056 load = gimple_build_assign (name, cst);
1057 else
1059 tree array_type, ctor, decl, value_type, fetch, default_type;
1061 default_type = TREE_TYPE (info->default_values[num]);
1062 value_type = array_value_type (swtch, default_type, num, info);
1063 array_type = build_array_type (value_type, arr_index_type);
1064 if (default_type != value_type)
1066 unsigned int i;
1067 constructor_elt *elt;
1069 FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
1070 elt->value = fold_convert (value_type, elt->value);
1072 ctor = build_constructor (array_type, info->constructors[num]);
1073 TREE_CONSTANT (ctor) = true;
1074 TREE_STATIC (ctor) = true;
1076 decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
1077 TREE_STATIC (decl) = 1;
1078 DECL_INITIAL (decl) = ctor;
1080 DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
1081 DECL_ARTIFICIAL (decl) = 1;
1082 DECL_IGNORED_P (decl) = 1;
1083 TREE_CONSTANT (decl) = 1;
1084 TREE_READONLY (decl) = 1;
1085 DECL_IGNORED_P (decl) = 1;
1086 varpool_node::finalize_decl (decl);
1088 fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
1089 NULL_TREE);
1090 if (default_type != value_type)
1092 fetch = fold_convert (default_type, fetch);
1093 fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
1094 true, GSI_SAME_STMT);
1096 load = gimple_build_assign (name, fetch);
1099 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1100 update_stmt (load);
1101 info->arr_ref_last = load;
1104 /* Builds and initializes static arrays initialized with values gathered from
1105 the SWTCH switch statement. Also creates statements that load values from
1106 them. */
1108 static void
1109 build_arrays (gswitch *swtch, struct switch_conv_info *info)
1111 tree arr_index_type;
1112 tree tidx, sub, utype;
1113 gimple stmt;
1114 gimple_stmt_iterator gsi;
1115 gphi_iterator gpi;
1116 int i;
1117 location_t loc = gimple_location (swtch);
1119 gsi = gsi_for_stmt (swtch);
1121 /* Make sure we do not generate arithmetics in a subrange. */
1122 utype = TREE_TYPE (info->index_expr);
1123 if (TREE_TYPE (utype))
1124 utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
1125 else
1126 utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
1128 arr_index_type = build_index_type (info->range_size);
1129 tidx = make_ssa_name (utype);
1130 sub = fold_build2_loc (loc, MINUS_EXPR, utype,
1131 fold_convert_loc (loc, utype, info->index_expr),
1132 fold_convert_loc (loc, utype, info->range_min));
1133 sub = force_gimple_operand_gsi (&gsi, sub,
1134 false, NULL, true, GSI_SAME_STMT);
1135 stmt = gimple_build_assign (tidx, sub);
1137 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1138 update_stmt (stmt);
1139 info->arr_ref_first = stmt;
1141 for (gpi = gsi_start_phis (info->final_bb), i = 0;
1142 !gsi_end_p (gpi); gsi_next (&gpi), i++)
1143 build_one_array (swtch, i, arr_index_type, gpi.phi (), tidx, info);
1146 /* Generates and appropriately inserts loads of default values at the position
1147 given by BSI. Returns the last inserted statement. */
1149 static gassign *
1150 gen_def_assigns (gimple_stmt_iterator *gsi, struct switch_conv_info *info)
1152 int i;
1153 gassign *assign = NULL;
1155 for (i = 0; i < info->phi_count; i++)
1157 tree name = copy_ssa_name (info->target_inbound_names[i]);
1158 info->target_outbound_names[i] = name;
1159 assign = gimple_build_assign (name, info->default_values[i]);
1160 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
1161 update_stmt (assign);
1163 return assign;
1166 /* Deletes the unused bbs and edges that now contain the switch statement and
1167 its empty branch bbs. BBD is the now dead BB containing the original switch
1168 statement, FINAL is the last BB of the converted switch statement (in terms
1169 of succession). */
1171 static void
1172 prune_bbs (basic_block bbd, basic_block final)
1174 edge_iterator ei;
1175 edge e;
1177 for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
1179 basic_block bb;
1180 bb = e->dest;
1181 remove_edge (e);
1182 if (bb != final)
1183 delete_basic_block (bb);
1185 delete_basic_block (bbd);
1188 /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
1189 from the basic block loading values from an array and E2F from the basic
1190 block loading default values. BBF is the last switch basic block (see the
1191 bbf description in the comment below). */
1193 static void
1194 fix_phi_nodes (edge e1f, edge e2f, basic_block bbf,
1195 struct switch_conv_info *info)
1197 gphi_iterator gsi;
1198 int i;
1200 for (gsi = gsi_start_phis (bbf), i = 0;
1201 !gsi_end_p (gsi); gsi_next (&gsi), i++)
1203 gphi *phi = gsi.phi ();
1204 add_phi_arg (phi, info->target_inbound_names[i], e1f, UNKNOWN_LOCATION);
1205 add_phi_arg (phi, info->target_outbound_names[i], e2f, UNKNOWN_LOCATION);
1209 /* Creates a check whether the switch expression value actually falls into the
1210 range given by all the cases. If it does not, the temporaries are loaded
1211 with default values instead. SWTCH is the switch statement being converted.
1213 bb0 is the bb with the switch statement, however, we'll end it with a
1214 condition instead.
1216 bb1 is the bb to be used when the range check went ok. It is derived from
1217 the switch BB
1219 bb2 is the bb taken when the expression evaluated outside of the range
1220 covered by the created arrays. It is populated by loads of default
1221 values.
1223 bbF is a fall through for both bb1 and bb2 and contains exactly what
1224 originally followed the switch statement.
1226 bbD contains the switch statement (in the end). It is unreachable but we
1227 still need to strip off its edges.
1230 static void
1231 gen_inbound_check (gswitch *swtch, struct switch_conv_info *info)
1233 tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
1234 tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
1235 tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
1236 glabel *label1, *label2, *label3;
1237 tree utype, tidx;
1238 tree bound;
1240 gcond *cond_stmt;
1242 gassign *last_assign;
1243 gimple_stmt_iterator gsi;
1244 basic_block bb0, bb1, bb2, bbf, bbd;
1245 edge e01, e02, e21, e1d, e1f, e2f;
1246 location_t loc = gimple_location (swtch);
1248 gcc_assert (info->default_values);
1250 bb0 = gimple_bb (swtch);
1252 tidx = gimple_assign_lhs (info->arr_ref_first);
1253 utype = TREE_TYPE (tidx);
1255 /* (end of) block 0 */
1256 gsi = gsi_for_stmt (info->arr_ref_first);
1257 gsi_next (&gsi);
1259 bound = fold_convert_loc (loc, utype, info->range_size);
1260 cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
1261 gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
1262 update_stmt (cond_stmt);
1264 /* block 2 */
1265 label2 = gimple_build_label (label_decl2);
1266 gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
1267 last_assign = gen_def_assigns (&gsi, info);
1269 /* block 1 */
1270 label1 = gimple_build_label (label_decl1);
1271 gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
1273 /* block F */
1274 gsi = gsi_start_bb (info->final_bb);
1275 label3 = gimple_build_label (label_decl3);
1276 gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
1278 /* cfg fix */
1279 e02 = split_block (bb0, cond_stmt);
1280 bb2 = e02->dest;
1282 e21 = split_block (bb2, last_assign);
1283 bb1 = e21->dest;
1284 remove_edge (e21);
1286 e1d = split_block (bb1, info->arr_ref_last);
1287 bbd = e1d->dest;
1288 remove_edge (e1d);
1290 /* flags and profiles of the edge for in-range values */
1291 e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
1292 e01->probability = REG_BR_PROB_BASE - info->default_prob;
1293 e01->count = info->other_count;
1295 /* flags and profiles of the edge taking care of out-of-range values */
1296 e02->flags &= ~EDGE_FALLTHRU;
1297 e02->flags |= EDGE_FALSE_VALUE;
1298 e02->probability = info->default_prob;
1299 e02->count = info->default_count;
1301 bbf = info->final_bb;
1303 e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
1304 e1f->probability = REG_BR_PROB_BASE;
1305 e1f->count = info->other_count;
1307 e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
1308 e2f->probability = REG_BR_PROB_BASE;
1309 e2f->count = info->default_count;
1311 /* frequencies of the new BBs */
1312 bb1->frequency = EDGE_FREQUENCY (e01);
1313 bb2->frequency = EDGE_FREQUENCY (e02);
1314 bbf->frequency = EDGE_FREQUENCY (e1f) + EDGE_FREQUENCY (e2f);
1316 /* Tidy blocks that have become unreachable. */
1317 prune_bbs (bbd, info->final_bb);
1319 /* Fixup the PHI nodes in bbF. */
1320 fix_phi_nodes (e1f, e2f, bbf, info);
1322 /* Fix the dominator tree, if it is available. */
1323 if (dom_info_available_p (CDI_DOMINATORS))
1325 vec<basic_block> bbs_to_fix_dom;
1327 set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
1328 set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
1329 if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
1330 /* If bbD was the immediate dominator ... */
1331 set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
1333 bbs_to_fix_dom.create (4);
1334 bbs_to_fix_dom.quick_push (bb0);
1335 bbs_to_fix_dom.quick_push (bb1);
1336 bbs_to_fix_dom.quick_push (bb2);
1337 bbs_to_fix_dom.quick_push (bbf);
1339 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
1340 bbs_to_fix_dom.release ();
1344 /* The following function is invoked on every switch statement (the current one
1345 is given in SWTCH) and runs the individual phases of switch conversion on it
1346 one after another until one fails or the conversion is completed.
1347 Returns NULL on success, or a pointer to a string with the reason why the
1348 conversion failed. */
1350 static const char *
1351 process_switch (gswitch *swtch)
1353 struct switch_conv_info info;
1355 /* Group case labels so that we get the right results from the heuristics
1356 that decide on the code generation approach for this switch. */
1357 group_case_labels_stmt (swtch);
1359 /* If this switch is now a degenerate case with only a default label,
1360 there is nothing left for us to do. */
1361 if (gimple_switch_num_labels (swtch) < 2)
1362 return "switch is a degenerate case";
1364 collect_switch_conv_info (swtch, &info);
1366 /* No error markers should reach here (they should be filtered out
1367 during gimplification). */
1368 gcc_checking_assert (TREE_TYPE (info.index_expr) != error_mark_node);
1370 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
1371 gcc_checking_assert (! TREE_CONSTANT (info.index_expr));
1373 if (info.uniq <= MAX_CASE_BIT_TESTS)
1375 if (expand_switch_using_bit_tests_p (info.range_size,
1376 info.uniq, info.count,
1377 optimize_bb_for_speed_p
1378 (gimple_bb (swtch))))
1380 if (dump_file)
1381 fputs (" expanding as bit test is preferable\n", dump_file);
1382 emit_case_bit_tests (swtch, info.index_expr, info.range_min,
1383 info.range_size, info.range_max);
1384 loops_state_set (LOOPS_NEED_FIXUP);
1385 return NULL;
1388 if (info.uniq <= 2)
1389 /* This will be expanded as a decision tree in stmt.c:expand_case. */
1390 return " expanding as jumps is preferable";
1393 /* If there is no common successor, we cannot do the transformation. */
1394 if (! info.final_bb)
1395 return "no common successor to all case label target blocks found";
1397 /* Check the case label values are within reasonable range: */
1398 if (!check_range (&info))
1400 gcc_assert (info.reason);
1401 return info.reason;
1404 /* For all the cases, see whether they are empty, the assignments they
1405 represent constant and so on... */
1406 if (! check_all_empty_except_final (&info))
1408 gcc_assert (info.reason);
1409 return info.reason;
1411 if (!check_final_bb (&info))
1413 gcc_assert (info.reason);
1414 return info.reason;
1417 /* At this point all checks have passed and we can proceed with the
1418 transformation. */
1420 create_temp_arrays (&info);
1421 gather_default_values (gimple_switch_default_label (swtch), &info);
1422 build_constructors (swtch, &info);
1424 build_arrays (swtch, &info); /* Build the static arrays and assignments. */
1425 gen_inbound_check (swtch, &info); /* Build the bounds check. */
1427 /* Cleanup: */
1428 free_temp_arrays (&info);
1429 return NULL;
1432 /* The main function of the pass scans statements for switches and invokes
1433 process_switch on them. */
1435 namespace {
1437 const pass_data pass_data_convert_switch =
1439 GIMPLE_PASS, /* type */
1440 "switchconv", /* name */
1441 OPTGROUP_NONE, /* optinfo_flags */
1442 TV_TREE_SWITCH_CONVERSION, /* tv_id */
1443 ( PROP_cfg | PROP_ssa ), /* properties_required */
1444 0, /* properties_provided */
1445 0, /* properties_destroyed */
1446 0, /* todo_flags_start */
1447 TODO_update_ssa, /* todo_flags_finish */
1450 class pass_convert_switch : public gimple_opt_pass
1452 public:
1453 pass_convert_switch (gcc::context *ctxt)
1454 : gimple_opt_pass (pass_data_convert_switch, ctxt)
1457 /* opt_pass methods: */
1458 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
1459 virtual unsigned int execute (function *);
1461 }; // class pass_convert_switch
1463 unsigned int
1464 pass_convert_switch::execute (function *fun)
1466 basic_block bb;
1468 FOR_EACH_BB_FN (bb, fun)
1470 const char *failure_reason;
1471 gimple stmt = last_stmt (bb);
1472 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
1474 if (dump_file)
1476 expanded_location loc = expand_location (gimple_location (stmt));
1478 fprintf (dump_file, "beginning to process the following "
1479 "SWITCH statement (%s:%d) : ------- \n",
1480 loc.file, loc.line);
1481 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1482 putc ('\n', dump_file);
1485 failure_reason = process_switch (as_a <gswitch *> (stmt));
1486 if (! failure_reason)
1488 if (dump_file)
1490 fputs ("Switch converted\n", dump_file);
1491 fputs ("--------------------------------\n", dump_file);
1494 /* Make no effort to update the post-dominator tree. It is actually not
1495 that hard for the transformations we have performed, but it is not
1496 supported by iterate_fix_dominators. */
1497 free_dominance_info (CDI_POST_DOMINATORS);
1499 else
1501 if (dump_file)
1503 fputs ("Bailing out - ", dump_file);
1504 fputs (failure_reason, dump_file);
1505 fputs ("\n--------------------------------\n", dump_file);
1511 return 0;
1514 } // anon namespace
1516 gimple_opt_pass *
1517 make_pass_convert_switch (gcc::context *ctxt)
1519 return new pass_convert_switch (ctxt);