]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-switch-conversion.c
Come up with new --completion option.
[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 }
1124 }
1125
1126 /* No result. */
1127 if (min[l].m_count == INT_MAX)
1128 return clusters.copy ();
1129
1130 vec<cluster *> output;
1131 output.create (4);
1132
1133 /* Find and build the clusters. */
1134 for (int end = l;;)
1135 {
1136 int start = min[end].m_start;
1137
1138 /* Do not allow clusters with small number of cases. */
1139 if (is_beneficial (clusters, start, end - 1))
1140 output.safe_push (new jump_table_cluster (clusters, start, end - 1));
1141 else
1142 for (int i = end - 1; i >= start; i--)
1143 output.safe_push (clusters[i]);
1144
1145 end = start;
1146
1147 if (start <= 0)
1148 break;
1149 }
1150
1151 output.reverse ();
1152 return output;
1153}
1154
dc223ad4
ML
1155/* Return true when cluster starting at START and ending at END (inclusive)
1156 can build a jump-table. */
1157
1158bool
1159jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1160 unsigned start, unsigned end)
9dc3d6a9 1161{
dc223ad4
ML
1162 /* If the switch is relatively small such that the cost of one
1163 indirect jump on the target are higher than the cost of a
1164 decision tree, go with the decision tree.
9dc3d6a9 1165
dc223ad4
ML
1166 If range of values is much bigger than number of values,
1167 or if it is too large to represent in a HOST_WIDE_INT,
1168 make a sequence of conditional branches instead of a dispatch.
9dc3d6a9 1169
dc223ad4 1170 The definition of "much bigger" depends on whether we are
de840bde 1171 optimizing for size or for speed. */
dc223ad4
ML
1172 if (!flag_jump_tables)
1173 return false;
9dc3d6a9 1174
de840bde 1175 unsigned HOST_WIDE_INT max_ratio = optimize_insn_for_size_p () ? 3 : 8;
9dc3d6a9 1176
dc223ad4
ML
1177 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1178 clusters[end]->get_high ());
1179 /* Check overflow. */
1180 if (range == 0)
1181 return false;
9dc3d6a9 1182
dc223ad4
ML
1183 unsigned HOST_WIDE_INT comparison_count = 0;
1184 for (unsigned i = start; i <= end; i++)
1185 {
1186 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1187 comparison_count += sc->m_range_p ? 2 : 1;
1188 }
9dc3d6a9 1189
dc223ad4 1190 return range <= max_ratio * comparison_count;
9dc3d6a9
ML
1191}
1192
dc223ad4
ML
1193/* Return true if cluster starting at START and ending at END (inclusive)
1194 is profitable transformation. */
9dc3d6a9 1195
dc223ad4
ML
1196bool
1197jump_table_cluster::is_beneficial (const vec<cluster *> &,
1198 unsigned start, unsigned end)
9dc3d6a9 1199{
dc223ad4 1200 return end - start + 1 >= case_values_threshold ();
9dc3d6a9
ML
1201}
1202
2f928c1b
ML
1203/* Find bit tests of given CLUSTERS, where all members of the vector
1204 are of type simple_cluster. New clusters are returned. */
1205
1206vec<cluster *>
1207bit_test_cluster::find_bit_tests (vec<cluster *> &clusters)
1208{
1209 vec<cluster *> output;
1210 output.create (4);
1211
1212 unsigned l = clusters.length ();
1213 auto_vec<min_cluster_item> min;
1214 min.reserve (l + 1);
1215
1216 min.quick_push (min_cluster_item (0, 0, 0));
1217
1218 for (unsigned i = 1; i <= l; i++)
1219 {
1220 /* Set minimal # of clusters with i-th item to infinite. */
1221 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1222
1223 for (unsigned j = 0; j < i; j++)
1224 {
1225 if (min[j].m_count + 1 < min[i].m_count
1226 && can_be_handled (clusters, j, i - 1))
1227 min[i] = min_cluster_item (min[j].m_count + 1, j, INT_MAX);
1228 }
1229 }
1230
1231 /* No result. */
1232 if (min[l].m_count == INT_MAX)
1233 return clusters.copy ();
1234
1235 /* Find and build the clusters. */
1236 for (int end = l;;)
1237 {
1238 int start = min[end].m_start;
1239
1240 if (is_beneficial (clusters, start, end - 1))
1241 output.safe_push (new bit_test_cluster (clusters, start, end - 1));
1242 else
1243 for (int i = end - 1; i >= start; i--)
1244 output.safe_push (clusters[i]);
1245
1246 end = start;
1247
1248 if (start <= 0)
1249 break;
1250 }
1251
1252 output.reverse ();
1253 return output;
1254}
1255
dc223ad4
ML
1256/* Return true when RANGE of case values with UNIQ labels
1257 can build a bit test. */
9dc3d6a9 1258
dc223ad4
ML
1259bool
1260bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1261 unsigned int uniq)
9dc3d6a9 1262{
dc223ad4
ML
1263 /* Check overflow. */
1264 if (range == 0)
1265 return 0;
1266
1267 if (range >= GET_MODE_BITSIZE (word_mode))
1268 return false;
1269
1270 return uniq <= 3;
1271}
1272
1273/* Return true when cluster starting at START and ending at END (inclusive)
1274 can build a bit test. */
1275
1276bool
1277bit_test_cluster::can_be_handled (const vec<cluster *> &clusters,
1278 unsigned start, unsigned end)
1279{
1280 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1281 clusters[end]->get_high ());
1282 auto_bitmap dest_bbs;
1283
1284 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1285 {
dc223ad4
ML
1286 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1287 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1288 }
9dc3d6a9 1289
dc223ad4
ML
1290 return can_be_handled (range, bitmap_count_bits (dest_bbs));
1291}
9dc3d6a9 1292
dc223ad4
ML
1293/* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1294 transformation. */
9dc3d6a9 1295
dc223ad4
ML
1296bool
1297bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
9dc3d6a9 1298{
dc223ad4
ML
1299 return (((uniq == 1 && count >= 3)
1300 || (uniq == 2 && count >= 5)
1301 || (uniq == 3 && count >= 6)));
9dc3d6a9
ML
1302}
1303
dc223ad4
ML
1304/* Return true if cluster starting at START and ending at END (inclusive)
1305 is profitable transformation. */
9dc3d6a9 1306
dc223ad4
ML
1307bool
1308bit_test_cluster::is_beneficial (const vec<cluster *> &clusters,
1309 unsigned start, unsigned end)
9dc3d6a9 1310{
dc223ad4 1311 auto_bitmap dest_bbs;
9dc3d6a9 1312
dc223ad4 1313 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1314 {
dc223ad4
ML
1315 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1316 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1317 }
9dc3d6a9 1318
dc223ad4
ML
1319 unsigned uniq = bitmap_count_bits (dest_bbs);
1320 unsigned count = end - start + 1;
1321 return is_beneficial (count, uniq);
9dc3d6a9
ML
1322}
1323
dc223ad4
ML
1324/* Comparison function for qsort to order bit tests by decreasing
1325 probability of execution. */
9dc3d6a9 1326
dc223ad4
ML
1327int
1328case_bit_test::cmp (const void *p1, const void *p2)
1329{
1330 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
1331 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
1332
1333 if (d2->bits != d1->bits)
1334 return d2->bits - d1->bits;
1335
1336 /* Stabilize the sort. */
1337 return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1338 - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1339}
1340
1341/* Expand a switch statement by a short sequence of bit-wise
1342 comparisons. "switch(x)" is effectively converted into
1343 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1344 integer constants.
1345
1346 INDEX_EXPR is the value being switched on.
1347
1348 MINVAL is the lowest case value of in the case nodes,
1349 and RANGE is highest value minus MINVAL. MINVAL and RANGE
1350 are not guaranteed to be of the same type as INDEX_EXPR
1351 (the gimplifier doesn't change the type of case label values,
1352 and MINVAL and RANGE are derived from those values).
1353 MAXVAL is MINVAL + RANGE.
9dc3d6a9 1354
dc223ad4
ML
1355 There *MUST* be max_case_bit_tests or less unique case
1356 node targets. */
1357
1358void
1359bit_test_cluster::emit (tree index_expr, tree index_type,
1360 tree, basic_block default_bb)
9dc3d6a9 1361{
dc223ad4
ML
1362 struct case_bit_test test[m_max_case_bit_tests] = { {} };
1363 unsigned int i, j, k;
1364 unsigned int count;
9dc3d6a9 1365
dc223ad4 1366 tree unsigned_index_type = unsigned_type_for (index_type);
9dc3d6a9 1367
dc223ad4
ML
1368 gimple_stmt_iterator gsi;
1369 gassign *shift_stmt;
9dc3d6a9 1370
dc223ad4
ML
1371 tree idx, tmp, csui;
1372 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1373 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1374 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1375 int prec = TYPE_PRECISION (word_type_node);
1376 wide_int wone = wi::one (prec);
9dc3d6a9 1377
dc223ad4
ML
1378 tree minval = get_low ();
1379 tree maxval = get_high ();
1380 tree range = int_const_binop (MINUS_EXPR, maxval, minval);
9dc3d6a9 1381
dc223ad4
ML
1382 /* Go through all case labels, and collect the case labels, profile
1383 counts, and other information we need to build the branch tests. */
1384 count = 0;
1385 for (i = 0; i < m_cases.length (); i++)
1386 {
1387 unsigned int lo, hi;
1388 simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
1389 for (k = 0; k < count; k++)
1390 if (n->m_case_bb == test[k].target_bb)
1391 break;
1392
1393 if (k == count)
9dc3d6a9 1394 {
dc223ad4
ML
1395 gcc_checking_assert (count < m_max_case_bit_tests);
1396 test[k].mask = wi::zero (prec);
1397 test[k].target_bb = n->m_case_bb;
1398 test[k].label = n->m_case_label_expr;
1399 test[k].bits = 1;
1400 count++;
1401 }
1402 else
1403 test[k].bits++;
9dc3d6a9 1404
dc223ad4
ML
1405 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
1406 if (n->get_high () == NULL_TREE)
1407 hi = lo;
1408 else
1409 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
1410 minval));
9dc3d6a9 1411
dc223ad4
ML
1412 for (j = lo; j <= hi; j++)
1413 test[k].mask |= wi::lshift (wone, j);
1414 }
1415
1416 qsort (test, count, sizeof (*test), case_bit_test::cmp);
1417
1418 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
1419 the minval subtractions, but it might make the mask constants more
1420 expensive. So, compare the costs. */
1421 if (compare_tree_int (minval, 0) > 0
1422 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
1423 {
1424 int cost_diff;
1425 HOST_WIDE_INT m = tree_to_uhwi (minval);
1426 rtx reg = gen_raw_REG (word_mode, 10000);
1427 bool speed_p = optimize_insn_for_speed_p ();
1428 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
1429 GEN_INT (-m)), speed_p);
1430 for (i = 0; i < count; i++)
1431 {
1432 rtx r = immed_wide_int_const (test[i].mask, word_mode);
1433 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
1434 word_mode, speed_p);
1435 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
1436 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
1437 word_mode, speed_p);
9dc3d6a9 1438 }
dc223ad4 1439 if (cost_diff > 0)
9dc3d6a9 1440 {
dc223ad4
ML
1441 for (i = 0; i < count; i++)
1442 test[i].mask = wi::lshift (test[i].mask, m);
1443 minval = build_zero_cst (TREE_TYPE (minval));
1444 range = maxval;
9dc3d6a9
ML
1445 }
1446 }
9dc3d6a9 1447
dc223ad4
ML
1448 /* Now build the test-and-branch code. */
1449
1450 gsi = gsi_last_bb (m_case_bb);
1451
1452 /* idx = (unsigned)x - minval. */
1453 idx = fold_convert (unsigned_index_type, index_expr);
1454 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
1455 fold_convert (unsigned_index_type, minval));
1456 idx = force_gimple_operand_gsi (&gsi, idx,
1457 /*simple=*/true, NULL_TREE,
1458 /*before=*/true, GSI_SAME_STMT);
1459
1460 /* if (idx > range) goto default */
1461 range = force_gimple_operand_gsi (&gsi,
1462 fold_convert (unsigned_index_type, range),
1463 /*simple=*/true, NULL_TREE,
1464 /*before=*/true, GSI_SAME_STMT);
1465 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
1466 basic_block new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb);
1467 gsi = gsi_last_bb (new_bb);
1468
1469 /* csui = (1 << (word_mode) idx) */
1470 csui = make_ssa_name (word_type_node);
1471 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
1472 fold_convert (word_type_node, idx));
1473 tmp = force_gimple_operand_gsi (&gsi, tmp,
1474 /*simple=*/false, NULL_TREE,
1475 /*before=*/true, GSI_SAME_STMT);
1476 shift_stmt = gimple_build_assign (csui, tmp);
1477 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
1478 update_stmt (shift_stmt);
1479
1480 /* for each unique set of cases:
1481 if (const & csui) goto target */
1482 for (k = 0; k < count; k++)
1483 {
1484 tmp = wide_int_to_tree (word_type_node, test[k].mask);
1485 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
1486 tmp = force_gimple_operand_gsi (&gsi, tmp,
1487 /*simple=*/true, NULL_TREE,
1488 /*before=*/true, GSI_SAME_STMT);
1489 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
1490 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb);
1491 gsi = gsi_last_bb (new_bb);
1492 }
9dc3d6a9 1493
dc223ad4
ML
1494 /* We should have removed all edges now. */
1495 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
9dc3d6a9 1496
dc223ad4
ML
1497 /* If nothing matched, go to the default label. */
1498 make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
1499}
9dc3d6a9 1500
dc223ad4
ML
1501/* Split the basic block at the statement pointed to by GSIP, and insert
1502 a branch to the target basic block of E_TRUE conditional on tree
1503 expression COND.
9dc3d6a9 1504
dc223ad4
ML
1505 It is assumed that there is already an edge from the to-be-split
1506 basic block to E_TRUE->dest block. This edge is removed, and the
1507 profile information on the edge is re-used for the new conditional
1508 jump.
9dc3d6a9 1509
dc223ad4
ML
1510 The CFG is updated. The dominator tree will not be valid after
1511 this transformation, but the immediate dominators are updated if
1512 UPDATE_DOMINATORS is true.
9dc3d6a9 1513
dc223ad4 1514 Returns the newly created basic block. */
9dc3d6a9 1515
dc223ad4
ML
1516basic_block
1517bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
1518 tree cond, basic_block case_bb)
9dc3d6a9 1519{
dc223ad4
ML
1520 tree tmp;
1521 gcond *cond_stmt;
1522 edge e_false;
1523 basic_block new_bb, split_bb = gsi_bb (*gsip);
9dc3d6a9 1524
dc223ad4
ML
1525 edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
1526 gcc_assert (e_true->src == split_bb);
9dc3d6a9 1527
dc223ad4
ML
1528 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
1529 /*before=*/true, GSI_SAME_STMT);
1530 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
1531 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
9dc3d6a9 1532
dc223ad4
ML
1533 e_false = split_block (split_bb, cond_stmt);
1534 new_bb = e_false->dest;
1535 redirect_edge_pred (e_true, split_bb);
9dc3d6a9 1536
dc223ad4
ML
1537 e_false->flags &= ~EDGE_FALLTHRU;
1538 e_false->flags |= EDGE_FALSE_VALUE;
1539 e_false->probability = e_true->probability.invert ();
1540 new_bb->count = e_false->count ();
1541
1542 return new_bb;
9dc3d6a9
ML
1543}
1544
dc223ad4
ML
1545/* Compute the number of case labels that correspond to each outgoing edge of
1546 switch statement. Record this information in the aux field of the edge. */
9dc3d6a9 1547
dc223ad4
ML
1548void
1549switch_decision_tree::compute_cases_per_edge ()
1550{
1551 basic_block bb = gimple_bb (m_switch);
1552 reset_out_edges_aux ();
1553 int ncases = gimple_switch_num_labels (m_switch);
1554 for (int i = ncases - 1; i >= 1; --i)
1555 {
1556 tree elt = gimple_switch_label (m_switch, i);
1557 tree lab = CASE_LABEL (elt);
1558 basic_block case_bb = label_to_block_fn (cfun, lab);
1559 edge case_edge = find_edge (bb, case_bb);
1560 case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
1561 }
1562}
1563
1564/* Analyze switch statement and return true when the statement is expanded
1565 as decision tree. */
9dc3d6a9 1566
dc223ad4
ML
1567bool
1568switch_decision_tree::analyze_switch_statement ()
9dc3d6a9 1569{
dc223ad4
ML
1570 unsigned l = gimple_switch_num_labels (m_switch);
1571 basic_block bb = gimple_bb (m_switch);
1572 auto_vec<cluster *> clusters;
1573 clusters.create (l - 1);
1574
1575 tree default_label = CASE_LABEL (gimple_switch_default_label (m_switch));
1576 basic_block default_bb = label_to_block_fn (cfun, default_label);
1577 m_case_bbs.reserve (l);
1578 m_case_bbs.quick_push (default_bb);
1579
1580 compute_cases_per_edge ();
1581
1582 for (unsigned i = 1; i < l; i++)
1583 {
1584 tree elt = gimple_switch_label (m_switch, i);
1585 tree lab = CASE_LABEL (elt);
1586 basic_block case_bb = label_to_block_fn (cfun, lab);
1587 edge case_edge = find_edge (bb, case_bb);
1588 tree low = CASE_LOW (elt);
1589 tree high = CASE_HIGH (elt);
1590
1591 profile_probability p
1592 = case_edge->probability.apply_scale (1, (intptr_t) (case_edge->aux));
1593 clusters.quick_push (new simple_cluster (low, high, elt, case_bb, p));
1594 m_case_bbs.quick_push (case_bb);
1595 }
1596
1597 reset_out_edges_aux ();
1598
2f928c1b
ML
1599 /* Find jump table clusters. */
1600 vec<cluster *> output = jump_table_cluster::find_jump_tables (clusters);
1601
1602 /* Find jump table clusters. */
1603 vec<cluster *> output2;
1604 auto_vec<cluster *> tmp;
1605 output2.create (1);
1606 tmp.create (1);
1607
1608 for (unsigned i = 0; i < output.length (); i++)
1609 {
1610 cluster *c = output[i];
1611 if (c->get_type () != SIMPLE_CASE)
1612 {
1613 if (!tmp.is_empty ())
1614 {
1615 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1616 output2.safe_splice (n);
1617 n.release ();
1618 tmp.truncate (0);
1619 }
1620 output2.safe_push (c);
1621 }
1622 else
1623 tmp.safe_push (c);
1624 }
1625
1626 /* We still can have a temporary vector to test. */
1627 if (!tmp.is_empty ())
1628 {
1629 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1630 output2.safe_splice (n);
1631 n.release ();
1632 }
9dc3d6a9
ML
1633
1634 if (dump_file)
9dc3d6a9 1635 {
dc223ad4 1636 fprintf (dump_file, ";; GIMPLE switch case clusters: ");
2f928c1b
ML
1637 for (unsigned i = 0; i < output2.length (); i++)
1638 output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
dc223ad4
ML
1639 fprintf (dump_file, "\n");
1640 }
1641
2f928c1b 1642 output.release ();
dc223ad4 1643
2f928c1b
ML
1644 bool expanded = try_switch_expansion (output2);
1645
1646 for (unsigned i = 0; i < output2.length (); i++)
1647 delete output2[i];
1648
1649 output2.release ();
dc223ad4
ML
1650
1651 return expanded;
1652}
1653
1654/* Attempt to expand CLUSTERS as a decision tree. Return true when
1655 expanded. */
1656
1657bool
1658switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
1659{
1660 tree index_expr = gimple_switch_index (m_switch);
1661 tree index_type = TREE_TYPE (index_expr);
1662 basic_block bb = gimple_bb (m_switch);
1663
1664 if (gimple_switch_num_labels (m_switch) == 1)
1665 return false;
1666
1667 /* Find the default case target label. */
1668 tree default_label_expr = CASE_LABEL (gimple_switch_default_label (m_switch));
1669 m_default_bb = label_to_block_fn (cfun, default_label_expr);
1670 edge default_edge = find_edge (bb, m_default_bb);
1671
1672 /* Do the insertion of a case label into m_case_list. The labels are
1673 fed to us in descending order from the sorted vector of case labels used
1674 in the tree part of the middle end. So the list we construct is
1675 sorted in ascending order. */
1676
1677 for (int i = clusters.length () - 1; i >= 0; i--)
1678 {
1679 case_tree_node *r = m_case_list;
1680 m_case_list = m_case_node_pool.allocate ();
1681 m_case_list->m_right = r;
1682 m_case_list->m_c = clusters[i];
9dc3d6a9
ML
1683 }
1684
dc223ad4
ML
1685 record_phi_operand_mapping ();
1686
1687 /* Split basic block that contains the gswitch statement. */
9dc3d6a9
ML
1688 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1689 edge e;
1690 if (gsi_end_p (gsi))
1691 e = split_block_after_labels (bb);
1692 else
1693 {
1694 gsi_prev (&gsi);
1695 e = split_block (bb, gsi_stmt (gsi));
1696 }
1697 bb = split_edge (e);
1698
dc223ad4
ML
1699 /* Create new basic blocks for non-case clusters where specific expansion
1700 needs to happen. */
1701 for (unsigned i = 0; i < clusters.length (); i++)
1702 if (clusters[i]->get_type () != SIMPLE_CASE)
1703 {
1704 clusters[i]->m_case_bb = create_empty_bb (bb);
1705 clusters[i]->m_case_bb->loop_father = bb->loop_father;
1706 }
9dc3d6a9 1707
dc223ad4
ML
1708 /* Do not do an extra work for a single cluster. */
1709 if (clusters.length () == 1
1710 && clusters[0]->get_type () != SIMPLE_CASE)
1711 clusters[0]->emit (index_expr, index_type,
1712 gimple_switch_default_label (m_switch), m_default_bb);
1713 else
1714 {
1715 emit (bb, index_expr, default_edge->probability, index_type);
1716
1717 /* Emit cluster-specific switch handling. */
1718 for (unsigned i = 0; i < clusters.length (); i++)
1719 if (clusters[i]->get_type () != SIMPLE_CASE)
1720 clusters[i]->emit (index_expr, index_type,
1721 gimple_switch_default_label (m_switch),
1722 m_default_bb);
1723 }
9dc3d6a9 1724
dc223ad4
ML
1725 fix_phi_operands_for_edges ();
1726
1727 return true;
9dc3d6a9
ML
1728}
1729
dc223ad4
ML
1730/* Before switch transformation, record all SSA_NAMEs defined in switch BB
1731 and used in a label basic block. */
1732
1733void
1734switch_decision_tree::record_phi_operand_mapping ()
9dc3d6a9 1735{
dc223ad4 1736 basic_block switch_bb = gimple_bb (m_switch);
9dc3d6a9 1737 /* Record all PHI nodes that have to be fixed after conversion. */
dc223ad4 1738 for (unsigned i = 0; i < m_case_bbs.length (); i++)
9dc3d6a9 1739 {
9dc3d6a9 1740 gphi_iterator gsi;
dc223ad4 1741 basic_block bb = m_case_bbs[i];
9dc3d6a9
ML
1742 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1743 {
1744 gphi *phi = gsi.phi ();
1745
1746 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
1747 {
1748 basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
1749 if (phi_src_bb == switch_bb)
1750 {
1751 tree def = gimple_phi_arg_def (phi, i);
1752 tree result = gimple_phi_result (phi);
dc223ad4 1753 m_phi_mapping.put (result, def);
9dc3d6a9
ML
1754 break;
1755 }
1756 }
1757 }
1758 }
1759}
1760
dc223ad4
ML
1761/* Append new operands to PHI statements that were introduced due to
1762 addition of new edges to case labels. */
9dc3d6a9 1763
dc223ad4
ML
1764void
1765switch_decision_tree::fix_phi_operands_for_edges ()
9dc3d6a9 1766{
dc223ad4 1767 gphi_iterator gsi;
9dc3d6a9 1768
dc223ad4
ML
1769 for (unsigned i = 0; i < m_case_bbs.length (); i++)
1770 {
1771 basic_block bb = m_case_bbs[i];
1772 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1773 {
1774 gphi *phi = gsi.phi ();
1775 for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
1776 {
1777 tree def = gimple_phi_arg_def (phi, j);
1778 if (def == NULL_TREE)
1779 {
1780 edge e = gimple_phi_arg_edge (phi, j);
1781 tree *definition
1782 = m_phi_mapping.get (gimple_phi_result (phi));
1783 gcc_assert (definition);
1784 add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
1785 }
1786 }
1787 }
1788 }
1789}
9dc3d6a9 1790
dc223ad4
ML
1791/* Generate a decision tree, switching on INDEX_EXPR and jumping to
1792 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
9dc3d6a9 1793
dc223ad4
ML
1794 We generate a binary decision tree to select the appropriate target
1795 code. */
9dc3d6a9 1796
dc223ad4
ML
1797void
1798switch_decision_tree::emit (basic_block bb, tree index_expr,
1799 profile_probability default_prob, tree index_type)
1800{
1801 balance_case_nodes (&m_case_list, NULL);
9dc3d6a9 1802
dc223ad4
ML
1803 if (dump_file)
1804 dump_function_to_file (current_function_decl, dump_file, dump_flags);
1805 if (dump_file && (dump_flags & TDF_DETAILS))
1806 {
1807 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1808 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1809 gcc_assert (m_case_list != NULL);
1810 dump_case_nodes (dump_file, m_case_list, indent_step, 0);
1811 }
9dc3d6a9 1812
dc223ad4 1813 bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type);
9dc3d6a9 1814
dc223ad4
ML
1815 if (bb)
1816 emit_jump (bb, m_default_bb);
9dc3d6a9 1817
dc223ad4
ML
1818 /* Remove all edges and do just an edge that will reach default_bb. */
1819 bb = gimple_bb (m_switch);
1820 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1821 gsi_remove (&gsi, true);
9dc3d6a9 1822
dc223ad4
ML
1823 delete_basic_block (bb);
1824}
1825
1826/* Take an ordered list of case nodes
1827 and transform them into a near optimal binary tree,
1828 on the assumption that any target code selection value is as
1829 likely as any other.
1830
1831 The transformation is performed by splitting the ordered
1832 list into two equal sections plus a pivot. The parts are
1833 then attached to the pivot as left and right branches. Each
1834 branch is then transformed recursively. */
1835
1836void
1837switch_decision_tree::balance_case_nodes (case_tree_node **head,
1838 case_tree_node *parent)
1839{
1840 case_tree_node *np;
1841
1842 np = *head;
1843 if (np)
9dc3d6a9 1844 {
dc223ad4
ML
1845 int i = 0;
1846 int ranges = 0;
1847 case_tree_node **npp;
1848 case_tree_node *left;
9dc3d6a9 1849
dc223ad4 1850 /* Count the number of entries on branch. Also count the ranges. */
9dc3d6a9 1851
dc223ad4
ML
1852 while (np)
1853 {
1854 if (!tree_int_cst_equal (np->m_c->get_low (), np->m_c->get_high ()))
1855 ranges++;
9dc3d6a9 1856
dc223ad4
ML
1857 i++;
1858 np = np->m_right;
1859 }
9dc3d6a9 1860
dc223ad4
ML
1861 if (i > 2)
1862 {
1863 /* Split this list if it is long enough for that to help. */
1864 npp = head;
1865 left = *npp;
9dc3d6a9 1866
dc223ad4
ML
1867 /* If there are just three nodes, split at the middle one. */
1868 if (i == 3)
1869 npp = &(*npp)->m_right;
1870 else
1871 {
1872 /* Find the place in the list that bisects the list's total cost,
1873 where ranges count as 2.
1874 Here I gets half the total cost. */
1875 i = (i + ranges + 1) / 2;
1876 while (1)
1877 {
1878 /* Skip nodes while their cost does not reach that amount. */
1879 if (!tree_int_cst_equal ((*npp)->m_c->get_low (),
1880 (*npp)->m_c->get_high ()))
1881 i--;
1882 i--;
1883 if (i <= 0)
1884 break;
1885 npp = &(*npp)->m_right;
1886 }
1887 }
1888 *head = np = *npp;
1889 *npp = 0;
1890 np->m_parent = parent;
1891 np->m_left = left;
9dc3d6a9 1892
dc223ad4
ML
1893 /* Optimize each of the two split parts. */
1894 balance_case_nodes (&np->m_left, np);
1895 balance_case_nodes (&np->m_right, np);
1896 np->m_c->m_subtree_prob = np->m_c->m_prob;
1897 np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
1898 np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1899 }
1900 else
1901 {
1902 /* Else leave this branch as one level,
1903 but fill in `parent' fields. */
1904 np = *head;
1905 np->m_parent = parent;
1906 np->m_c->m_subtree_prob = np->m_c->m_prob;
1907 for (; np->m_right; np = np->m_right)
1908 {
1909 np->m_right->m_parent = np;
1910 (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1911 }
1912 }
9dc3d6a9 1913 }
dc223ad4
ML
1914}
1915
1916/* Dump ROOT, a list or tree of case nodes, to file. */
9dc3d6a9 1917
dc223ad4
ML
1918void
1919switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
1920 int indent_step, int indent_level)
1921{
1922 if (root == 0)
1923 return;
1924 indent_level++;
1925
1926 dump_case_nodes (f, root->m_left, indent_step, indent_level);
1927
1928 fputs (";; ", f);
1929 fprintf (f, "%*s", indent_step * indent_level, "");
1930 root->m_c->dump (f);
1931 root->m_c->m_prob.dump (f);
1932 fputs ("\n", f);
1933
1934 dump_case_nodes (f, root->m_right, indent_step, indent_level);
1935}
1936
1937
1938/* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1939
1940void
1941switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
1942{
1943 edge e = single_succ_edge (bb);
1944 redirect_edge_succ (e, case_bb);
1945}
1946
1947/* Generate code to compare OP0 with OP1 so that the condition codes are
1948 set and to jump to LABEL_BB if the condition is true.
1949 COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
1950 PROB is the probability of jumping to LABEL_BB. */
1951
1952basic_block
1953switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
1954 tree op1, tree_code comparison,
1955 basic_block label_bb,
1956 profile_probability prob)
1957{
1958 // TODO: it's once called with lhs != index.
1959 op1 = fold_convert (TREE_TYPE (op0), op1);
1960
1961 gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
1962 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1963 gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
1964
1965 gcc_assert (single_succ_p (bb));
1966
1967 /* Make a new basic block where false branch will take place. */
1968 edge false_edge = split_block (bb, cond);
1969 false_edge->flags = EDGE_FALSE_VALUE;
1970 false_edge->probability = prob.invert ();
1971
1972 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
1973 true_edge->probability = prob;
1974
1975 return false_edge->dest;
1976}
1977
1978/* Emit step-by-step code to select a case for the value of INDEX.
1979 The thus generated decision tree follows the form of the
1980 case-node binary tree NODE, whose nodes represent test conditions.
1981 DEFAULT_PROB is probability of cases leading to default BB.
1982 INDEX_TYPE is the type of the index of the switch. */
1983
1984basic_block
1985switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
1986 case_tree_node *node,
1987 profile_probability default_prob,
1988 tree index_type)
1989{
1990 /* If node is null, we are done. */
1991 if (node == NULL)
1992 return bb;
1993
1994 /* Branch to a label where we will handle it later. */
1995 basic_block test_bb = split_edge (single_succ_edge (bb));
1996 redirect_edge_succ (single_pred_edge (test_bb),
1997 single_succ_edge (bb)->dest);
1998
1999 profile_probability probability
2000 = (node->m_right
2001 ? node->m_right->m_c->m_subtree_prob : profile_probability::never ());
2002 probability = ((probability + default_prob.apply_scale (1, 2))
2003 / (node->m_c->m_subtree_prob + default_prob));
2004 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (), GT_EXPR,
2005 test_bb, probability);
2006 default_prob = default_prob.apply_scale (1, 2);
2007
2008 /* Value belongs to this node or to the left-hand subtree. */
2009 probability = node->m_c->m_prob /
2010 (node->m_c->m_subtree_prob + default_prob);
2011 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (), GE_EXPR,
2012 node->m_c->m_case_bb, probability);
2013
2014 /* Handle the left-hand subtree. */
2015 bb = emit_case_nodes (bb, index, node->m_left,
2016 default_prob, index_type);
2017
2018 /* If the left-hand subtree fell through,
2019 don't let it fall into the right-hand subtree. */
2020 if (m_default_bb)
2021 emit_jump (bb, m_default_bb);
2022
2023 bb = emit_case_nodes (test_bb, index, node->m_right,
2024 default_prob, index_type);
2025
2026 return bb;
2027}
2028
2029/* The main function of the pass scans statements for switches and invokes
2030 process_switch on them. */
2031
2032namespace {
2033
2034const pass_data pass_data_convert_switch =
2035{
2036 GIMPLE_PASS, /* type */
2037 "switchconv", /* name */
2038 OPTGROUP_NONE, /* optinfo_flags */
2039 TV_TREE_SWITCH_CONVERSION, /* tv_id */
2040 ( PROP_cfg | PROP_ssa ), /* properties_required */
2041 0, /* properties_provided */
2042 0, /* properties_destroyed */
2043 0, /* todo_flags_start */
2044 TODO_update_ssa, /* todo_flags_finish */
2045};
2046
2047class pass_convert_switch : public gimple_opt_pass
2048{
2049public:
2050 pass_convert_switch (gcc::context *ctxt)
2051 : gimple_opt_pass (pass_data_convert_switch, ctxt)
2052 {}
2053
2054 /* opt_pass methods: */
2055 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
2056 virtual unsigned int execute (function *);
2057
2058}; // class pass_convert_switch
2059
2060unsigned int
2061pass_convert_switch::execute (function *fun)
2062{
2063 basic_block bb;
2064 bool cfg_altered = false;
2065
2066 FOR_EACH_BB_FN (bb, fun)
2067 {
2068 gimple *stmt = last_stmt (bb);
2069 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2070 {
2071 if (dump_file)
2072 {
2073 expanded_location loc = expand_location (gimple_location (stmt));
2074
2075 fprintf (dump_file, "beginning to process the following "
2076 "SWITCH statement (%s:%d) : ------- \n",
2077 loc.file, loc.line);
2078 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2079 putc ('\n', dump_file);
2080 }
2081
2082 switch_conversion sconv;
2083 sconv.expand (as_a <gswitch *> (stmt));
2084 cfg_altered |= sconv.m_cfg_altered;
2085 if (!sconv.m_reason)
2086 {
2087 if (dump_file)
2088 {
2089 fputs ("Switch converted\n", dump_file);
2090 fputs ("--------------------------------\n", dump_file);
2091 }
2092
2093 /* Make no effort to update the post-dominator tree.
2094 It is actually not that hard for the transformations
2095 we have performed, but it is not supported
2096 by iterate_fix_dominators. */
2097 free_dominance_info (CDI_POST_DOMINATORS);
2098 }
2099 else
2100 {
2101 if (dump_file)
2102 {
2103 fputs ("Bailing out - ", dump_file);
2104 fputs (sconv.m_reason, dump_file);
2105 fputs ("\n--------------------------------\n", dump_file);
2106 }
2107 }
2108 }
2109 }
2110
2111 return cfg_altered ? TODO_cleanup_cfg : 0;;
2112}
2113
2114} // anon namespace
2115
2116gimple_opt_pass *
2117make_pass_convert_switch (gcc::context *ctxt)
2118{
2119 return new pass_convert_switch (ctxt);
9dc3d6a9
ML
2120}
2121
2122/* The main function of the pass scans statements for switches and invokes
2123 process_switch on them. */
2124
2125namespace {
2126
eb63c01f 2127template <bool O0> class pass_lower_switch: public gimple_opt_pass
9dc3d6a9 2128{
eb63c01f
ML
2129public:
2130 pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
2131
2132 static const pass_data data;
2133 opt_pass *
2134 clone ()
2135 {
2136 return new pass_lower_switch<O0> (m_ctxt);
2137 }
2138
2139 virtual bool
2140 gate (function *)
2141 {
2142 return !O0 || !optimize;
2143 }
2144
2145 virtual unsigned int execute (function *fun);
2146}; // class pass_lower_switch
2147
2148template <bool O0>
2149const pass_data pass_lower_switch<O0>::data = {
2150 GIMPLE_PASS, /* type */
2151 O0 ? "switchlower_O0" : "switchlower", /* name */
9dc3d6a9
ML
2152 OPTGROUP_NONE, /* optinfo_flags */
2153 TV_TREE_SWITCH_LOWERING, /* tv_id */
2154 ( PROP_cfg | PROP_ssa ), /* properties_required */
2155 0, /* properties_provided */
2156 0, /* properties_destroyed */
2157 0, /* todo_flags_start */
2158 TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
2159};
2160
eb63c01f 2161template <bool O0>
9dc3d6a9 2162unsigned int
eb63c01f 2163pass_lower_switch<O0>::execute (function *fun)
9dc3d6a9
ML
2164{
2165 basic_block bb;
2166 bool expanded = false;
2167
dc223ad4
ML
2168 auto_vec<gimple *> switch_statements;
2169 switch_statements.create (1);
2170
9dc3d6a9
ML
2171 FOR_EACH_BB_FN (bb, fun)
2172 {
2173 gimple *stmt = last_stmt (bb);
2174 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
dc223ad4
ML
2175 switch_statements.safe_push (stmt);
2176 }
2177
2178 for (unsigned i = 0; i < switch_statements.length (); i++)
2179 {
2180 gimple *stmt = switch_statements[i];
2181 if (dump_file)
9dc3d6a9 2182 {
dc223ad4 2183 expanded_location loc = expand_location (gimple_location (stmt));
9dc3d6a9 2184
dc223ad4
ML
2185 fprintf (dump_file, "beginning to process the following "
2186 "SWITCH statement (%s:%d) : ------- \n",
2187 loc.file, loc.line);
2188 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2189 putc ('\n', dump_file);
2190 }
9dc3d6a9 2191
dc223ad4
ML
2192 gswitch *swtch = dyn_cast<gswitch *> (stmt);
2193 if (swtch)
2194 {
2195 switch_decision_tree dt (swtch);
2196 expanded |= dt.analyze_switch_statement ();
9dc3d6a9
ML
2197 }
2198 }
2199
2200 if (expanded)
2201 {
2202 free_dominance_info (CDI_DOMINATORS);
2203 free_dominance_info (CDI_POST_DOMINATORS);
2204 mark_virtual_operands_for_renaming (cfun);
2205 }
2206
2207 return 0;
2208}
2209
2210} // anon namespace
2211
2212gimple_opt_pass *
eb63c01f 2213make_pass_lower_switch_O0 (gcc::context *ctxt)
9dc3d6a9 2214{
eb63c01f 2215 return new pass_lower_switch<true> (ctxt);
9dc3d6a9 2216}
eb63c01f
ML
2217gimple_opt_pass *
2218make_pass_lower_switch (gcc::context *ctxt)
9dc3d6a9 2219{
eb63c01f 2220 return new pass_lower_switch<false> (ctxt);
9dc3d6a9
ML
2221}
2222
9dc3d6a9 2223