]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-switch-conversion.c
Fix clustering algorithm in switch expansion.
[thirdparty/gcc.git] / gcc / tree-switch-conversion.c
CommitLineData
531b10fc
SB
1/* Lower GIMPLE_SWITCH expressions to something more efficient than
2 a jump table.
85ec4feb 3 Copyright (C) 2006-2018 Free Software Foundation, Inc.
b6e99746
MJ
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 3, or (at your option) any
10later version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT
13ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not, write to the Free
19Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
2002110-1301, USA. */
21
531b10fc
SB
22/* This file handles the lowering of GIMPLE_SWITCH to an indexed
23 load, or a series of bit-test-and-branch expressions. */
24
25#include "config.h"
26#include "system.h"
27#include "coretypes.h"
c7131fb2 28#include "backend.h"
957060b5
AM
29#include "insn-codes.h"
30#include "rtl.h"
c7131fb2
AM
31#include "tree.h"
32#include "gimple.h"
957060b5
AM
33#include "cfghooks.h"
34#include "tree-pass.h"
c7131fb2 35#include "ssa.h"
957060b5
AM
36#include "optabs-tree.h"
37#include "cgraph.h"
38#include "gimple-pretty-print.h"
531b10fc 39#include "params.h"
40e23961 40#include "fold-const.h"
d8a2d370
DN
41#include "varasm.h"
42#include "stor-layout.h"
60393bbc 43#include "cfganal.h"
45b0be94 44#include "gimplify.h"
5be5c238 45#include "gimple-iterator.h"
18f429e2 46#include "gimplify-me.h"
442b4905 47#include "tree-cfg.h"
a9e0d843 48#include "cfgloop.h"
9dc3d6a9
ML
49#include "alloc-pool.h"
50#include "target.h"
51#include "tree-into-ssa.h"
46dbeb40 52#include "omp-general.h"
7ee2468b
SB
53
54/* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
55 type in the GIMPLE type system that is language-independent? */
531b10fc
SB
56#include "langhooks.h"
57
789410e4 58#include "tree-switch-conversion.h"
531b10fc 59\f
789410e4 60using namespace tree_switch_conversion;
531b10fc 61
789410e4 62/* Constructor. */
531b10fc 63
789410e4
ML
64switch_conversion::switch_conversion (): m_final_bb (NULL), m_other_count (),
65 m_constructors (NULL), m_default_values (NULL),
66 m_arr_ref_first (NULL), m_arr_ref_last (NULL),
67 m_reason (NULL), m_default_case_nonstandard (false), m_cfg_altered (false)
531b10fc 68{
531b10fc 69}
b6e99746 70
789410e4 71/* Collection information about SWTCH statement. */
886cd84f 72
789410e4
ML
73void
74switch_conversion::collect (gswitch *swtch)
b6e99746 75{
726a989a 76 unsigned int branch_num = gimple_switch_num_labels (swtch);
886cd84f 77 tree min_case, max_case;
789410e4 78 unsigned int i;
18bfe940 79 edge e, e_default, e_first;
886cd84f 80 edge_iterator ei;
18bfe940 81 basic_block first;
886cd84f 82
789410e4 83 m_switch = swtch;
b6e99746
MJ
84
85 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
fd8d363e
SB
86 is a default label which is the first in the vector.
87 Collect the bits we can deduce from the CFG. */
789410e4
ML
88 m_index_expr = gimple_switch_index (swtch);
89 m_switch_bb = gimple_bb (swtch);
90 m_default_bb
18bfe940 91 = label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
789410e4
ML
92 e_default = find_edge (m_switch_bb, m_default_bb);
93 m_default_prob = e_default->probability;
94 m_default_count = e_default->count ();
95 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
886cd84f 96 if (e != e_default)
789410e4 97 m_other_count += e->count ();
b6e99746 98
18bfe940
JJ
99 /* Get upper and lower bounds of case values, and the covered range. */
100 min_case = gimple_switch_label (swtch, 1);
101 max_case = gimple_switch_label (swtch, branch_num - 1);
102
789410e4 103 m_range_min = CASE_LOW (min_case);
18bfe940 104 if (CASE_HIGH (max_case) != NULL_TREE)
789410e4 105 m_range_max = CASE_HIGH (max_case);
18bfe940 106 else
789410e4 107 m_range_max = CASE_LOW (max_case);
18bfe940 108
789410e4
ML
109 m_contiguous_range = true;
110 tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : m_range_min;
18bfe940
JJ
111 for (i = 2; i < branch_num; i++)
112 {
113 tree elt = gimple_switch_label (swtch, i);
8e6cdc90 114 if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
18bfe940 115 {
789410e4 116 m_contiguous_range = false;
18bfe940
JJ
117 break;
118 }
119 last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
120 }
121
789410e4 122 if (m_contiguous_range)
18bfe940
JJ
123 {
124 first = label_to_block (CASE_LABEL (gimple_switch_label (swtch, 1)));
789410e4 125 e_first = find_edge (m_switch_bb, first);
18bfe940
JJ
126 }
127 else
128 {
789410e4 129 first = m_default_bb;
18bfe940
JJ
130 e_first = e_default;
131 }
132
886cd84f 133 /* See if there is one common successor block for all branch
866f20d6 134 targets. If it exists, record it in FINAL_BB.
18bfe940
JJ
135 Start with the destination of the first non-default case
136 if the range is contiguous and default case otherwise as
137 guess or its destination in case it is a forwarder block. */
138 if (! single_pred_p (e_first->dest))
789410e4 139 m_final_bb = e_first->dest;
18bfe940
JJ
140 else if (single_succ_p (e_first->dest)
141 && ! single_pred_p (single_succ (e_first->dest)))
789410e4 142 m_final_bb = single_succ (e_first->dest);
866f20d6 143 /* Require that all switch destinations are either that common
18bfe940
JJ
144 FINAL_BB or a forwarder to it, except for the default
145 case if contiguous range. */
789410e4
ML
146 if (m_final_bb)
147 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
886cd84f 148 {
789410e4 149 if (e->dest == m_final_bb)
886cd84f
SB
150 continue;
151
152 if (single_pred_p (e->dest)
153 && single_succ_p (e->dest)
789410e4 154 && single_succ (e->dest) == m_final_bb)
886cd84f
SB
155 continue;
156
789410e4 157 if (e == e_default && m_contiguous_range)
18bfe940 158 {
789410e4 159 m_default_case_nonstandard = true;
18bfe940
JJ
160 continue;
161 }
162
789410e4 163 m_final_bb = NULL;
886cd84f
SB
164 break;
165 }
166
789410e4
ML
167 m_range_size
168 = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
b6e99746 169
886cd84f
SB
170 /* Get a count of the number of case labels. Single-valued case labels
171 simply count as one, but a case range counts double, since it may
172 require two compares if it gets lowered as a branching tree. */
789410e4 173 m_count = 0;
886cd84f
SB
174 for (i = 1; i < branch_num; i++)
175 {
176 tree elt = gimple_switch_label (swtch, i);
789410e4 177 m_count++;
886cd84f
SB
178 if (CASE_HIGH (elt)
179 && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
789410e4 180 m_count++;
886cd84f 181 }
dc223ad4
ML
182
183 /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
184 block. Assume a CFG cleanup would have already removed degenerate
185 switch statements, this allows us to just use EDGE_COUNT. */
186 m_uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
886cd84f 187}
b6e99746 188
789410e4 189/* Checks whether the range given by individual case statements of the switch
886cd84f
SB
190 switch statement isn't too big and whether the number of branches actually
191 satisfies the size of the new array. */
b6e99746 192
789410e4
ML
193bool
194switch_conversion::check_range ()
886cd84f 195{
789410e4
ML
196 gcc_assert (m_range_size);
197 if (!tree_fits_uhwi_p (m_range_size))
b6e99746 198 {
789410e4 199 m_reason = "index range way too large or otherwise unusable";
b6e99746
MJ
200 return false;
201 }
202
789410e4
ML
203 if (tree_to_uhwi (m_range_size)
204 > ((unsigned) m_count * SWITCH_CONVERSION_BRANCH_RATIO))
b6e99746 205 {
789410e4 206 m_reason = "the maximum range-branch ratio exceeded";
b6e99746
MJ
207 return false;
208 }
209
210 return true;
211}
212
789410e4 213/* Checks whether all but the final BB basic blocks are empty. */
b6e99746 214
789410e4
ML
215bool
216switch_conversion::check_all_empty_except_final ()
b6e99746 217{
789410e4 218 edge e, e_default = find_edge (m_switch_bb, m_default_bb);
886cd84f 219 edge_iterator ei;
b6e99746 220
789410e4 221 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
b6e99746 222 {
789410e4 223 if (e->dest == m_final_bb)
886cd84f 224 continue;
b6e99746 225
886cd84f 226 if (!empty_block_p (e->dest))
b6e99746 227 {
789410e4 228 if (m_contiguous_range && e == e_default)
18bfe940 229 {
789410e4 230 m_default_case_nonstandard = true;
18bfe940
JJ
231 continue;
232 }
233
789410e4 234 m_reason = "bad case - a non-final BB not empty";
b6e99746
MJ
235 return false;
236 }
b6e99746
MJ
237 }
238
239 return true;
240}
241
242/* This function checks whether all required values in phi nodes in final_bb
243 are constants. Required values are those that correspond to a basic block
244 which is a part of the examined switch statement. It returns true if the
245 phi nodes are OK, otherwise false. */
246
789410e4
ML
247bool
248switch_conversion::check_final_bb ()
b6e99746 249{
538dd0b7 250 gphi_iterator gsi;
b6e99746 251
789410e4
ML
252 m_phi_count = 0;
253 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 254 {
538dd0b7 255 gphi *phi = gsi.phi ();
726a989a 256 unsigned int i;
b6e99746 257
18bfe940
JJ
258 if (virtual_operand_p (gimple_phi_result (phi)))
259 continue;
260
789410e4 261 m_phi_count++;
b6e99746 262
726a989a 263 for (i = 0; i < gimple_phi_num_args (phi); i++)
b6e99746 264 {
726a989a 265 basic_block bb = gimple_phi_arg_edge (phi, i)->src;
b6e99746 266
789410e4 267 if (bb == m_switch_bb
18bfe940 268 || (single_pred_p (bb)
789410e4
ML
269 && single_pred (bb) == m_switch_bb
270 && (!m_default_case_nonstandard
18bfe940 271 || empty_block_p (bb))))
b6e99746 272 {
f6e6e990 273 tree reloc, val;
18bfe940 274 const char *reason = NULL;
f6e6e990
JJ
275
276 val = gimple_phi_arg_def (phi, i);
277 if (!is_gimple_ip_invariant (val))
18bfe940
JJ
278 reason = "non-invariant value from a case";
279 else
f6e6e990 280 {
18bfe940
JJ
281 reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
282 if ((flag_pic && reloc != null_pointer_node)
283 || (!flag_pic && reloc == NULL_TREE))
284 {
285 if (reloc)
286 reason
287 = "value from a case would need runtime relocations";
288 else
289 reason
290 = "value from a case is not a valid initializer";
291 }
f6e6e990 292 }
18bfe940 293 if (reason)
f6e6e990 294 {
18bfe940
JJ
295 /* For contiguous range, we can allow non-constant
296 or one that needs relocation, as long as it is
297 only reachable from the default case. */
789410e4
ML
298 if (bb == m_switch_bb)
299 bb = m_final_bb;
300 if (!m_contiguous_range || bb != m_default_bb)
18bfe940 301 {
789410e4 302 m_reason = reason;
18bfe940
JJ
303 return false;
304 }
305
789410e4 306 unsigned int branch_num = gimple_switch_num_labels (m_switch);
18bfe940
JJ
307 for (unsigned int i = 1; i < branch_num; i++)
308 {
789410e4 309 tree lab = CASE_LABEL (gimple_switch_label (m_switch, i));
18bfe940
JJ
310 if (label_to_block (lab) == bb)
311 {
789410e4 312 m_reason = reason;
18bfe940
JJ
313 return false;
314 }
315 }
789410e4 316 m_default_case_nonstandard = true;
f6e6e990 317 }
b6e99746
MJ
318 }
319 }
320 }
321
322 return true;
323}
324
325/* The following function allocates default_values, target_{in,out}_names and
326 constructors arrays. The last one is also populated with pointers to
327 vectors that will become constructors of new arrays. */
328
789410e4
ML
329void
330switch_conversion::create_temp_arrays ()
b6e99746
MJ
331{
332 int i;
333
789410e4 334 m_default_values = XCNEWVEC (tree, m_phi_count * 3);
9771b263
DN
335 /* ??? Macros do not support multi argument templates in their
336 argument list. We create a typedef to work around that problem. */
337 typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
789410e4
ML
338 m_constructors = XCNEWVEC (vec_constructor_elt_gc, m_phi_count);
339 m_target_inbound_names = m_default_values + m_phi_count;
340 m_target_outbound_names = m_target_inbound_names + m_phi_count;
341 for (i = 0; i < m_phi_count; i++)
342 vec_alloc (m_constructors[i], tree_to_uhwi (m_range_size) + 1);
b6e99746
MJ
343}
344
345/* Populate the array of default values in the order of phi nodes.
18bfe940
JJ
346 DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
347 if the range is non-contiguous or the default case has standard
348 structure, otherwise it is the first non-default case instead. */
b6e99746 349
789410e4
ML
350void
351switch_conversion::gather_default_values (tree default_case)
b6e99746 352{
538dd0b7 353 gphi_iterator gsi;
b6e99746
MJ
354 basic_block bb = label_to_block (CASE_LABEL (default_case));
355 edge e;
726a989a 356 int i = 0;
b6e99746 357
18bfe940 358 gcc_assert (CASE_LOW (default_case) == NULL_TREE
789410e4 359 || m_default_case_nonstandard);
b6e99746 360
789410e4
ML
361 if (bb == m_final_bb)
362 e = find_edge (m_switch_bb, bb);
b6e99746
MJ
363 else
364 e = single_succ_edge (bb);
365
789410e4 366 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 367 {
538dd0b7 368 gphi *phi = gsi.phi ();
18bfe940
JJ
369 if (virtual_operand_p (gimple_phi_result (phi)))
370 continue;
b6e99746
MJ
371 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
372 gcc_assert (val);
789410e4 373 m_default_values[i++] = val;
b6e99746
MJ
374 }
375}
376
377/* The following function populates the vectors in the constructors array with
378 future contents of the static arrays. The vectors are populated in the
789410e4 379 order of phi nodes. */
b6e99746 380
789410e4
ML
381void
382switch_conversion::build_constructors ()
b6e99746 383{
789410e4
ML
384 unsigned i, branch_num = gimple_switch_num_labels (m_switch);
385 tree pos = m_range_min;
18bfe940 386 tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
b6e99746 387
726a989a 388 for (i = 1; i < branch_num; i++)
b6e99746 389 {
789410e4 390 tree cs = gimple_switch_label (m_switch, i);
b6e99746
MJ
391 basic_block bb = label_to_block (CASE_LABEL (cs));
392 edge e;
726a989a 393 tree high;
538dd0b7 394 gphi_iterator gsi;
b6e99746
MJ
395 int j;
396
789410e4
ML
397 if (bb == m_final_bb)
398 e = find_edge (m_switch_bb, bb);
b6e99746
MJ
399 else
400 e = single_succ_edge (bb);
401 gcc_assert (e);
402
403 while (tree_int_cst_lt (pos, CASE_LOW (cs)))
404 {
405 int k;
789410e4 406 for (k = 0; k < m_phi_count; k++)
b6e99746 407 {
f32682ca 408 constructor_elt elt;
b6e99746 409
789410e4 410 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
d1f98542 411 elt.value
789410e4
ML
412 = unshare_expr_without_location (m_default_values[k]);
413 m_constructors[k]->quick_push (elt);
b6e99746
MJ
414 }
415
18bfe940 416 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
b6e99746 417 }
b1ae1681 418 gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
b6e99746
MJ
419
420 j = 0;
421 if (CASE_HIGH (cs))
422 high = CASE_HIGH (cs);
423 else
b1ae1681 424 high = CASE_LOW (cs);
789410e4 425 for (gsi = gsi_start_phis (m_final_bb);
726a989a 426 !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 427 {
538dd0b7 428 gphi *phi = gsi.phi ();
18bfe940
JJ
429 if (virtual_operand_p (gimple_phi_result (phi)))
430 continue;
b6e99746 431 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
7f2a9982 432 tree low = CASE_LOW (cs);
b6e99746
MJ
433 pos = CASE_LOW (cs);
434
b8698a0f 435 do
b6e99746 436 {
f32682ca 437 constructor_elt elt;
b6e99746 438
789410e4 439 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
d1f98542 440 elt.value = unshare_expr_without_location (val);
789410e4 441 m_constructors[j]->quick_push (elt);
b6e99746 442
18bfe940 443 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
7156c8ab
MJ
444 } while (!tree_int_cst_lt (high, pos)
445 && tree_int_cst_lt (low, pos));
b6e99746
MJ
446 j++;
447 }
448 }
449}
450
7156c8ab
MJ
451/* If all values in the constructor vector are the same, return the value.
452 Otherwise return NULL_TREE. Not supposed to be called for empty
453 vectors. */
454
789410e4
ML
455tree
456switch_conversion::contains_same_values_p (vec<constructor_elt, va_gc> *vec)
7156c8ab 457{
8e97bc2b 458 unsigned int i;
7156c8ab 459 tree prev = NULL_TREE;
8e97bc2b 460 constructor_elt *elt;
7156c8ab 461
9771b263 462 FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
7156c8ab 463 {
7156c8ab
MJ
464 if (!prev)
465 prev = elt->value;
466 else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
467 return NULL_TREE;
468 }
469 return prev;
470}
471
f1b0632a
OH
472/* Return type which should be used for array elements, either TYPE's
473 main variant or, for integral types, some smaller integral type
474 that can still hold all the constants. */
8e97bc2b 475
789410e4
ML
476tree
477switch_conversion::array_value_type (tree type, int num)
8e97bc2b 478{
789410e4 479 unsigned int i, len = vec_safe_length (m_constructors[num]);
8e97bc2b 480 constructor_elt *elt;
8e97bc2b
JJ
481 int sign = 0;
482 tree smaller_type;
483
f1b0632a
OH
484 /* Types with alignments greater than their size can reach here, e.g. out of
485 SRA. We couldn't use these as an array component type so get back to the
486 main variant first, which, for our purposes, is fine for other types as
487 well. */
488
489 type = TYPE_MAIN_VARIANT (type);
490
8e97bc2b
JJ
491 if (!INTEGRAL_TYPE_P (type))
492 return type;
493
7a504f33 494 scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
095a2d76 495 scalar_int_mode mode = get_narrowest_mode (type_mode);
ec35d572 496 if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
8e97bc2b
JJ
497 return type;
498
789410e4 499 if (len < (optimize_bb_for_size_p (gimple_bb (m_switch)) ? 2 : 32))
8e97bc2b
JJ
500 return type;
501
789410e4 502 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
8e97bc2b 503 {
807e902e 504 wide_int cst;
8e97bc2b
JJ
505
506 if (TREE_CODE (elt->value) != INTEGER_CST)
507 return type;
508
8e6cdc90 509 cst = wi::to_wide (elt->value);
8e97bc2b
JJ
510 while (1)
511 {
512 unsigned int prec = GET_MODE_BITSIZE (mode);
513 if (prec > HOST_BITS_PER_WIDE_INT)
514 return type;
515
807e902e 516 if (sign >= 0 && cst == wi::zext (cst, prec))
8e97bc2b 517 {
807e902e 518 if (sign == 0 && cst == wi::sext (cst, prec))
8e97bc2b
JJ
519 break;
520 sign = 1;
521 break;
522 }
807e902e 523 if (sign <= 0 && cst == wi::sext (cst, prec))
8e97bc2b
JJ
524 {
525 sign = -1;
526 break;
527 }
528
529 if (sign == 1)
530 sign = 0;
531
490d0f6c 532 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
ec35d572 533 || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
8e97bc2b
JJ
534 return type;
535 }
536 }
537
538 if (sign == 0)
539 sign = TYPE_UNSIGNED (type) ? 1 : -1;
540 smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
7a504f33
RS
541 if (GET_MODE_SIZE (type_mode)
542 <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
8e97bc2b
JJ
543 return type;
544
545 return smaller_type;
546}
547
789410e4
ML
548/* Create an appropriate array type and declaration and assemble a static
549 array variable. Also create a load statement that initializes
550 the variable in question with a value from the static array. SWTCH is
551 the switch statement being converted, NUM is the index to
552 arrays of constructors, default values and target SSA names
553 for this particular array. ARR_INDEX_TYPE is the type of the index
554 of the new array, PHI is the phi node of the final BB that corresponds
555 to the value that will be loaded from the created array. TIDX
7156c8ab
MJ
556 is an ssa name of a temporary variable holding the index for loads from the
557 new array. */
b6e99746 558
789410e4
ML
559void
560switch_conversion::build_one_array (int num, tree arr_index_type,
561 gphi *phi, tree tidx)
b6e99746 562{
7156c8ab 563 tree name, cst;
355fe088 564 gimple *load;
789410e4
ML
565 gimple_stmt_iterator gsi = gsi_for_stmt (m_switch);
566 location_t loc = gimple_location (m_switch);
b6e99746 567
789410e4 568 gcc_assert (m_default_values[num]);
b6e99746 569
b731b390 570 name = copy_ssa_name (PHI_RESULT (phi));
789410e4 571 m_target_inbound_names[num] = name;
b6e99746 572
789410e4 573 cst = contains_same_values_p (m_constructors[num]);
7156c8ab
MJ
574 if (cst)
575 load = gimple_build_assign (name, cst);
576 else
577 {
8e97bc2b 578 tree array_type, ctor, decl, value_type, fetch, default_type;
7156c8ab 579
789410e4
ML
580 default_type = TREE_TYPE (m_default_values[num]);
581 value_type = array_value_type (default_type, num);
7156c8ab 582 array_type = build_array_type (value_type, arr_index_type);
8e97bc2b
JJ
583 if (default_type != value_type)
584 {
585 unsigned int i;
586 constructor_elt *elt;
587
789410e4 588 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
8e97bc2b
JJ
589 elt->value = fold_convert (value_type, elt->value);
590 }
789410e4 591 ctor = build_constructor (array_type, m_constructors[num]);
7156c8ab 592 TREE_CONSTANT (ctor) = true;
5f7ae6b6 593 TREE_STATIC (ctor) = true;
7156c8ab 594
c2255bc4 595 decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
7156c8ab
MJ
596 TREE_STATIC (decl) = 1;
597 DECL_INITIAL (decl) = ctor;
598
599 DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
600 DECL_ARTIFICIAL (decl) = 1;
f8d851c6 601 DECL_IGNORED_P (decl) = 1;
7156c8ab 602 TREE_CONSTANT (decl) = 1;
2e3b4885 603 TREE_READONLY (decl) = 1;
d7438551 604 DECL_IGNORED_P (decl) = 1;
46dbeb40
TV
605 if (offloading_function_p (cfun->decl))
606 DECL_ATTRIBUTES (decl)
607 = tree_cons (get_identifier ("omp declare target"), NULL_TREE,
608 NULL_TREE);
9041d2e6 609 varpool_node::finalize_decl (decl);
7156c8ab
MJ
610
611 fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
612 NULL_TREE);
8e97bc2b
JJ
613 if (default_type != value_type)
614 {
615 fetch = fold_convert (default_type, fetch);
616 fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
617 true, GSI_SAME_STMT);
618 }
7156c8ab
MJ
619 load = gimple_build_assign (name, fetch);
620 }
b6e99746 621
726a989a 622 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
7156c8ab 623 update_stmt (load);
789410e4 624 m_arr_ref_last = load;
b6e99746
MJ
625}
626
627/* Builds and initializes static arrays initialized with values gathered from
789410e4 628 the switch statement. Also creates statements that load values from
b6e99746
MJ
629 them. */
630
789410e4
ML
631void
632switch_conversion::build_arrays ()
b6e99746
MJ
633{
634 tree arr_index_type;
83d5977e 635 tree tidx, sub, utype;
355fe088 636 gimple *stmt;
726a989a 637 gimple_stmt_iterator gsi;
538dd0b7 638 gphi_iterator gpi;
b6e99746 639 int i;
789410e4 640 location_t loc = gimple_location (m_switch);
b6e99746 641
789410e4 642 gsi = gsi_for_stmt (m_switch);
04e78aa9 643
edb9b69e 644 /* Make sure we do not generate arithmetics in a subrange. */
789410e4 645 utype = TREE_TYPE (m_index_expr);
edb9b69e
JJ
646 if (TREE_TYPE (utype))
647 utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
648 else
649 utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
650
789410e4 651 arr_index_type = build_index_type (m_range_size);
b731b390 652 tidx = make_ssa_name (utype);
edb9b69e 653 sub = fold_build2_loc (loc, MINUS_EXPR, utype,
789410e4
ML
654 fold_convert_loc (loc, utype, m_index_expr),
655 fold_convert_loc (loc, utype, m_range_min));
fae1034e 656 sub = force_gimple_operand_gsi (&gsi, sub,
726a989a
RB
657 false, NULL, true, GSI_SAME_STMT);
658 stmt = gimple_build_assign (tidx, sub);
b6e99746 659
726a989a 660 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
7156c8ab 661 update_stmt (stmt);
789410e4 662 m_arr_ref_first = stmt;
b6e99746 663
789410e4 664 for (gpi = gsi_start_phis (m_final_bb), i = 0;
18bfe940
JJ
665 !gsi_end_p (gpi); gsi_next (&gpi))
666 {
667 gphi *phi = gpi.phi ();
668 if (!virtual_operand_p (gimple_phi_result (phi)))
789410e4 669 build_one_array (i++, arr_index_type, phi, tidx);
8dc6a926
JJ
670 else
671 {
672 edge e;
673 edge_iterator ei;
789410e4 674 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
8dc6a926 675 {
789410e4 676 if (e->dest == m_final_bb)
8dc6a926 677 break;
789410e4
ML
678 if (!m_default_case_nonstandard
679 || e->dest != m_default_bb)
8dc6a926
JJ
680 {
681 e = single_succ_edge (e->dest);
682 break;
683 }
684 }
789410e4
ML
685 gcc_assert (e && e->dest == m_final_bb);
686 m_target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
8dc6a926 687 }
18bfe940 688 }
b6e99746
MJ
689}
690
691/* Generates and appropriately inserts loads of default values at the position
789410e4 692 given by GSI. Returns the last inserted statement. */
b6e99746 693
789410e4
ML
694gassign *
695switch_conversion::gen_def_assigns (gimple_stmt_iterator *gsi)
b6e99746
MJ
696{
697 int i;
538dd0b7 698 gassign *assign = NULL;
b6e99746 699
789410e4 700 for (i = 0; i < m_phi_count; i++)
b6e99746 701 {
789410e4
ML
702 tree name = copy_ssa_name (m_target_inbound_names[i]);
703 m_target_outbound_names[i] = name;
704 assign = gimple_build_assign (name, m_default_values[i]);
726a989a 705 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
7156c8ab 706 update_stmt (assign);
b6e99746
MJ
707 }
708 return assign;
709}
710
711/* Deletes the unused bbs and edges that now contain the switch statement and
789410e4
ML
712 its empty branch bbs. BBD is the now dead BB containing
713 the original switch statement, FINAL is the last BB of the converted
714 switch statement (in terms of succession). */
b6e99746 715
789410e4
ML
716void
717switch_conversion::prune_bbs (basic_block bbd, basic_block final,
718 basic_block default_bb)
b6e99746
MJ
719{
720 edge_iterator ei;
721 edge e;
722
723 for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
724 {
725 basic_block bb;
726 bb = e->dest;
727 remove_edge (e);
18bfe940 728 if (bb != final && bb != default_bb)
b6e99746
MJ
729 delete_basic_block (bb);
730 }
731 delete_basic_block (bbd);
732}
733
734/* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
735 from the basic block loading values from an array and E2F from the basic
736 block loading default values. BBF is the last switch basic block (see the
737 bbf description in the comment below). */
738
789410e4
ML
739void
740switch_conversion::fix_phi_nodes (edge e1f, edge e2f, basic_block bbf)
b6e99746 741{
538dd0b7 742 gphi_iterator gsi;
b6e99746
MJ
743 int i;
744
726a989a 745 for (gsi = gsi_start_phis (bbf), i = 0;
18bfe940 746 !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 747 {
538dd0b7 748 gphi *phi = gsi.phi ();
18bfe940
JJ
749 tree inbound, outbound;
750 if (virtual_operand_p (gimple_phi_result (phi)))
789410e4 751 inbound = outbound = m_target_vop;
18bfe940
JJ
752 else
753 {
789410e4
ML
754 inbound = m_target_inbound_names[i];
755 outbound = m_target_outbound_names[i++];
18bfe940
JJ
756 }
757 add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
789410e4 758 if (!m_default_case_nonstandard)
18bfe940 759 add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
b6e99746 760 }
b6e99746
MJ
761}
762
763/* Creates a check whether the switch expression value actually falls into the
764 range given by all the cases. If it does not, the temporaries are loaded
789410e4 765 with default values instead. */
b6e99746 766
789410e4
ML
767void
768switch_conversion::gen_inbound_check ()
b6e99746 769{
c2255bc4
AH
770 tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
771 tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
772 tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
538dd0b7 773 glabel *label1, *label2, *label3;
edb9b69e 774 tree utype, tidx;
b6e99746
MJ
775 tree bound;
776
538dd0b7 777 gcond *cond_stmt;
b6e99746 778
18bfe940 779 gassign *last_assign = NULL;
726a989a 780 gimple_stmt_iterator gsi;
b6e99746 781 basic_block bb0, bb1, bb2, bbf, bbd;
18bfe940 782 edge e01 = NULL, e02, e21, e1d, e1f, e2f;
789410e4 783 location_t loc = gimple_location (m_switch);
b6e99746 784
789410e4 785 gcc_assert (m_default_values);
6ab1ab14 786
789410e4 787 bb0 = gimple_bb (m_switch);
b6e99746 788
789410e4 789 tidx = gimple_assign_lhs (m_arr_ref_first);
edb9b69e 790 utype = TREE_TYPE (tidx);
145544ab 791
b6e99746 792 /* (end of) block 0 */
789410e4 793 gsi = gsi_for_stmt (m_arr_ref_first);
edb9b69e 794 gsi_next (&gsi);
b6e99746 795
789410e4 796 bound = fold_convert_loc (loc, utype, m_range_size);
edb9b69e 797 cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
726a989a 798 gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
7156c8ab 799 update_stmt (cond_stmt);
b6e99746
MJ
800
801 /* block 2 */
789410e4 802 if (!m_default_case_nonstandard)
18bfe940
JJ
803 {
804 label2 = gimple_build_label (label_decl2);
805 gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
789410e4 806 last_assign = gen_def_assigns (&gsi);
18bfe940 807 }
b6e99746
MJ
808
809 /* block 1 */
726a989a
RB
810 label1 = gimple_build_label (label_decl1);
811 gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
b6e99746
MJ
812
813 /* block F */
789410e4 814 gsi = gsi_start_bb (m_final_bb);
726a989a
RB
815 label3 = gimple_build_label (label_decl3);
816 gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
b6e99746
MJ
817
818 /* cfg fix */
726a989a 819 e02 = split_block (bb0, cond_stmt);
b6e99746
MJ
820 bb2 = e02->dest;
821
789410e4 822 if (m_default_case_nonstandard)
18bfe940
JJ
823 {
824 bb1 = bb2;
789410e4 825 bb2 = m_default_bb;
18bfe940
JJ
826 e01 = e02;
827 e01->flags = EDGE_TRUE_VALUE;
828 e02 = make_edge (bb0, bb2, EDGE_FALSE_VALUE);
829 edge e_default = find_edge (bb1, bb2);
830 for (gphi_iterator gsi = gsi_start_phis (bb2);
831 !gsi_end_p (gsi); gsi_next (&gsi))
832 {
833 gphi *phi = gsi.phi ();
834 tree arg = PHI_ARG_DEF_FROM_EDGE (phi, e_default);
835 add_phi_arg (phi, arg, e02,
836 gimple_phi_arg_location_from_edge (phi, e_default));
837 }
838 /* Partially fix the dominator tree, if it is available. */
839 if (dom_info_available_p (CDI_DOMINATORS))
840 redirect_immediate_dominators (CDI_DOMINATORS, bb1, bb0);
841 }
842 else
843 {
844 e21 = split_block (bb2, last_assign);
845 bb1 = e21->dest;
846 remove_edge (e21);
847 }
b6e99746 848
789410e4 849 e1d = split_block (bb1, m_arr_ref_last);
b6e99746
MJ
850 bbd = e1d->dest;
851 remove_edge (e1d);
852
789410e4
ML
853 /* Flags and profiles of the edge for in-range values. */
854 if (!m_default_case_nonstandard)
18bfe940 855 e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
789410e4 856 e01->probability = m_default_prob.invert ();
b6e99746 857
789410e4 858 /* Flags and profiles of the edge taking care of out-of-range values. */
b6e99746
MJ
859 e02->flags &= ~EDGE_FALLTHRU;
860 e02->flags |= EDGE_FALSE_VALUE;
789410e4 861 e02->probability = m_default_prob;
b6e99746 862
789410e4 863 bbf = m_final_bb;
b6e99746
MJ
864
865 e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
357067f2 866 e1f->probability = profile_probability::always ();
b6e99746 867
789410e4 868 if (m_default_case_nonstandard)
18bfe940
JJ
869 e2f = NULL;
870 else
871 {
872 e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
357067f2 873 e2f->probability = profile_probability::always ();
18bfe940 874 }
b6e99746
MJ
875
876 /* frequencies of the new BBs */
e7a74006
JH
877 bb1->count = e01->count ();
878 bb2->count = e02->count ();
789410e4 879 if (!m_default_case_nonstandard)
e7a74006 880 bbf->count = e1f->count () + e2f->count ();
b6e99746 881
6ab1ab14 882 /* Tidy blocks that have become unreachable. */
789410e4
ML
883 prune_bbs (bbd, m_final_bb,
884 m_default_case_nonstandard ? m_default_bb : NULL);
b6e99746 885
6ab1ab14 886 /* Fixup the PHI nodes in bbF. */
789410e4 887 fix_phi_nodes (e1f, e2f, bbf);
b6e99746 888
6ab1ab14
SB
889 /* Fix the dominator tree, if it is available. */
890 if (dom_info_available_p (CDI_DOMINATORS))
891 {
9771b263 892 vec<basic_block> bbs_to_fix_dom;
6ab1ab14
SB
893
894 set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
789410e4 895 if (!m_default_case_nonstandard)
18bfe940 896 set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
531b10fc 897 if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
6ab1ab14
SB
898 /* If bbD was the immediate dominator ... */
899 set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
900
18bfe940 901 bbs_to_fix_dom.create (3 + (bb2 != bbf));
9771b263
DN
902 bbs_to_fix_dom.quick_push (bb0);
903 bbs_to_fix_dom.quick_push (bb1);
18bfe940
JJ
904 if (bb2 != bbf)
905 bbs_to_fix_dom.quick_push (bb2);
9771b263 906 bbs_to_fix_dom.quick_push (bbf);
6ab1ab14
SB
907
908 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
9771b263 909 bbs_to_fix_dom.release ();
6ab1ab14 910 }
b6e99746
MJ
911}
912
789410e4
ML
913/* The following function is invoked on every switch statement (the current
914 one is given in SWTCH) and runs the individual phases of switch
915 conversion on it one after another until one fails or the conversion
916 is completed. On success, NULL is in m_reason, otherwise points
917 to a string with the reason why the conversion failed. */
b6e99746 918
789410e4
ML
919void
920switch_conversion::expand (gswitch *swtch)
b6e99746 921{
238065a7
SB
922 /* Group case labels so that we get the right results from the heuristics
923 that decide on the code generation approach for this switch. */
789410e4 924 m_cfg_altered |= group_case_labels_stmt (swtch);
238065a7
SB
925
926 /* If this switch is now a degenerate case with only a default label,
789410e4 927 there is nothing left for us to do. */
238065a7 928 if (gimple_switch_num_labels (swtch) < 2)
789410e4
ML
929 {
930 m_reason = "switch is a degenerate case";
931 return;
932 }
886cd84f 933
789410e4 934 collect (swtch);
886cd84f
SB
935
936 /* No error markers should reach here (they should be filtered out
937 during gimplification). */
789410e4 938 gcc_checking_assert (TREE_TYPE (m_index_expr) != error_mark_node);
886cd84f 939
531b10fc 940 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
789410e4 941 gcc_checking_assert (!TREE_CONSTANT (m_index_expr));
886cd84f 942
dc223ad4
ML
943 /* Prefer bit test if possible. */
944 if (tree_fits_uhwi_p (m_range_size)
945 && bit_test_cluster::can_be_handled (tree_to_uhwi (m_range_size), m_uniq)
946 && bit_test_cluster::is_beneficial (m_count, m_uniq))
947 {
948 m_reason = "expanding as bit test is preferable";
949 return;
950 }
951
952 if (m_uniq <= 2)
953 {
954 /* This will be expanded as a decision tree . */
955 m_reason = "expanding as jumps is preferable";
956 return;
957 }
958
789410e4
ML
959 /* If there is no common successor, we cannot do the transformation. */
960 if (!m_final_bb)
886cd84f 961 {
789410e4
ML
962 m_reason = "no common successor to all case label target blocks found";
963 return;
886cd84f 964 }
b6e99746
MJ
965
966 /* Check the case label values are within reasonable range: */
789410e4 967 if (!check_range ())
fade902a 968 {
789410e4
ML
969 gcc_assert (m_reason);
970 return;
fade902a 971 }
b6e99746
MJ
972
973 /* For all the cases, see whether they are empty, the assignments they
974 represent constant and so on... */
789410e4 975 if (!check_all_empty_except_final ())
8e97bc2b 976 {
789410e4
ML
977 gcc_assert (m_reason);
978 return;
8e97bc2b 979 }
789410e4 980 if (!check_final_bb ())
fade902a 981 {
789410e4
ML
982 gcc_assert (m_reason);
983 return;
fade902a 984 }
b6e99746
MJ
985
986 /* At this point all checks have passed and we can proceed with the
987 transformation. */
988
789410e4
ML
989 create_temp_arrays ();
990 gather_default_values (m_default_case_nonstandard
18bfe940 991 ? gimple_switch_label (swtch, 1)
789410e4
ML
992 : gimple_switch_default_label (swtch));
993 build_constructors ();
b6e99746 994
789410e4
ML
995 build_arrays (); /* Build the static arrays and assignments. */
996 gen_inbound_check (); /* Build the bounds check. */
b6e99746 997
789410e4
ML
998 m_cfg_altered = true;
999}
1000
1001/* Destructor. */
1002
1003switch_conversion::~switch_conversion ()
1004{
1005 XDELETEVEC (m_constructors);
1006 XDELETEVEC (m_default_values);
b6e99746
MJ
1007}
1008
dc223ad4 1009/* Constructor. */
be55bfe6 1010
dc223ad4
ML
1011group_cluster::group_cluster (vec<cluster *> &clusters,
1012 unsigned start, unsigned end)
be55bfe6 1013{
dc223ad4
ML
1014 gcc_checking_assert (end - start + 1 >= 1);
1015 m_prob = profile_probability::never ();
1016 m_cases.create (end - start + 1);
1017 for (unsigned i = start; i <= end; i++)
1018 {
1019 m_cases.quick_push (static_cast<simple_cluster *> (clusters[i]));
1020 m_prob += clusters[i]->m_prob;
1021 }
1022 m_subtree_prob = m_prob;
1023}
be55bfe6 1024
dc223ad4
ML
1025/* Destructor. */
1026
1027group_cluster::~group_cluster ()
be55bfe6 1028{
dc223ad4
ML
1029 for (unsigned i = 0; i < m_cases.length (); i++)
1030 delete m_cases[i];
be55bfe6 1031
dc223ad4
ML
1032 m_cases.release ();
1033}
be55bfe6 1034
dc223ad4 1035/* Dump content of a cluster. */
be55bfe6 1036
dc223ad4
ML
1037void
1038group_cluster::dump (FILE *f, bool details)
b6e99746 1039{
dc223ad4
ML
1040 unsigned total_values = 0;
1041 for (unsigned i = 0; i < m_cases.length (); i++)
1042 total_values += m_cases[i]->get_range (m_cases[i]->get_low (),
1043 m_cases[i]->get_high ());
726a989a 1044
dc223ad4
ML
1045 unsigned comparison_count = 0;
1046 for (unsigned i = 0; i < m_cases.length (); i++)
1047 {
1048 simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1049 comparison_count += sc->m_range_p ? 2 : 1;
1050 }
b6e99746 1051
dc223ad4
ML
1052 unsigned HOST_WIDE_INT range = get_range (get_low (), get_high ());
1053 fprintf (f, "%s", get_type () == JUMP_TABLE ? "JT" : "BT");
531b10fc 1054
dc223ad4
ML
1055 if (details)
1056 fprintf (f, "(values:%d comparisons:%d range:" HOST_WIDE_INT_PRINT_DEC
1057 " density: %.2f%%)", total_values, comparison_count, range,
1058 100.0f * comparison_count / range);
b6e99746 1059
dc223ad4
ML
1060 fprintf (f, ":");
1061 PRINT_CASE (f, get_low ());
1062 fprintf (f, "-");
1063 PRINT_CASE (f, get_high ());
1064 fprintf (f, " ");
b6e99746
MJ
1065}
1066
dc223ad4 1067/* Emit GIMPLE code to handle the cluster. */
27a4cd48 1068
dc223ad4
ML
1069void
1070jump_table_cluster::emit (tree index_expr, tree,
1071 tree default_label_expr, basic_block default_bb)
27a4cd48 1072{
dc223ad4
ML
1073 /* For jump table we just emit a new gswitch statement that will
1074 be latter lowered to jump table. */
1075 auto_vec <tree> labels;
1076 labels.create (m_cases.length ());
1077
1078 make_edge (m_case_bb, default_bb, 0);
1079 for (unsigned i = 0; i < m_cases.length (); i++)
1080 {
1081 labels.quick_push (unshare_expr (m_cases[i]->m_case_label_expr));
1082 make_edge (m_case_bb, m_cases[i]->m_case_bb, 0);
1083 }
1084
1085 gswitch *s = gimple_build_switch (index_expr,
1086 unshare_expr (default_label_expr), labels);
1087 gimple_stmt_iterator gsi = gsi_start_bb (m_case_bb);
1088 gsi_insert_after (&gsi, s, GSI_NEW_STMT);
27a4cd48 1089}
9dc3d6a9 1090
2f928c1b
ML
1091/* Find jump tables of given CLUSTERS, where all members of the vector
1092 are of type simple_cluster. New clusters are returned. */
1093
1094vec<cluster *>
1095jump_table_cluster::find_jump_tables (vec<cluster *> &clusters)
1096{
5885a1bd
ML
1097 if (!is_enabled ())
1098 return clusters.copy ();
1099
2f928c1b
ML
1100 unsigned l = clusters.length ();
1101 auto_vec<min_cluster_item> min;
1102 min.reserve (l + 1);
1103
1104 min.quick_push (min_cluster_item (0, 0, 0));
1105
1106 for (unsigned i = 1; i <= l; i++)
1107 {
1108 /* Set minimal # of clusters with i-th item to infinite. */
1109 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1110
1111 for (unsigned j = 0; j < i; j++)
1112 {
1113 unsigned HOST_WIDE_INT s = min[j].m_non_jt_cases;
1114 if (i - j < case_values_threshold ())
1115 s += i - j;
1116
1117 /* Prefer clusters with smaller number of numbers covered. */
1118 if ((min[j].m_count + 1 < min[i].m_count
1119 || (min[j].m_count + 1 == min[i].m_count
1120 && s < min[i].m_non_jt_cases))
1121 && can_be_handled (clusters, j, i - 1))
1122 min[i] = min_cluster_item (min[j].m_count + 1, j, s);
1123 }
df7c7974
ML
1124
1125 gcc_checking_assert (min[i].m_count != INT_MAX);
2f928c1b
ML
1126 }
1127
1128 /* No result. */
1129 if (min[l].m_count == INT_MAX)
1130 return clusters.copy ();
1131
1132 vec<cluster *> output;
1133 output.create (4);
1134
1135 /* Find and build the clusters. */
1136 for (int end = l;;)
1137 {
1138 int start = min[end].m_start;
1139
1140 /* Do not allow clusters with small number of cases. */
1141 if (is_beneficial (clusters, start, end - 1))
1142 output.safe_push (new jump_table_cluster (clusters, start, end - 1));
1143 else
1144 for (int i = end - 1; i >= start; i--)
1145 output.safe_push (clusters[i]);
1146
1147 end = start;
1148
1149 if (start <= 0)
1150 break;
1151 }
1152
1153 output.reverse ();
1154 return output;
1155}
1156
dc223ad4
ML
1157/* Return true when cluster starting at START and ending at END (inclusive)
1158 can build a jump-table. */
1159
1160bool
1161jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1162 unsigned start, unsigned end)
9dc3d6a9 1163{
dc223ad4
ML
1164 /* If the switch is relatively small such that the cost of one
1165 indirect jump on the target are higher than the cost of a
1166 decision tree, go with the decision tree.
9dc3d6a9 1167
dc223ad4
ML
1168 If range of values is much bigger than number of values,
1169 or if it is too large to represent in a HOST_WIDE_INT,
1170 make a sequence of conditional branches instead of a dispatch.
9dc3d6a9 1171
dc223ad4 1172 The definition of "much bigger" depends on whether we are
de840bde 1173 optimizing for size or for speed. */
dc223ad4
ML
1174 if (!flag_jump_tables)
1175 return false;
9dc3d6a9 1176
df7c7974
ML
1177 /* For algorithm correctness, jump table for a single case must return
1178 true. We bail out in is_beneficial if it's called just for
1179 a single case. */
1180 if (start == end)
1181 return true;
9dc3d6a9 1182
df7c7974 1183 unsigned HOST_WIDE_INT max_ratio = optimize_insn_for_size_p () ? 3 : 8;
dc223ad4
ML
1184 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1185 clusters[end]->get_high ());
1186 /* Check overflow. */
1187 if (range == 0)
1188 return false;
9dc3d6a9 1189
dc223ad4
ML
1190 unsigned HOST_WIDE_INT comparison_count = 0;
1191 for (unsigned i = start; i <= end; i++)
1192 {
1193 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1194 comparison_count += sc->m_range_p ? 2 : 1;
1195 }
9dc3d6a9 1196
dc223ad4 1197 return range <= max_ratio * comparison_count;
9dc3d6a9
ML
1198}
1199
dc223ad4
ML
1200/* Return true if cluster starting at START and ending at END (inclusive)
1201 is profitable transformation. */
9dc3d6a9 1202
dc223ad4
ML
1203bool
1204jump_table_cluster::is_beneficial (const vec<cluster *> &,
1205 unsigned start, unsigned end)
9dc3d6a9 1206{
df7c7974
ML
1207 /* Single case bail out. */
1208 if (start == end)
1209 return false;
1210
dc223ad4 1211 return end - start + 1 >= case_values_threshold ();
9dc3d6a9
ML
1212}
1213
2f928c1b
ML
1214/* Find bit tests of given CLUSTERS, where all members of the vector
1215 are of type simple_cluster. New clusters are returned. */
1216
1217vec<cluster *>
1218bit_test_cluster::find_bit_tests (vec<cluster *> &clusters)
1219{
1220 vec<cluster *> output;
1221 output.create (4);
1222
1223 unsigned l = clusters.length ();
1224 auto_vec<min_cluster_item> min;
1225 min.reserve (l + 1);
1226
1227 min.quick_push (min_cluster_item (0, 0, 0));
1228
1229 for (unsigned i = 1; i <= l; i++)
1230 {
1231 /* Set minimal # of clusters with i-th item to infinite. */
1232 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1233
1234 for (unsigned j = 0; j < i; j++)
1235 {
1236 if (min[j].m_count + 1 < min[i].m_count
1237 && can_be_handled (clusters, j, i - 1))
1238 min[i] = min_cluster_item (min[j].m_count + 1, j, INT_MAX);
1239 }
df7c7974
ML
1240
1241 gcc_checking_assert (min[i].m_count != INT_MAX);
2f928c1b
ML
1242 }
1243
1244 /* No result. */
1245 if (min[l].m_count == INT_MAX)
1246 return clusters.copy ();
1247
1248 /* Find and build the clusters. */
1249 for (int end = l;;)
1250 {
1251 int start = min[end].m_start;
1252
1253 if (is_beneficial (clusters, start, end - 1))
1254 output.safe_push (new bit_test_cluster (clusters, start, end - 1));
1255 else
1256 for (int i = end - 1; i >= start; i--)
1257 output.safe_push (clusters[i]);
1258
1259 end = start;
1260
1261 if (start <= 0)
1262 break;
1263 }
1264
1265 output.reverse ();
1266 return output;
1267}
1268
dc223ad4
ML
1269/* Return true when RANGE of case values with UNIQ labels
1270 can build a bit test. */
9dc3d6a9 1271
dc223ad4
ML
1272bool
1273bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1274 unsigned int uniq)
9dc3d6a9 1275{
dc223ad4
ML
1276 /* Check overflow. */
1277 if (range == 0)
1278 return 0;
1279
1280 if (range >= GET_MODE_BITSIZE (word_mode))
1281 return false;
1282
1283 return uniq <= 3;
1284}
1285
1286/* Return true when cluster starting at START and ending at END (inclusive)
1287 can build a bit test. */
1288
1289bool
1290bit_test_cluster::can_be_handled (const vec<cluster *> &clusters,
1291 unsigned start, unsigned end)
1292{
df7c7974
ML
1293 /* For algorithm correctness, bit test for a single case must return
1294 true. We bail out in is_beneficial if it's called just for
1295 a single case. */
1296 if (start == end)
1297 return true;
1298
dc223ad4
ML
1299 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1300 clusters[end]->get_high ());
1301 auto_bitmap dest_bbs;
1302
1303 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1304 {
dc223ad4
ML
1305 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1306 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1307 }
9dc3d6a9 1308
dc223ad4
ML
1309 return can_be_handled (range, bitmap_count_bits (dest_bbs));
1310}
9dc3d6a9 1311
dc223ad4
ML
1312/* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1313 transformation. */
9dc3d6a9 1314
dc223ad4
ML
1315bool
1316bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
9dc3d6a9 1317{
dc223ad4
ML
1318 return (((uniq == 1 && count >= 3)
1319 || (uniq == 2 && count >= 5)
1320 || (uniq == 3 && count >= 6)));
9dc3d6a9
ML
1321}
1322
dc223ad4
ML
1323/* Return true if cluster starting at START and ending at END (inclusive)
1324 is profitable transformation. */
9dc3d6a9 1325
dc223ad4
ML
1326bool
1327bit_test_cluster::is_beneficial (const vec<cluster *> &clusters,
1328 unsigned start, unsigned end)
9dc3d6a9 1329{
df7c7974
ML
1330 /* Single case bail out. */
1331 if (start == end)
1332 return false;
1333
dc223ad4 1334 auto_bitmap dest_bbs;
9dc3d6a9 1335
dc223ad4 1336 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1337 {
dc223ad4
ML
1338 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1339 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1340 }
9dc3d6a9 1341
dc223ad4
ML
1342 unsigned uniq = bitmap_count_bits (dest_bbs);
1343 unsigned count = end - start + 1;
1344 return is_beneficial (count, uniq);
9dc3d6a9
ML
1345}
1346
dc223ad4
ML
1347/* Comparison function for qsort to order bit tests by decreasing
1348 probability of execution. */
9dc3d6a9 1349
dc223ad4
ML
1350int
1351case_bit_test::cmp (const void *p1, const void *p2)
1352{
1353 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
1354 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
1355
1356 if (d2->bits != d1->bits)
1357 return d2->bits - d1->bits;
1358
1359 /* Stabilize the sort. */
1360 return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1361 - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1362}
1363
1364/* Expand a switch statement by a short sequence of bit-wise
1365 comparisons. "switch(x)" is effectively converted into
1366 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1367 integer constants.
1368
1369 INDEX_EXPR is the value being switched on.
1370
1371 MINVAL is the lowest case value of in the case nodes,
1372 and RANGE is highest value minus MINVAL. MINVAL and RANGE
1373 are not guaranteed to be of the same type as INDEX_EXPR
1374 (the gimplifier doesn't change the type of case label values,
1375 and MINVAL and RANGE are derived from those values).
1376 MAXVAL is MINVAL + RANGE.
9dc3d6a9 1377
dc223ad4
ML
1378 There *MUST* be max_case_bit_tests or less unique case
1379 node targets. */
1380
1381void
1382bit_test_cluster::emit (tree index_expr, tree index_type,
1383 tree, basic_block default_bb)
9dc3d6a9 1384{
dc223ad4
ML
1385 struct case_bit_test test[m_max_case_bit_tests] = { {} };
1386 unsigned int i, j, k;
1387 unsigned int count;
9dc3d6a9 1388
dc223ad4 1389 tree unsigned_index_type = unsigned_type_for (index_type);
9dc3d6a9 1390
dc223ad4
ML
1391 gimple_stmt_iterator gsi;
1392 gassign *shift_stmt;
9dc3d6a9 1393
dc223ad4
ML
1394 tree idx, tmp, csui;
1395 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1396 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1397 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1398 int prec = TYPE_PRECISION (word_type_node);
1399 wide_int wone = wi::one (prec);
9dc3d6a9 1400
dc223ad4
ML
1401 tree minval = get_low ();
1402 tree maxval = get_high ();
1403 tree range = int_const_binop (MINUS_EXPR, maxval, minval);
9dc3d6a9 1404
dc223ad4
ML
1405 /* Go through all case labels, and collect the case labels, profile
1406 counts, and other information we need to build the branch tests. */
1407 count = 0;
1408 for (i = 0; i < m_cases.length (); i++)
1409 {
1410 unsigned int lo, hi;
1411 simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
1412 for (k = 0; k < count; k++)
1413 if (n->m_case_bb == test[k].target_bb)
1414 break;
1415
1416 if (k == count)
9dc3d6a9 1417 {
dc223ad4
ML
1418 gcc_checking_assert (count < m_max_case_bit_tests);
1419 test[k].mask = wi::zero (prec);
1420 test[k].target_bb = n->m_case_bb;
1421 test[k].label = n->m_case_label_expr;
1422 test[k].bits = 1;
1423 count++;
1424 }
1425 else
1426 test[k].bits++;
9dc3d6a9 1427
dc223ad4
ML
1428 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
1429 if (n->get_high () == NULL_TREE)
1430 hi = lo;
1431 else
1432 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
1433 minval));
9dc3d6a9 1434
dc223ad4
ML
1435 for (j = lo; j <= hi; j++)
1436 test[k].mask |= wi::lshift (wone, j);
1437 }
1438
1439 qsort (test, count, sizeof (*test), case_bit_test::cmp);
1440
1441 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
1442 the minval subtractions, but it might make the mask constants more
1443 expensive. So, compare the costs. */
1444 if (compare_tree_int (minval, 0) > 0
1445 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
1446 {
1447 int cost_diff;
1448 HOST_WIDE_INT m = tree_to_uhwi (minval);
1449 rtx reg = gen_raw_REG (word_mode, 10000);
1450 bool speed_p = optimize_insn_for_speed_p ();
1451 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
1452 GEN_INT (-m)), speed_p);
1453 for (i = 0; i < count; i++)
1454 {
1455 rtx r = immed_wide_int_const (test[i].mask, word_mode);
1456 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
1457 word_mode, speed_p);
1458 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
1459 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
1460 word_mode, speed_p);
9dc3d6a9 1461 }
dc223ad4 1462 if (cost_diff > 0)
9dc3d6a9 1463 {
dc223ad4
ML
1464 for (i = 0; i < count; i++)
1465 test[i].mask = wi::lshift (test[i].mask, m);
1466 minval = build_zero_cst (TREE_TYPE (minval));
1467 range = maxval;
9dc3d6a9
ML
1468 }
1469 }
9dc3d6a9 1470
dc223ad4
ML
1471 /* Now build the test-and-branch code. */
1472
1473 gsi = gsi_last_bb (m_case_bb);
1474
1475 /* idx = (unsigned)x - minval. */
1476 idx = fold_convert (unsigned_index_type, index_expr);
1477 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
1478 fold_convert (unsigned_index_type, minval));
1479 idx = force_gimple_operand_gsi (&gsi, idx,
1480 /*simple=*/true, NULL_TREE,
1481 /*before=*/true, GSI_SAME_STMT);
1482
1483 /* if (idx > range) goto default */
1484 range = force_gimple_operand_gsi (&gsi,
1485 fold_convert (unsigned_index_type, range),
1486 /*simple=*/true, NULL_TREE,
1487 /*before=*/true, GSI_SAME_STMT);
1488 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
1489 basic_block new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb);
1490 gsi = gsi_last_bb (new_bb);
1491
1492 /* csui = (1 << (word_mode) idx) */
1493 csui = make_ssa_name (word_type_node);
1494 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
1495 fold_convert (word_type_node, idx));
1496 tmp = force_gimple_operand_gsi (&gsi, tmp,
1497 /*simple=*/false, NULL_TREE,
1498 /*before=*/true, GSI_SAME_STMT);
1499 shift_stmt = gimple_build_assign (csui, tmp);
1500 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
1501 update_stmt (shift_stmt);
1502
1503 /* for each unique set of cases:
1504 if (const & csui) goto target */
1505 for (k = 0; k < count; k++)
1506 {
1507 tmp = wide_int_to_tree (word_type_node, test[k].mask);
1508 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
1509 tmp = force_gimple_operand_gsi (&gsi, tmp,
1510 /*simple=*/true, NULL_TREE,
1511 /*before=*/true, GSI_SAME_STMT);
1512 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
1513 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb);
1514 gsi = gsi_last_bb (new_bb);
1515 }
9dc3d6a9 1516
dc223ad4
ML
1517 /* We should have removed all edges now. */
1518 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
9dc3d6a9 1519
dc223ad4
ML
1520 /* If nothing matched, go to the default label. */
1521 make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
1522}
9dc3d6a9 1523
dc223ad4
ML
1524/* Split the basic block at the statement pointed to by GSIP, and insert
1525 a branch to the target basic block of E_TRUE conditional on tree
1526 expression COND.
9dc3d6a9 1527
dc223ad4
ML
1528 It is assumed that there is already an edge from the to-be-split
1529 basic block to E_TRUE->dest block. This edge is removed, and the
1530 profile information on the edge is re-used for the new conditional
1531 jump.
9dc3d6a9 1532
dc223ad4
ML
1533 The CFG is updated. The dominator tree will not be valid after
1534 this transformation, but the immediate dominators are updated if
1535 UPDATE_DOMINATORS is true.
9dc3d6a9 1536
dc223ad4 1537 Returns the newly created basic block. */
9dc3d6a9 1538
dc223ad4
ML
1539basic_block
1540bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
1541 tree cond, basic_block case_bb)
9dc3d6a9 1542{
dc223ad4
ML
1543 tree tmp;
1544 gcond *cond_stmt;
1545 edge e_false;
1546 basic_block new_bb, split_bb = gsi_bb (*gsip);
9dc3d6a9 1547
dc223ad4
ML
1548 edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
1549 gcc_assert (e_true->src == split_bb);
9dc3d6a9 1550
dc223ad4
ML
1551 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
1552 /*before=*/true, GSI_SAME_STMT);
1553 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
1554 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
9dc3d6a9 1555
dc223ad4
ML
1556 e_false = split_block (split_bb, cond_stmt);
1557 new_bb = e_false->dest;
1558 redirect_edge_pred (e_true, split_bb);
9dc3d6a9 1559
dc223ad4
ML
1560 e_false->flags &= ~EDGE_FALLTHRU;
1561 e_false->flags |= EDGE_FALSE_VALUE;
1562 e_false->probability = e_true->probability.invert ();
1563 new_bb->count = e_false->count ();
1564
1565 return new_bb;
9dc3d6a9
ML
1566}
1567
dc223ad4
ML
1568/* Compute the number of case labels that correspond to each outgoing edge of
1569 switch statement. Record this information in the aux field of the edge. */
9dc3d6a9 1570
dc223ad4
ML
1571void
1572switch_decision_tree::compute_cases_per_edge ()
1573{
1574 basic_block bb = gimple_bb (m_switch);
1575 reset_out_edges_aux ();
1576 int ncases = gimple_switch_num_labels (m_switch);
1577 for (int i = ncases - 1; i >= 1; --i)
1578 {
1579 tree elt = gimple_switch_label (m_switch, i);
1580 tree lab = CASE_LABEL (elt);
1581 basic_block case_bb = label_to_block_fn (cfun, lab);
1582 edge case_edge = find_edge (bb, case_bb);
1583 case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
1584 }
1585}
1586
1587/* Analyze switch statement and return true when the statement is expanded
1588 as decision tree. */
9dc3d6a9 1589
dc223ad4
ML
1590bool
1591switch_decision_tree::analyze_switch_statement ()
9dc3d6a9 1592{
dc223ad4
ML
1593 unsigned l = gimple_switch_num_labels (m_switch);
1594 basic_block bb = gimple_bb (m_switch);
1595 auto_vec<cluster *> clusters;
1596 clusters.create (l - 1);
1597
1598 tree default_label = CASE_LABEL (gimple_switch_default_label (m_switch));
1599 basic_block default_bb = label_to_block_fn (cfun, default_label);
1600 m_case_bbs.reserve (l);
1601 m_case_bbs.quick_push (default_bb);
1602
1603 compute_cases_per_edge ();
1604
1605 for (unsigned i = 1; i < l; i++)
1606 {
1607 tree elt = gimple_switch_label (m_switch, i);
1608 tree lab = CASE_LABEL (elt);
1609 basic_block case_bb = label_to_block_fn (cfun, lab);
1610 edge case_edge = find_edge (bb, case_bb);
1611 tree low = CASE_LOW (elt);
1612 tree high = CASE_HIGH (elt);
1613
1614 profile_probability p
1615 = case_edge->probability.apply_scale (1, (intptr_t) (case_edge->aux));
1616 clusters.quick_push (new simple_cluster (low, high, elt, case_bb, p));
1617 m_case_bbs.quick_push (case_bb);
1618 }
1619
1620 reset_out_edges_aux ();
1621
2f928c1b
ML
1622 /* Find jump table clusters. */
1623 vec<cluster *> output = jump_table_cluster::find_jump_tables (clusters);
1624
df7c7974 1625 /* Find bit test clusters. */
2f928c1b
ML
1626 vec<cluster *> output2;
1627 auto_vec<cluster *> tmp;
1628 output2.create (1);
1629 tmp.create (1);
1630
1631 for (unsigned i = 0; i < output.length (); i++)
1632 {
1633 cluster *c = output[i];
1634 if (c->get_type () != SIMPLE_CASE)
1635 {
1636 if (!tmp.is_empty ())
1637 {
1638 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1639 output2.safe_splice (n);
1640 n.release ();
1641 tmp.truncate (0);
1642 }
1643 output2.safe_push (c);
1644 }
1645 else
1646 tmp.safe_push (c);
1647 }
1648
1649 /* We still can have a temporary vector to test. */
1650 if (!tmp.is_empty ())
1651 {
1652 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1653 output2.safe_splice (n);
1654 n.release ();
1655 }
9dc3d6a9
ML
1656
1657 if (dump_file)
9dc3d6a9 1658 {
dc223ad4 1659 fprintf (dump_file, ";; GIMPLE switch case clusters: ");
2f928c1b
ML
1660 for (unsigned i = 0; i < output2.length (); i++)
1661 output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
dc223ad4
ML
1662 fprintf (dump_file, "\n");
1663 }
1664
2f928c1b 1665 output.release ();
dc223ad4 1666
2f928c1b
ML
1667 bool expanded = try_switch_expansion (output2);
1668
1669 for (unsigned i = 0; i < output2.length (); i++)
1670 delete output2[i];
1671
1672 output2.release ();
dc223ad4
ML
1673
1674 return expanded;
1675}
1676
1677/* Attempt to expand CLUSTERS as a decision tree. Return true when
1678 expanded. */
1679
1680bool
1681switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
1682{
1683 tree index_expr = gimple_switch_index (m_switch);
1684 tree index_type = TREE_TYPE (index_expr);
1685 basic_block bb = gimple_bb (m_switch);
1686
1687 if (gimple_switch_num_labels (m_switch) == 1)
1688 return false;
1689
1690 /* Find the default case target label. */
1691 tree default_label_expr = CASE_LABEL (gimple_switch_default_label (m_switch));
1692 m_default_bb = label_to_block_fn (cfun, default_label_expr);
1693 edge default_edge = find_edge (bb, m_default_bb);
1694
1695 /* Do the insertion of a case label into m_case_list. The labels are
1696 fed to us in descending order from the sorted vector of case labels used
1697 in the tree part of the middle end. So the list we construct is
1698 sorted in ascending order. */
1699
1700 for (int i = clusters.length () - 1; i >= 0; i--)
1701 {
1702 case_tree_node *r = m_case_list;
1703 m_case_list = m_case_node_pool.allocate ();
1704 m_case_list->m_right = r;
1705 m_case_list->m_c = clusters[i];
9dc3d6a9
ML
1706 }
1707
dc223ad4
ML
1708 record_phi_operand_mapping ();
1709
1710 /* Split basic block that contains the gswitch statement. */
9dc3d6a9
ML
1711 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1712 edge e;
1713 if (gsi_end_p (gsi))
1714 e = split_block_after_labels (bb);
1715 else
1716 {
1717 gsi_prev (&gsi);
1718 e = split_block (bb, gsi_stmt (gsi));
1719 }
1720 bb = split_edge (e);
1721
dc223ad4
ML
1722 /* Create new basic blocks for non-case clusters where specific expansion
1723 needs to happen. */
1724 for (unsigned i = 0; i < clusters.length (); i++)
1725 if (clusters[i]->get_type () != SIMPLE_CASE)
1726 {
1727 clusters[i]->m_case_bb = create_empty_bb (bb);
1728 clusters[i]->m_case_bb->loop_father = bb->loop_father;
1729 }
9dc3d6a9 1730
dc223ad4
ML
1731 /* Do not do an extra work for a single cluster. */
1732 if (clusters.length () == 1
1733 && clusters[0]->get_type () != SIMPLE_CASE)
1734 clusters[0]->emit (index_expr, index_type,
1735 gimple_switch_default_label (m_switch), m_default_bb);
1736 else
1737 {
1738 emit (bb, index_expr, default_edge->probability, index_type);
1739
1740 /* Emit cluster-specific switch handling. */
1741 for (unsigned i = 0; i < clusters.length (); i++)
1742 if (clusters[i]->get_type () != SIMPLE_CASE)
1743 clusters[i]->emit (index_expr, index_type,
1744 gimple_switch_default_label (m_switch),
1745 m_default_bb);
1746 }
9dc3d6a9 1747
dc223ad4
ML
1748 fix_phi_operands_for_edges ();
1749
1750 return true;
9dc3d6a9
ML
1751}
1752
dc223ad4
ML
1753/* Before switch transformation, record all SSA_NAMEs defined in switch BB
1754 and used in a label basic block. */
1755
1756void
1757switch_decision_tree::record_phi_operand_mapping ()
9dc3d6a9 1758{
dc223ad4 1759 basic_block switch_bb = gimple_bb (m_switch);
9dc3d6a9 1760 /* Record all PHI nodes that have to be fixed after conversion. */
dc223ad4 1761 for (unsigned i = 0; i < m_case_bbs.length (); i++)
9dc3d6a9 1762 {
9dc3d6a9 1763 gphi_iterator gsi;
dc223ad4 1764 basic_block bb = m_case_bbs[i];
9dc3d6a9
ML
1765 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1766 {
1767 gphi *phi = gsi.phi ();
1768
1769 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
1770 {
1771 basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
1772 if (phi_src_bb == switch_bb)
1773 {
1774 tree def = gimple_phi_arg_def (phi, i);
1775 tree result = gimple_phi_result (phi);
dc223ad4 1776 m_phi_mapping.put (result, def);
9dc3d6a9
ML
1777 break;
1778 }
1779 }
1780 }
1781 }
1782}
1783
dc223ad4
ML
1784/* Append new operands to PHI statements that were introduced due to
1785 addition of new edges to case labels. */
9dc3d6a9 1786
dc223ad4
ML
1787void
1788switch_decision_tree::fix_phi_operands_for_edges ()
9dc3d6a9 1789{
dc223ad4 1790 gphi_iterator gsi;
9dc3d6a9 1791
dc223ad4
ML
1792 for (unsigned i = 0; i < m_case_bbs.length (); i++)
1793 {
1794 basic_block bb = m_case_bbs[i];
1795 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1796 {
1797 gphi *phi = gsi.phi ();
1798 for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
1799 {
1800 tree def = gimple_phi_arg_def (phi, j);
1801 if (def == NULL_TREE)
1802 {
1803 edge e = gimple_phi_arg_edge (phi, j);
1804 tree *definition
1805 = m_phi_mapping.get (gimple_phi_result (phi));
1806 gcc_assert (definition);
1807 add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
1808 }
1809 }
1810 }
1811 }
1812}
9dc3d6a9 1813
dc223ad4
ML
1814/* Generate a decision tree, switching on INDEX_EXPR and jumping to
1815 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
9dc3d6a9 1816
dc223ad4
ML
1817 We generate a binary decision tree to select the appropriate target
1818 code. */
9dc3d6a9 1819
dc223ad4
ML
1820void
1821switch_decision_tree::emit (basic_block bb, tree index_expr,
1822 profile_probability default_prob, tree index_type)
1823{
1824 balance_case_nodes (&m_case_list, NULL);
9dc3d6a9 1825
dc223ad4
ML
1826 if (dump_file)
1827 dump_function_to_file (current_function_decl, dump_file, dump_flags);
1828 if (dump_file && (dump_flags & TDF_DETAILS))
1829 {
1830 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1831 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1832 gcc_assert (m_case_list != NULL);
1833 dump_case_nodes (dump_file, m_case_list, indent_step, 0);
1834 }
9dc3d6a9 1835
dc223ad4 1836 bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type);
9dc3d6a9 1837
dc223ad4
ML
1838 if (bb)
1839 emit_jump (bb, m_default_bb);
9dc3d6a9 1840
dc223ad4
ML
1841 /* Remove all edges and do just an edge that will reach default_bb. */
1842 bb = gimple_bb (m_switch);
1843 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1844 gsi_remove (&gsi, true);
9dc3d6a9 1845
dc223ad4
ML
1846 delete_basic_block (bb);
1847}
1848
1849/* Take an ordered list of case nodes
1850 and transform them into a near optimal binary tree,
1851 on the assumption that any target code selection value is as
1852 likely as any other.
1853
1854 The transformation is performed by splitting the ordered
1855 list into two equal sections plus a pivot. The parts are
1856 then attached to the pivot as left and right branches. Each
1857 branch is then transformed recursively. */
1858
1859void
1860switch_decision_tree::balance_case_nodes (case_tree_node **head,
1861 case_tree_node *parent)
1862{
1863 case_tree_node *np;
1864
1865 np = *head;
1866 if (np)
9dc3d6a9 1867 {
dc223ad4
ML
1868 int i = 0;
1869 int ranges = 0;
1870 case_tree_node **npp;
1871 case_tree_node *left;
9dc3d6a9 1872
dc223ad4 1873 /* Count the number of entries on branch. Also count the ranges. */
9dc3d6a9 1874
dc223ad4
ML
1875 while (np)
1876 {
1877 if (!tree_int_cst_equal (np->m_c->get_low (), np->m_c->get_high ()))
1878 ranges++;
9dc3d6a9 1879
dc223ad4
ML
1880 i++;
1881 np = np->m_right;
1882 }
9dc3d6a9 1883
dc223ad4
ML
1884 if (i > 2)
1885 {
1886 /* Split this list if it is long enough for that to help. */
1887 npp = head;
1888 left = *npp;
9dc3d6a9 1889
dc223ad4
ML
1890 /* If there are just three nodes, split at the middle one. */
1891 if (i == 3)
1892 npp = &(*npp)->m_right;
1893 else
1894 {
1895 /* Find the place in the list that bisects the list's total cost,
1896 where ranges count as 2.
1897 Here I gets half the total cost. */
1898 i = (i + ranges + 1) / 2;
1899 while (1)
1900 {
1901 /* Skip nodes while their cost does not reach that amount. */
1902 if (!tree_int_cst_equal ((*npp)->m_c->get_low (),
1903 (*npp)->m_c->get_high ()))
1904 i--;
1905 i--;
1906 if (i <= 0)
1907 break;
1908 npp = &(*npp)->m_right;
1909 }
1910 }
1911 *head = np = *npp;
1912 *npp = 0;
1913 np->m_parent = parent;
1914 np->m_left = left;
9dc3d6a9 1915
dc223ad4
ML
1916 /* Optimize each of the two split parts. */
1917 balance_case_nodes (&np->m_left, np);
1918 balance_case_nodes (&np->m_right, np);
1919 np->m_c->m_subtree_prob = np->m_c->m_prob;
1920 np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
1921 np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1922 }
1923 else
1924 {
1925 /* Else leave this branch as one level,
1926 but fill in `parent' fields. */
1927 np = *head;
1928 np->m_parent = parent;
1929 np->m_c->m_subtree_prob = np->m_c->m_prob;
1930 for (; np->m_right; np = np->m_right)
1931 {
1932 np->m_right->m_parent = np;
1933 (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1934 }
1935 }
9dc3d6a9 1936 }
dc223ad4
ML
1937}
1938
1939/* Dump ROOT, a list or tree of case nodes, to file. */
9dc3d6a9 1940
dc223ad4
ML
1941void
1942switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
1943 int indent_step, int indent_level)
1944{
1945 if (root == 0)
1946 return;
1947 indent_level++;
1948
1949 dump_case_nodes (f, root->m_left, indent_step, indent_level);
1950
1951 fputs (";; ", f);
1952 fprintf (f, "%*s", indent_step * indent_level, "");
1953 root->m_c->dump (f);
1954 root->m_c->m_prob.dump (f);
1955 fputs ("\n", f);
1956
1957 dump_case_nodes (f, root->m_right, indent_step, indent_level);
1958}
1959
1960
1961/* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1962
1963void
1964switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
1965{
1966 edge e = single_succ_edge (bb);
1967 redirect_edge_succ (e, case_bb);
1968}
1969
1970/* Generate code to compare OP0 with OP1 so that the condition codes are
1971 set and to jump to LABEL_BB if the condition is true.
1972 COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
1973 PROB is the probability of jumping to LABEL_BB. */
1974
1975basic_block
1976switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
1977 tree op1, tree_code comparison,
1978 basic_block label_bb,
1979 profile_probability prob)
1980{
1981 // TODO: it's once called with lhs != index.
1982 op1 = fold_convert (TREE_TYPE (op0), op1);
1983
1984 gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
1985 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1986 gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
1987
1988 gcc_assert (single_succ_p (bb));
1989
1990 /* Make a new basic block where false branch will take place. */
1991 edge false_edge = split_block (bb, cond);
1992 false_edge->flags = EDGE_FALSE_VALUE;
1993 false_edge->probability = prob.invert ();
1994
1995 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
1996 true_edge->probability = prob;
1997
1998 return false_edge->dest;
1999}
2000
2001/* Emit step-by-step code to select a case for the value of INDEX.
2002 The thus generated decision tree follows the form of the
2003 case-node binary tree NODE, whose nodes represent test conditions.
2004 DEFAULT_PROB is probability of cases leading to default BB.
2005 INDEX_TYPE is the type of the index of the switch. */
2006
2007basic_block
2008switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
2009 case_tree_node *node,
2010 profile_probability default_prob,
2011 tree index_type)
2012{
2013 /* If node is null, we are done. */
2014 if (node == NULL)
2015 return bb;
2016
2017 /* Branch to a label where we will handle it later. */
2018 basic_block test_bb = split_edge (single_succ_edge (bb));
2019 redirect_edge_succ (single_pred_edge (test_bb),
2020 single_succ_edge (bb)->dest);
2021
2022 profile_probability probability
2023 = (node->m_right
2024 ? node->m_right->m_c->m_subtree_prob : profile_probability::never ());
2025 probability = ((probability + default_prob.apply_scale (1, 2))
2026 / (node->m_c->m_subtree_prob + default_prob));
2027 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (), GT_EXPR,
2028 test_bb, probability);
2029 default_prob = default_prob.apply_scale (1, 2);
2030
2031 /* Value belongs to this node or to the left-hand subtree. */
2032 probability = node->m_c->m_prob /
2033 (node->m_c->m_subtree_prob + default_prob);
2034 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (), GE_EXPR,
2035 node->m_c->m_case_bb, probability);
2036
2037 /* Handle the left-hand subtree. */
2038 bb = emit_case_nodes (bb, index, node->m_left,
2039 default_prob, index_type);
2040
2041 /* If the left-hand subtree fell through,
2042 don't let it fall into the right-hand subtree. */
2043 if (m_default_bb)
2044 emit_jump (bb, m_default_bb);
2045
2046 bb = emit_case_nodes (test_bb, index, node->m_right,
2047 default_prob, index_type);
2048
2049 return bb;
2050}
2051
2052/* The main function of the pass scans statements for switches and invokes
2053 process_switch on them. */
2054
2055namespace {
2056
2057const pass_data pass_data_convert_switch =
2058{
2059 GIMPLE_PASS, /* type */
2060 "switchconv", /* name */
2061 OPTGROUP_NONE, /* optinfo_flags */
2062 TV_TREE_SWITCH_CONVERSION, /* tv_id */
2063 ( PROP_cfg | PROP_ssa ), /* properties_required */
2064 0, /* properties_provided */
2065 0, /* properties_destroyed */
2066 0, /* todo_flags_start */
2067 TODO_update_ssa, /* todo_flags_finish */
2068};
2069
2070class pass_convert_switch : public gimple_opt_pass
2071{
2072public:
2073 pass_convert_switch (gcc::context *ctxt)
2074 : gimple_opt_pass (pass_data_convert_switch, ctxt)
2075 {}
2076
2077 /* opt_pass methods: */
2078 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
2079 virtual unsigned int execute (function *);
2080
2081}; // class pass_convert_switch
2082
2083unsigned int
2084pass_convert_switch::execute (function *fun)
2085{
2086 basic_block bb;
2087 bool cfg_altered = false;
2088
2089 FOR_EACH_BB_FN (bb, fun)
2090 {
2091 gimple *stmt = last_stmt (bb);
2092 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2093 {
2094 if (dump_file)
2095 {
2096 expanded_location loc = expand_location (gimple_location (stmt));
2097
2098 fprintf (dump_file, "beginning to process the following "
2099 "SWITCH statement (%s:%d) : ------- \n",
2100 loc.file, loc.line);
2101 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2102 putc ('\n', dump_file);
2103 }
2104
2105 switch_conversion sconv;
2106 sconv.expand (as_a <gswitch *> (stmt));
2107 cfg_altered |= sconv.m_cfg_altered;
2108 if (!sconv.m_reason)
2109 {
2110 if (dump_file)
2111 {
2112 fputs ("Switch converted\n", dump_file);
2113 fputs ("--------------------------------\n", dump_file);
2114 }
2115
2116 /* Make no effort to update the post-dominator tree.
2117 It is actually not that hard for the transformations
2118 we have performed, but it is not supported
2119 by iterate_fix_dominators. */
2120 free_dominance_info (CDI_POST_DOMINATORS);
2121 }
2122 else
2123 {
2124 if (dump_file)
2125 {
2126 fputs ("Bailing out - ", dump_file);
2127 fputs (sconv.m_reason, dump_file);
2128 fputs ("\n--------------------------------\n", dump_file);
2129 }
2130 }
2131 }
2132 }
2133
2134 return cfg_altered ? TODO_cleanup_cfg : 0;;
2135}
2136
2137} // anon namespace
2138
2139gimple_opt_pass *
2140make_pass_convert_switch (gcc::context *ctxt)
2141{
2142 return new pass_convert_switch (ctxt);
9dc3d6a9
ML
2143}
2144
2145/* The main function of the pass scans statements for switches and invokes
2146 process_switch on them. */
2147
2148namespace {
2149
eb63c01f 2150template <bool O0> class pass_lower_switch: public gimple_opt_pass
9dc3d6a9 2151{
eb63c01f
ML
2152public:
2153 pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
2154
2155 static const pass_data data;
2156 opt_pass *
2157 clone ()
2158 {
2159 return new pass_lower_switch<O0> (m_ctxt);
2160 }
2161
2162 virtual bool
2163 gate (function *)
2164 {
2165 return !O0 || !optimize;
2166 }
2167
2168 virtual unsigned int execute (function *fun);
2169}; // class pass_lower_switch
2170
2171template <bool O0>
2172const pass_data pass_lower_switch<O0>::data = {
2173 GIMPLE_PASS, /* type */
2174 O0 ? "switchlower_O0" : "switchlower", /* name */
9dc3d6a9
ML
2175 OPTGROUP_NONE, /* optinfo_flags */
2176 TV_TREE_SWITCH_LOWERING, /* tv_id */
2177 ( PROP_cfg | PROP_ssa ), /* properties_required */
2178 0, /* properties_provided */
2179 0, /* properties_destroyed */
2180 0, /* todo_flags_start */
2181 TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
2182};
2183
eb63c01f 2184template <bool O0>
9dc3d6a9 2185unsigned int
eb63c01f 2186pass_lower_switch<O0>::execute (function *fun)
9dc3d6a9
ML
2187{
2188 basic_block bb;
2189 bool expanded = false;
2190
dc223ad4
ML
2191 auto_vec<gimple *> switch_statements;
2192 switch_statements.create (1);
2193
9dc3d6a9
ML
2194 FOR_EACH_BB_FN (bb, fun)
2195 {
2196 gimple *stmt = last_stmt (bb);
2197 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
dc223ad4
ML
2198 switch_statements.safe_push (stmt);
2199 }
2200
2201 for (unsigned i = 0; i < switch_statements.length (); i++)
2202 {
2203 gimple *stmt = switch_statements[i];
2204 if (dump_file)
9dc3d6a9 2205 {
dc223ad4 2206 expanded_location loc = expand_location (gimple_location (stmt));
9dc3d6a9 2207
dc223ad4
ML
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);
2213 }
9dc3d6a9 2214
dc223ad4
ML
2215 gswitch *swtch = dyn_cast<gswitch *> (stmt);
2216 if (swtch)
2217 {
2218 switch_decision_tree dt (swtch);
2219 expanded |= dt.analyze_switch_statement ();
9dc3d6a9
ML
2220 }
2221 }
2222
2223 if (expanded)
2224 {
2225 free_dominance_info (CDI_DOMINATORS);
2226 free_dominance_info (CDI_POST_DOMINATORS);
2227 mark_virtual_operands_for_renaming (cfun);
2228 }
2229
2230 return 0;
2231}
2232
2233} // anon namespace
2234
2235gimple_opt_pass *
eb63c01f 2236make_pass_lower_switch_O0 (gcc::context *ctxt)
9dc3d6a9 2237{
eb63c01f 2238 return new pass_lower_switch<true> (ctxt);
9dc3d6a9 2239}
eb63c01f
ML
2240gimple_opt_pass *
2241make_pass_lower_switch (gcc::context *ctxt)
9dc3d6a9 2242{
eb63c01f 2243 return new pass_lower_switch<false> (ctxt);
9dc3d6a9
ML
2244}
2245
9dc3d6a9 2246