Branch data Line data Source code
1 : : /* Lower GIMPLE_SWITCH expressions to something more efficient than
2 : : a jump table.
3 : : Copyright (C) 2006-2025 Free Software Foundation, Inc.
4 : :
5 : : This file is part of GCC.
6 : :
7 : : GCC is free software; you can redistribute it and/or modify it
8 : : under the terms of the GNU General Public License as published by the
9 : : Free Software Foundation; either version 3, or (at your option) any
10 : : later version.
11 : :
12 : : GCC is distributed in the hope that it will be useful, but WITHOUT
13 : : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 : : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 : : for more details.
16 : :
17 : : You should have received a copy of the GNU General Public License
18 : : along with GCC; see the file COPYING3. If not, write to the Free
19 : : Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 : : 02110-1301, USA. */
21 : :
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"
28 : : #include "backend.h"
29 : : #include "insn-codes.h"
30 : : #include "rtl.h"
31 : : #include "tree.h"
32 : : #include "gimple.h"
33 : : #include "cfghooks.h"
34 : : #include "tree-pass.h"
35 : : #include "ssa.h"
36 : : #include "optabs-tree.h"
37 : : #include "cgraph.h"
38 : : #include "gimple-pretty-print.h"
39 : : #include "fold-const.h"
40 : : #include "varasm.h"
41 : : #include "stor-layout.h"
42 : : #include "cfganal.h"
43 : : #include "gimplify.h"
44 : : #include "gimple-iterator.h"
45 : : #include "gimplify-me.h"
46 : : #include "gimple-fold.h"
47 : : #include "tree-cfg.h"
48 : : #include "cfgloop.h"
49 : : #include "alloc-pool.h"
50 : : #include "target.h"
51 : : #include "tree-into-ssa.h"
52 : : #include "omp-general.h"
53 : : #include "gimple-range.h"
54 : : #include "tree-cfgcleanup.h"
55 : : #include "hwint.h"
56 : : #include "internal-fn.h"
57 : : #include "diagnostic-core.h"
58 : :
59 : : /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
60 : : type in the GIMPLE type system that is language-independent? */
61 : : #include "langhooks.h"
62 : :
63 : : #include "tree-switch-conversion.h"
64 : :
65 : : using namespace tree_switch_conversion;
66 : :
67 : : /* Does the target have optabs needed to efficiently compute exact base two
68 : : logarithm of a variable with type TYPE?
69 : :
70 : : If yes, returns TYPE. If no, returns NULL_TREE. May also return another
71 : : type. This indicates that logarithm of the variable can be computed but
72 : : only after it is converted to this type.
73 : :
74 : : Also see gen_log2. */
75 : :
76 : : static tree
77 : 7449 : can_log2 (tree type, optimization_type opt_type)
78 : : {
79 : : /* Check if target supports FFS for given type. */
80 : 7449 : if (direct_internal_fn_supported_p (IFN_FFS, type, opt_type))
81 : : return type;
82 : :
83 : : /* Check if target supports FFS for some type we could convert to. */
84 : 1522 : int prec = TYPE_PRECISION (type);
85 : 1522 : int i_prec = TYPE_PRECISION (integer_type_node);
86 : 1522 : int li_prec = TYPE_PRECISION (long_integer_type_node);
87 : 1522 : int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
88 : 1522 : tree new_type;
89 : 1522 : if (prec <= i_prec
90 : 1522 : && direct_internal_fn_supported_p (IFN_FFS, integer_type_node, opt_type))
91 : 1502 : new_type = integer_type_node;
92 : 20 : else if (prec <= li_prec
93 : 20 : && direct_internal_fn_supported_p (IFN_FFS, long_integer_type_node,
94 : : opt_type))
95 : 0 : new_type = long_integer_type_node;
96 : 20 : else if (prec <= lli_prec
97 : 20 : && direct_internal_fn_supported_p (IFN_FFS,
98 : : long_long_integer_type_node,
99 : : opt_type))
100 : 0 : new_type = long_long_integer_type_node;
101 : : else
102 : 20 : return NULL_TREE;
103 : : return new_type;
104 : : }
105 : :
106 : : /* Assume that OP is a power of two. Build a sequence of gimple statements
107 : : efficiently computing the base two logarithm of OP using special optabs.
108 : : Return the ssa name represeting the result of the logarithm through RESULT.
109 : :
110 : : Before computing the logarithm, OP may have to be converted to another type.
111 : : This should be specified in TYPE. Use can_log2 to decide what this type
112 : : should be.
113 : :
114 : : Should only be used if can_log2 doesn't reject the type of OP. */
115 : :
116 : : static gimple_seq
117 : 21 : gen_log2 (tree op, location_t loc, tree *result, tree type)
118 : : {
119 : 21 : gimple_seq stmts = NULL;
120 : 21 : gimple_stmt_iterator gsi = gsi_last (stmts);
121 : :
122 : 21 : tree orig_type = TREE_TYPE (op);
123 : 21 : tree tmp1;
124 : 21 : if (type != orig_type)
125 : 4 : tmp1 = gimple_convert (&gsi, false, GSI_NEW_STMT, loc, type, op);
126 : : else
127 : : tmp1 = op;
128 : : /* Build FFS (op) - 1. */
129 : 21 : tree tmp2 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, IFN_FFS, orig_type,
130 : : tmp1);
131 : 21 : tree tmp3 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, MINUS_EXPR,
132 : : orig_type, tmp2, build_one_cst (orig_type));
133 : 21 : *result = tmp3;
134 : 21 : return stmts;
135 : : }
136 : :
137 : : /* Build a sequence of gimple statements checking that OP is a power of 2.
138 : : Return the result as a boolean_type_node ssa name through RESULT. Assumes
139 : : that OP's value will be non-negative. The generated check may give
140 : : arbitrary answer for negative values. */
141 : :
142 : : static gimple_seq
143 : 21 : gen_pow2p (tree op, location_t loc, tree *result)
144 : : {
145 : 21 : gimple_seq stmts = NULL;
146 : 21 : gimple_stmt_iterator gsi = gsi_last (stmts);
147 : :
148 : 21 : tree type = TREE_TYPE (op);
149 : 21 : tree utype = unsigned_type_for (type);
150 : :
151 : : /* Build (op ^ (op - 1)) > (op - 1). */
152 : 21 : tree tmp1;
153 : 21 : if (types_compatible_p (type, utype))
154 : : tmp1 = op;
155 : : else
156 : 13 : tmp1 = gimple_convert (&gsi, false, GSI_NEW_STMT, loc, utype, op);
157 : 21 : tree tmp2 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, MINUS_EXPR, utype,
158 : : tmp1, build_one_cst (utype));
159 : 21 : tree tmp3 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, BIT_XOR_EXPR,
160 : : utype, tmp1, tmp2);
161 : 21 : *result = gimple_build (&gsi, false, GSI_NEW_STMT, loc, GT_EXPR,
162 : : boolean_type_node, tmp3, tmp2);
163 : :
164 : 21 : return stmts;
165 : : }
166 : :
167 : :
168 : : /* Constructor. */
169 : :
170 : 29447 : switch_conversion::switch_conversion (): m_final_bb (NULL),
171 : 29447 : m_constructors (NULL), m_default_values (NULL),
172 : 29447 : m_arr_ref_first (NULL), m_arr_ref_last (NULL),
173 : 29447 : m_reason (NULL), m_default_case_nonstandard (false), m_cfg_altered (false),
174 : 29447 : m_exp_index_transform_applied (false)
175 : : {
176 : 29447 : }
177 : :
178 : : /* Collection information about SWTCH statement. */
179 : :
180 : : void
181 : 29447 : switch_conversion::collect (gswitch *swtch)
182 : : {
183 : 29447 : unsigned int branch_num = gimple_switch_num_labels (swtch);
184 : 29447 : tree min_case, max_case;
185 : 29447 : unsigned int i;
186 : 29447 : edge e, e_default, e_first;
187 : 29447 : edge_iterator ei;
188 : :
189 : 29447 : m_switch = swtch;
190 : :
191 : : /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
192 : : is a default label which is the first in the vector.
193 : : Collect the bits we can deduce from the CFG. */
194 : 29447 : m_index_expr = gimple_switch_index (swtch);
195 : 29447 : m_switch_bb = gimple_bb (swtch);
196 : 29447 : e_default = gimple_switch_default_edge (cfun, swtch);
197 : 29447 : m_default_bb = e_default->dest;
198 : 29447 : m_default_prob = e_default->probability;
199 : :
200 : : /* Get upper and lower bounds of case values, and the covered range. */
201 : 29447 : min_case = gimple_switch_label (swtch, 1);
202 : 29447 : max_case = gimple_switch_label (swtch, branch_num - 1);
203 : :
204 : 29447 : m_range_min = CASE_LOW (min_case);
205 : 29447 : if (CASE_HIGH (max_case) != NULL_TREE)
206 : 2715 : m_range_max = CASE_HIGH (max_case);
207 : : else
208 : 26732 : m_range_max = CASE_LOW (max_case);
209 : :
210 : 29447 : m_contiguous_range = true;
211 : 29447 : tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : m_range_min;
212 : 95849 : for (i = 2; i < branch_num; i++)
213 : : {
214 : 82549 : tree elt = gimple_switch_label (swtch, i);
215 : 82550 : if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
216 : : {
217 : 16147 : m_contiguous_range = false;
218 : 16147 : break;
219 : : }
220 : 66402 : last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
221 : : }
222 : :
223 : 29447 : if (m_contiguous_range)
224 : 13300 : e_first = gimple_switch_edge (cfun, swtch, 1);
225 : : else
226 : : e_first = e_default;
227 : :
228 : : /* See if there is one common successor block for all branch
229 : : targets. If it exists, record it in FINAL_BB.
230 : : Start with the destination of the first non-default case
231 : : if the range is contiguous and default case otherwise as
232 : : guess or its destination in case it is a forwarder block. */
233 : 29447 : if (! single_pred_p (e_first->dest))
234 : 8421 : m_final_bb = e_first->dest;
235 : 21026 : else if (single_succ_p (e_first->dest)
236 : 17735 : && ! single_pred_p (single_succ (e_first->dest)))
237 : 12731 : m_final_bb = single_succ (e_first->dest);
238 : : /* Require that all switch destinations are either that common
239 : : FINAL_BB or a forwarder to it, except for the default
240 : : case if contiguous range. */
241 : 29447 : auto_vec<edge, 10> fw_edges;
242 : 29447 : m_uniq = 0;
243 : 29447 : if (m_final_bb)
244 : 107060 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
245 : : {
246 : 94257 : edge phi_e = nullptr;
247 : 94257 : if (e->dest == m_final_bb)
248 : 13760 : phi_e = e;
249 : 80497 : else if (single_pred_p (e->dest)
250 : 166853 : && single_succ_p (e->dest)
251 : 153093 : && single_succ (e->dest) == m_final_bb)
252 : 69838 : phi_e = single_succ_edge (e->dest);
253 : 94257 : if (phi_e)
254 : : {
255 : 83598 : if (e == e_default)
256 : : ;
257 : 65138 : else if (phi_e == e || empty_block_p (e->dest))
258 : : {
259 : : /* For empty blocks consider forwarders with equal
260 : : PHI arguments in m_final_bb as unique. */
261 : : unsigned i;
262 : 111961 : for (i = 0; i < fw_edges.length (); ++i)
263 : 95913 : if (phi_alternatives_equal (m_final_bb, fw_edges[i], phi_e))
264 : : break;
265 : 34100 : if (i == fw_edges.length ())
266 : : {
267 : : /* But limit the above possibly quadratic search. */
268 : 16048 : if (fw_edges.length () < 10)
269 : 7548 : fw_edges.quick_push (phi_e);
270 : 16048 : m_uniq++;
271 : : }
272 : : }
273 : : else
274 : 48088 : m_uniq++;
275 : 85908 : continue;
276 : 83598 : }
277 : :
278 : 10659 : if (e == e_default && m_contiguous_range)
279 : : {
280 : 2310 : m_default_case_nonstandard = true;
281 : 2310 : continue;
282 : : }
283 : :
284 : 8349 : m_final_bb = NULL;
285 : 8349 : break;
286 : : }
287 : :
288 : : /* When there's not a single common successor block conservatively
289 : : approximate the number of unique non-default targets. */
290 : 29447 : if (!m_final_bb)
291 : 33288 : m_uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
292 : :
293 : 29447 : m_range_size
294 : 29447 : = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
295 : :
296 : : /* Get a count of the number of case labels. Single-valued case labels
297 : : simply count as one, but a case range counts double, since it may
298 : : require two compares if it gets lowered as a branching tree. */
299 : 29447 : m_count = 0;
300 : 197426 : for (i = 1; i < branch_num; i++)
301 : : {
302 : 167979 : tree elt = gimple_switch_label (swtch, i);
303 : 167979 : m_count++;
304 : 167979 : if (CASE_HIGH (elt)
305 : 167979 : && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
306 : 11568 : m_count++;
307 : : }
308 : 29447 : }
309 : :
310 : : /* Check that the "exponential index transform" can be applied to this switch.
311 : :
312 : : See comment of the exp_index_transform function for details about this
313 : : transformation.
314 : :
315 : : We want:
316 : : - This form of the switch is more efficient
317 : : - Cases are powers of 2
318 : :
319 : : Expects that SWTCH has at least one case. */
320 : :
321 : : bool
322 : 7449 : switch_conversion::is_exp_index_transform_viable (gswitch *swtch)
323 : : {
324 : 7449 : tree index = gimple_switch_index (swtch);
325 : 7449 : tree index_type = TREE_TYPE (index);
326 : 7449 : basic_block swtch_bb = gimple_bb (swtch);
327 : 7449 : unsigned num_labels = gimple_switch_num_labels (swtch);
328 : :
329 : 7449 : optimization_type opt_type = bb_optimization_type (swtch_bb);
330 : 7449 : m_exp_index_transform_log2_type = can_log2 (index_type, opt_type);
331 : 7449 : if (!m_exp_index_transform_log2_type)
332 : : return false;
333 : :
334 : : /* Check that each case label corresponds only to one value
335 : : (no case 1..3). */
336 : : unsigned i;
337 : 56728 : for (i = 1; i < num_labels; i++)
338 : : {
339 : 49782 : tree label = gimple_switch_label (swtch, i);
340 : 49782 : if (CASE_HIGH (label))
341 : : return false;
342 : : }
343 : :
344 : : /* Check that each label is nonnegative and a power of 2. */
345 : 10350 : for (i = 1; i < num_labels; i++)
346 : : {
347 : 10276 : tree label = gimple_switch_label (swtch, i);
348 : 10276 : wide_int label_wi = wi::to_wide (CASE_LOW (label));
349 : 10276 : if (!wi::ge_p (label_wi, 0, TYPE_SIGN (index_type)))
350 : : return false;
351 : 10155 : if (wi::exact_log2 (label_wi) == -1)
352 : : return false;
353 : 10276 : }
354 : :
355 : 74 : if (dump_file)
356 : 12 : fprintf (dump_file, "Exponential index transform viable\n");
357 : :
358 : : return true;
359 : : }
360 : :
361 : : /* Perform the "exponential index transform".
362 : :
363 : : Assume that cases of SWTCH are powers of 2. The transformation replaces the
364 : : cases by their exponents (2^k -> k). It also inserts a statement that
365 : : computes the exponent of the original index variable (basically taking the
366 : : logarithm) and then sets the result as the new index variable.
367 : :
368 : : The transformation also inserts a conditional statement checking that the
369 : : incoming original index variable is a power of 2 with the false edge leading
370 : : to the default case.
371 : :
372 : : The exponential index transform shrinks the range of case numbers which
373 : : helps switch conversion convert switches it otherwise could not.
374 : :
375 : : Consider for example:
376 : :
377 : : switch (i)
378 : : {
379 : : case (1 << 0): return 0;
380 : : case (1 << 1): return 1;
381 : : case (1 << 2): return 2;
382 : : ...
383 : : case (1 << 30): return 30;
384 : : default: return 31;
385 : : }
386 : :
387 : : First, exponential index transform gets applied. Since each case becomes
388 : : case x: return x;, the rest of switch conversion is then able to get rid of
389 : : the switch statement.
390 : :
391 : : if (i is power of 2)
392 : : return log2 (i);
393 : : else
394 : : return 31;
395 : :
396 : : */
397 : :
398 : : void
399 : 21 : switch_conversion::exp_index_transform (gswitch *swtch)
400 : : {
401 : 21 : if (dump_file)
402 : 11 : fprintf (dump_file, "Applying exponential index transform\n");
403 : :
404 : 21 : tree index = gimple_switch_index (swtch);
405 : 21 : tree index_type = TREE_TYPE (index);
406 : 21 : basic_block swtch_bb = gimple_bb (swtch);
407 : 21 : unsigned num_labels = gimple_switch_num_labels (swtch);
408 : :
409 : : /* Insert a cond stmt that checks if the index variable is a power of 2. */
410 : 21 : gimple_stmt_iterator gsi = gsi_for_stmt (swtch);
411 : 21 : gsi_prev (&gsi);
412 : 21 : gimple *foo = gsi_stmt (gsi);
413 : 21 : edge new_edge1 = split_block (swtch_bb, foo);
414 : :
415 : 21 : swtch_bb = new_edge1->dest;
416 : 21 : basic_block cond_bb = new_edge1->src;
417 : 21 : new_edge1->flags |= EDGE_TRUE_VALUE;
418 : 21 : new_edge1->flags &= ~EDGE_FALLTHRU;
419 : 21 : new_edge1->probability = profile_probability::even ();
420 : :
421 : 21 : basic_block default_bb = gimple_switch_default_bb (cfun, swtch);
422 : 21 : edge new_edge2 = make_edge (cond_bb, default_bb, EDGE_FALSE_VALUE);
423 : 21 : new_edge2->probability = profile_probability::even ();
424 : :
425 : 21 : tree tmp;
426 : 21 : gimple_seq stmts = gen_pow2p (index, UNKNOWN_LOCATION, &tmp);
427 : 21 : gsi = gsi_last_bb (cond_bb);
428 : 21 : gsi_insert_seq_after (&gsi, stmts, GSI_LAST_NEW_STMT);
429 : 21 : gcond *stmt_cond = gimple_build_cond (NE_EXPR, tmp, boolean_false_node,
430 : : NULL, NULL);
431 : 21 : gsi_insert_after (&gsi, stmt_cond, GSI_NEW_STMT);
432 : :
433 : : /* We just added an edge going to default bb so fix PHI nodes in that bb:
434 : : For each PHI add new PHI arg. It will be the same arg as when comming to
435 : : the default bb from the switch bb. */
436 : 21 : edge default_edge = find_edge (swtch_bb, default_bb);
437 : 21 : for (gphi_iterator gsi = gsi_start_phis (default_bb);
438 : 33 : !gsi_end_p (gsi); gsi_next (&gsi))
439 : : {
440 : 12 : gphi *phi = gsi.phi ();
441 : 12 : tree arg = PHI_ARG_DEF_FROM_EDGE (phi, default_edge);
442 : 12 : location_t loc = gimple_phi_arg_location_from_edge (phi, default_edge);
443 : 12 : add_phi_arg (phi, arg, new_edge2, loc);
444 : : }
445 : :
446 : : /* Insert a sequence of stmts that takes the log of the index variable. */
447 : 21 : stmts = gen_log2 (index, UNKNOWN_LOCATION, &tmp,
448 : : m_exp_index_transform_log2_type);
449 : 21 : gsi = gsi_after_labels (swtch_bb);
450 : 21 : gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
451 : :
452 : : /* Use the result of the logarithm as the new index variable. */
453 : 21 : gimple_switch_set_index (swtch, tmp);
454 : 21 : update_stmt (swtch);
455 : :
456 : : /* Replace each case number with its logarithm. */
457 : 21 : unsigned i;
458 : 134 : for (i = 1; i < num_labels; i++)
459 : : {
460 : 113 : tree label = gimple_switch_label (swtch, i);
461 : 226 : CASE_LOW (label) = build_int_cst (index_type,
462 : 113 : tree_log2 (CASE_LOW (label)));
463 : : }
464 : :
465 : : /* Fix the dominator tree, if it is available. */
466 : 21 : if (dom_info_available_p (CDI_DOMINATORS))
467 : : {
468 : : /* Analysis of how dominators should look after we add the edge E going
469 : : from the cond block to the default block.
470 : :
471 : : 1 For the blocks between the switch block and the final block
472 : : (excluding the final block itself): They had the switch block as
473 : : their immediate dominator. That shouldn't change.
474 : :
475 : : 2 The final block may now have the switch block or the cond block as
476 : : its immediate dominator. There's no easy way of knowing (consider
477 : : two cases where in both m_default_case_nonstandard = true, in one a
478 : : path through default intersects the final block and in one all paths
479 : : through default avoid the final block but intersect a successor of the
480 : : final block).
481 : :
482 : : 3 Other blocks that had the switch block as their immediate dominator
483 : : should now have the cond block as their immediate dominator.
484 : :
485 : : 4 Immediate dominators of the rest of the blocks shouldn't change.
486 : :
487 : : Reasoning for 3 and 4:
488 : :
489 : : We'll only consider blocks that do not fall into 1 or 2.
490 : :
491 : : Consider a block X whose original imm dom was the switch block. All
492 : : paths to X must also intersect the cond block since it's the only
493 : : pred of the switch block. The final block doesn't dominate X so at
494 : : least one path P must lead through the default block. Let P' be P but
495 : : instead of going through the switch block, take E. The switch block
496 : : doesn't dominate X so its imm dom must now be the cond block.
497 : :
498 : : Consider a block X whose original imm dom was Y != the switch block.
499 : : We only added an edge so all original paths to X are still present.
500 : : So X gained no new dominators. Observe that Y still dominates X.
501 : : There would have to be a path that avoids Y otherwise. But any block
502 : : we can avoid now except for the switch block we were able to avoid
503 : : before adding E. */
504 : :
505 : 21 : redirect_immediate_dominators (CDI_DOMINATORS, swtch_bb, cond_bb);
506 : :
507 : 21 : edge e;
508 : 21 : edge_iterator ei;
509 : 155 : FOR_EACH_EDGE (e, ei, swtch_bb->succs)
510 : : {
511 : 134 : basic_block bb = e->dest;
512 : 134 : if (bb == m_final_bb || bb == default_bb)
513 : 30 : continue;
514 : 104 : set_immediate_dominator (CDI_DOMINATORS, bb, swtch_bb);
515 : : }
516 : :
517 : 21 : vec<basic_block> v;
518 : 21 : v.create (1);
519 : 21 : v.quick_push (m_final_bb);
520 : 21 : iterate_fix_dominators (CDI_DOMINATORS, v, true);
521 : : }
522 : :
523 : : /* Update information about the switch statement. */
524 : 21 : tree first_label = gimple_switch_label (swtch, 1);
525 : 21 : tree last_label = gimple_switch_label (swtch, num_labels - 1);
526 : :
527 : 21 : m_range_min = CASE_LOW (first_label);
528 : 21 : m_range_max = CASE_LOW (last_label);
529 : 21 : m_index_expr = gimple_switch_index (swtch);
530 : 21 : m_switch_bb = swtch_bb;
531 : :
532 : 21 : m_range_size = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
533 : :
534 : 21 : m_cfg_altered = true;
535 : :
536 : 21 : m_contiguous_range = true;
537 : 21 : wide_int last_wi = wi::to_wide (CASE_LOW (first_label));
538 : 113 : for (i = 2; i < num_labels; i++)
539 : : {
540 : 92 : tree label = gimple_switch_label (swtch, i);
541 : 92 : wide_int label_wi = wi::to_wide (CASE_LOW (label));
542 : 92 : m_contiguous_range &= wi::eq_p (wi::add (last_wi, 1), label_wi);
543 : 92 : last_wi = label_wi;
544 : 92 : }
545 : :
546 : 21 : m_exp_index_transform_applied = true;
547 : 21 : }
548 : :
549 : : /* Checks whether the range given by individual case statements of the switch
550 : : switch statement isn't too big and whether the number of branches actually
551 : : satisfies the size of the new array. */
552 : :
553 : : bool
554 : 7375 : switch_conversion::check_range ()
555 : : {
556 : 7375 : gcc_assert (m_range_size);
557 : 7375 : if (!tree_fits_uhwi_p (m_range_size))
558 : : {
559 : 18 : m_reason = "index range way too large or otherwise unusable";
560 : 18 : return false;
561 : : }
562 : :
563 : 7357 : if (tree_to_uhwi (m_range_size)
564 : 7357 : > ((unsigned) m_count * param_switch_conversion_branch_ratio))
565 : : {
566 : 748 : m_reason = "the maximum range-branch ratio exceeded";
567 : 748 : return false;
568 : : }
569 : :
570 : : return true;
571 : : }
572 : :
573 : : /* Checks whether all but the final BB basic blocks are empty. */
574 : :
575 : : bool
576 : 6683 : switch_conversion::check_all_empty_except_final ()
577 : : {
578 : 6683 : edge e, e_default = find_edge (m_switch_bb, m_default_bb);
579 : 6683 : edge_iterator ei;
580 : :
581 : 21376 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
582 : : {
583 : 20600 : if (e->dest == m_final_bb)
584 : 4464 : continue;
585 : :
586 : 16136 : if (!empty_block_p (e->dest))
587 : : {
588 : 7273 : if (m_contiguous_range && e == e_default)
589 : : {
590 : 1366 : m_default_case_nonstandard = true;
591 : 1366 : continue;
592 : : }
593 : :
594 : 5907 : m_reason = "bad case - a non-final BB not empty";
595 : 5907 : return false;
596 : : }
597 : : }
598 : :
599 : : return true;
600 : : }
601 : :
602 : : /* This function checks whether all required values in phi nodes in final_bb
603 : : are constants. Required values are those that correspond to a basic block
604 : : which is a part of the examined switch statement. It returns true if the
605 : : phi nodes are OK, otherwise false. */
606 : :
607 : : bool
608 : 776 : switch_conversion::check_final_bb ()
609 : : {
610 : 776 : gphi_iterator gsi;
611 : :
612 : 776 : m_phi_count = 0;
613 : 1542 : for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
614 : : {
615 : 853 : gphi *phi = gsi.phi ();
616 : 853 : unsigned int i;
617 : :
618 : 1706 : if (virtual_operand_p (gimple_phi_result (phi)))
619 : 20 : continue;
620 : :
621 : 833 : m_phi_count++;
622 : :
623 : 9973 : for (i = 0; i < gimple_phi_num_args (phi); i++)
624 : : {
625 : 9227 : basic_block bb = gimple_phi_arg_edge (phi, i)->src;
626 : :
627 : 9227 : if (bb == m_switch_bb
628 : 26746 : || (single_pred_p (bb)
629 : 8379 : && single_pred (bb) == m_switch_bb
630 : 8179 : && (!m_default_case_nonstandard
631 : 487 : || empty_block_p (bb))))
632 : : {
633 : 8986 : tree reloc, val;
634 : 8986 : const char *reason = NULL;
635 : :
636 : 8986 : val = gimple_phi_arg_def (phi, i);
637 : 8986 : if (!is_gimple_ip_invariant (val))
638 : : reason = "non-invariant value from a case";
639 : : else
640 : : {
641 : 8949 : reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
642 : 8949 : if ((flag_pic && reloc != null_pointer_node)
643 : 8882 : || (!flag_pic && reloc == NULL_TREE))
644 : : {
645 : 67 : if (reloc)
646 : : reason
647 : : = "value from a case would need runtime relocations";
648 : : else
649 : : reason
650 : : = "value from a case is not a valid initializer";
651 : : }
652 : : }
653 : : if (reason)
654 : : {
655 : : /* For contiguous range, we can allow non-constant
656 : : or one that needs relocation, as long as it is
657 : : only reachable from the default case. */
658 : 104 : if (bb == m_switch_bb)
659 : 88 : bb = m_final_bb;
660 : 104 : if (!m_contiguous_range || bb != m_default_bb)
661 : : {
662 : 87 : m_reason = reason;
663 : 87 : return false;
664 : : }
665 : :
666 : 17 : unsigned int branch_num = gimple_switch_num_labels (m_switch);
667 : 116 : for (unsigned int i = 1; i < branch_num; i++)
668 : : {
669 : 99 : if (gimple_switch_label_bb (cfun, m_switch, i) == bb)
670 : : {
671 : 0 : m_reason = reason;
672 : 0 : return false;
673 : : }
674 : : }
675 : 17 : m_default_case_nonstandard = true;
676 : : }
677 : : }
678 : : }
679 : : }
680 : :
681 : : return true;
682 : : }
683 : :
684 : : /* The following function allocates default_values, target_{in,out}_names and
685 : : constructors arrays. The last one is also populated with pointers to
686 : : vectors that will become constructors of new arrays. */
687 : :
688 : : void
689 : 689 : switch_conversion::create_temp_arrays ()
690 : : {
691 : 689 : int i;
692 : :
693 : 689 : m_default_values = XCNEWVEC (tree, m_phi_count * 3);
694 : : /* ??? Macros do not support multi argument templates in their
695 : : argument list. We create a typedef to work around that problem. */
696 : 689 : typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
697 : 689 : m_constructors = XCNEWVEC (vec_constructor_elt_gc, m_phi_count);
698 : 689 : m_target_inbound_names = m_default_values + m_phi_count;
699 : 689 : m_target_outbound_names = m_target_inbound_names + m_phi_count;
700 : 1433 : for (i = 0; i < m_phi_count; i++)
701 : 744 : vec_alloc (m_constructors[i], tree_to_uhwi (m_range_size) + 1);
702 : 689 : }
703 : :
704 : : /* Populate the array of default values in the order of phi nodes.
705 : : DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
706 : : if the range is non-contiguous or the default case has standard
707 : : structure, otherwise it is the first non-default case instead. */
708 : :
709 : : void
710 : 689 : switch_conversion::gather_default_values (tree default_case)
711 : : {
712 : 689 : gphi_iterator gsi;
713 : 689 : basic_block bb = label_to_block (cfun, CASE_LABEL (default_case));
714 : 689 : edge e;
715 : 689 : int i = 0;
716 : :
717 : 689 : gcc_assert (CASE_LOW (default_case) == NULL_TREE
718 : : || m_default_case_nonstandard);
719 : :
720 : 689 : if (bb == m_final_bb)
721 : 234 : e = find_edge (m_switch_bb, bb);
722 : : else
723 : 455 : e = single_succ_edge (bb);
724 : :
725 : 1453 : for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
726 : : {
727 : 764 : gphi *phi = gsi.phi ();
728 : 1528 : if (virtual_operand_p (gimple_phi_result (phi)))
729 : 20 : continue;
730 : 744 : tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
731 : 744 : gcc_assert (val);
732 : 744 : m_default_values[i++] = val;
733 : : }
734 : 689 : }
735 : :
736 : : /* The following function populates the vectors in the constructors array with
737 : : future contents of the static arrays. The vectors are populated in the
738 : : order of phi nodes. */
739 : :
740 : : void
741 : 689 : switch_conversion::build_constructors ()
742 : : {
743 : 689 : unsigned i, branch_num = gimple_switch_num_labels (m_switch);
744 : 689 : tree pos = m_range_min;
745 : 689 : tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
746 : :
747 : 8850 : for (i = 1; i < branch_num; i++)
748 : : {
749 : 8161 : tree cs = gimple_switch_label (m_switch, i);
750 : 8161 : basic_block bb = label_to_block (cfun, CASE_LABEL (cs));
751 : 8161 : edge e;
752 : 8161 : tree high;
753 : 8161 : gphi_iterator gsi;
754 : 8161 : int j;
755 : :
756 : 8161 : if (bb == m_final_bb)
757 : 529 : e = find_edge (m_switch_bb, bb);
758 : : else
759 : 7632 : e = single_succ_edge (bb);
760 : 8161 : gcc_assert (e);
761 : :
762 : 12016 : while (tree_int_cst_lt (pos, CASE_LOW (cs)))
763 : : {
764 : : int k;
765 : 9142 : for (k = 0; k < m_phi_count; k++)
766 : : {
767 : 5287 : constructor_elt elt;
768 : :
769 : 5287 : elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
770 : 5287 : if (TYPE_PRECISION (TREE_TYPE (elt.index))
771 : 5287 : > TYPE_PRECISION (sizetype))
772 : 18 : elt.index = fold_convert (sizetype, elt.index);
773 : 5287 : elt.value
774 : 5287 : = unshare_expr_without_location (m_default_values[k]);
775 : 5287 : m_constructors[k]->quick_push (elt);
776 : : }
777 : :
778 : 3855 : pos = int_const_binop (PLUS_EXPR, pos, pos_one);
779 : : }
780 : 8161 : gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
781 : :
782 : 8161 : j = 0;
783 : 8161 : if (CASE_HIGH (cs))
784 : 108 : high = CASE_HIGH (cs);
785 : : else
786 : 8053 : high = CASE_LOW (cs);
787 : 8161 : for (gsi = gsi_start_phis (m_final_bb);
788 : 16881 : !gsi_end_p (gsi); gsi_next (&gsi))
789 : : {
790 : 8720 : gphi *phi = gsi.phi ();
791 : 17440 : if (virtual_operand_p (gimple_phi_result (phi)))
792 : 102 : continue;
793 : 8618 : tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
794 : 8618 : tree low = CASE_LOW (cs);
795 : 8618 : pos = CASE_LOW (cs);
796 : :
797 : 8945 : do
798 : : {
799 : 8945 : constructor_elt elt;
800 : :
801 : 8945 : elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
802 : 8945 : if (TYPE_PRECISION (TREE_TYPE (elt.index))
803 : 8945 : > TYPE_PRECISION (sizetype))
804 : 33 : elt.index = fold_convert (sizetype, elt.index);
805 : 8945 : elt.value = unshare_expr_without_location (val);
806 : 8945 : m_constructors[j]->quick_push (elt);
807 : :
808 : 8945 : pos = int_const_binop (PLUS_EXPR, pos, pos_one);
809 : 8945 : } while (!tree_int_cst_lt (high, pos)
810 : 17563 : && tree_int_cst_lt (low, pos));
811 : 8618 : j++;
812 : : }
813 : : }
814 : 689 : }
815 : :
816 : : /* If all values in the constructor vector are products of a linear function
817 : : a * x + b, then return true. When true, COEFF_A and COEFF_B and
818 : : coefficients of the linear function. Note that equal values are special
819 : : case of a linear function with a and b equal to zero. */
820 : :
821 : : bool
822 : 744 : switch_conversion::contains_linear_function_p (vec<constructor_elt, va_gc> *vec,
823 : : wide_int *coeff_a,
824 : : wide_int *coeff_b)
825 : : {
826 : 744 : unsigned int i;
827 : 744 : constructor_elt *elt;
828 : :
829 : 744 : gcc_assert (vec->length () >= 2);
830 : :
831 : : /* Let's try to find any linear function a * x + y that can apply to
832 : : given values. 'a' can be calculated as follows:
833 : :
834 : : a = (y2 - y1) / (x2 - x1) where x2 - x1 = 1 (consecutive case indices)
835 : : a = y2 - y1
836 : :
837 : : and
838 : :
839 : : b = y2 - a * x2
840 : :
841 : : */
842 : :
843 : 744 : tree elt0 = (*vec)[0].value;
844 : 744 : tree elt1 = (*vec)[1].value;
845 : :
846 : 744 : if (TREE_CODE (elt0) != INTEGER_CST || TREE_CODE (elt1) != INTEGER_CST)
847 : : return false;
848 : :
849 : 580 : wide_int range_min
850 : 580 : = wide_int::from (wi::to_wide (m_range_min),
851 : 580 : TYPE_PRECISION (TREE_TYPE (elt0)),
852 : 1740 : TYPE_SIGN (TREE_TYPE (m_range_min)));
853 : 580 : wide_int y1 = wi::to_wide (elt0);
854 : 580 : wide_int y2 = wi::to_wide (elt1);
855 : 580 : wide_int a = y2 - y1;
856 : 580 : wide_int b = y2 - a * (range_min + 1);
857 : :
858 : : /* Verify that all values fulfill the linear function. */
859 : 2247 : FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
860 : : {
861 : 2146 : if (TREE_CODE (elt->value) != INTEGER_CST)
862 : 479 : return false;
863 : :
864 : 2146 : wide_int value = wi::to_wide (elt->value);
865 : 2146 : if (a * range_min + b != value)
866 : 479 : return false;
867 : :
868 : 1667 : ++range_min;
869 : 2146 : }
870 : :
871 : 101 : *coeff_a = a;
872 : 101 : *coeff_b = b;
873 : :
874 : 101 : return true;
875 : 580 : }
876 : :
877 : : /* Return type which should be used for array elements, either TYPE's
878 : : main variant or, for integral types, some smaller integral type
879 : : that can still hold all the constants. */
880 : :
881 : : tree
882 : 643 : switch_conversion::array_value_type (tree type, int num)
883 : : {
884 : 643 : unsigned int i, len = vec_safe_length (m_constructors[num]);
885 : 643 : constructor_elt *elt;
886 : 643 : int sign = 0;
887 : 643 : tree smaller_type;
888 : :
889 : : /* Types with alignments greater than their size can reach here, e.g. out of
890 : : SRA. We couldn't use these as an array component type so get back to the
891 : : main variant first, which, for our purposes, is fine for other types as
892 : : well. */
893 : :
894 : 643 : type = TYPE_MAIN_VARIANT (type);
895 : :
896 : 643 : if (!INTEGRAL_TYPE_P (type)
897 : 643 : || (TREE_CODE (type) == BITINT_TYPE
898 : 0 : && (TYPE_PRECISION (type) > MAX_FIXED_MODE_SIZE
899 : 0 : || TYPE_MODE (type) == BLKmode)))
900 : 164 : return type;
901 : :
902 : 479 : scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
903 : 479 : scalar_int_mode mode = get_narrowest_mode (type_mode);
904 : 1437 : if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
905 : : return type;
906 : :
907 : 474 : if (len < (optimize_bb_for_size_p (gimple_bb (m_switch)) ? 2 : 32))
908 : : return type;
909 : :
910 : 2642 : FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
911 : : {
912 : 2589 : wide_int cst;
913 : :
914 : 2589 : if (TREE_CODE (elt->value) != INTEGER_CST)
915 : : return type;
916 : :
917 : 2589 : cst = wi::to_wide (elt->value);
918 : 2610 : while (1)
919 : : {
920 : 2612 : unsigned int prec = GET_MODE_BITSIZE (mode);
921 : 2610 : if (prec > HOST_BITS_PER_WIDE_INT)
922 : : return type;
923 : :
924 : 2610 : if (sign >= 0 && cst == wi::zext (cst, prec))
925 : : {
926 : 1411 : if (sign == 0 && cst == wi::sext (cst, prec))
927 : : break;
928 : 457 : sign = 1;
929 : 457 : break;
930 : : }
931 : 1199 : if (sign <= 0 && cst == wi::sext (cst, prec))
932 : : {
933 : : sign = -1;
934 : : break;
935 : : }
936 : :
937 : 23 : if (sign == 1)
938 : : sign = 0;
939 : :
940 : 46 : if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
941 : 48 : || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
942 : : return type;
943 : : }
944 : 2589 : }
945 : :
946 : 53 : if (sign == 0)
947 : 28 : sign = TYPE_UNSIGNED (type) ? 1 : -1;
948 : 53 : smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
949 : 53 : if (GET_MODE_SIZE (type_mode)
950 : 106 : <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
951 : : return type;
952 : :
953 : : return smaller_type;
954 : : }
955 : :
956 : : /* Create an appropriate array type and declaration and assemble a static
957 : : array variable. Also create a load statement that initializes
958 : : the variable in question with a value from the static array. SWTCH is
959 : : the switch statement being converted, NUM is the index to
960 : : arrays of constructors, default values and target SSA names
961 : : for this particular array. ARR_INDEX_TYPE is the type of the index
962 : : of the new array, PHI is the phi node of the final BB that corresponds
963 : : to the value that will be loaded from the created array. TIDX
964 : : is an ssa name of a temporary variable holding the index for loads from the
965 : : new array. */
966 : :
967 : : void
968 : 744 : switch_conversion::build_one_array (int num, tree arr_index_type,
969 : : gphi *phi, tree tidx)
970 : : {
971 : 744 : tree name;
972 : 744 : gimple *load;
973 : 744 : gimple_stmt_iterator gsi = gsi_for_stmt (m_switch);
974 : 744 : location_t loc = gimple_location (m_switch);
975 : :
976 : 744 : gcc_assert (m_default_values[num]);
977 : :
978 : 744 : name = copy_ssa_name (PHI_RESULT (phi));
979 : 744 : m_target_inbound_names[num] = name;
980 : :
981 : 744 : vec<constructor_elt, va_gc> *constructor = m_constructors[num];
982 : 744 : wide_int coeff_a, coeff_b;
983 : 744 : bool linear_p = contains_linear_function_p (constructor, &coeff_a, &coeff_b);
984 : 744 : tree type;
985 : 744 : if (linear_p
986 : 744 : && (type = range_check_type (TREE_TYPE ((*constructor)[0].value))))
987 : : {
988 : 118 : if (dump_file && coeff_a.to_uhwi () > 0)
989 : 16 : fprintf (dump_file, "Linear transformation with A = %" PRId64
990 : : " and B = %" PRId64 "\n", coeff_a.to_shwi (),
991 : : coeff_b.to_shwi ());
992 : :
993 : : /* We must use type of constructor values. */
994 : 101 : gimple_seq seq = NULL;
995 : 101 : tree tmp = gimple_convert (&seq, type, m_index_expr);
996 : 202 : tree tmp2 = gimple_build (&seq, MULT_EXPR, type,
997 : 101 : wide_int_to_tree (type, coeff_a), tmp);
998 : 202 : tree tmp3 = gimple_build (&seq, PLUS_EXPR, type, tmp2,
999 : 101 : wide_int_to_tree (type, coeff_b));
1000 : 101 : tree tmp4 = gimple_convert (&seq, TREE_TYPE (name), tmp3);
1001 : 101 : gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
1002 : 101 : load = gimple_build_assign (name, tmp4);
1003 : : }
1004 : : else
1005 : : {
1006 : 643 : tree array_type, ctor, decl, value_type, fetch, default_type;
1007 : :
1008 : 643 : default_type = TREE_TYPE (m_default_values[num]);
1009 : 643 : value_type = array_value_type (default_type, num);
1010 : 643 : array_type = build_array_type (value_type, arr_index_type);
1011 : 643 : addr_space_t as
1012 : 643 : = targetm.addr_space.for_artificial_rodata (array_type,
1013 : : ARTIFICIAL_RODATA_CSWITCH);
1014 : 643 : if (!ADDR_SPACE_GENERIC_P (as))
1015 : : {
1016 : 0 : int quals = (TYPE_QUALS_NO_ADDR_SPACE (value_type)
1017 : 0 : | ENCODE_QUAL_ADDR_SPACE (as));
1018 : 0 : value_type = build_qualified_type (value_type, quals);
1019 : 0 : array_type = build_array_type (value_type, arr_index_type);
1020 : : }
1021 : 643 : if (default_type != value_type)
1022 : : {
1023 : : unsigned int i;
1024 : : constructor_elt *elt;
1025 : :
1026 : 3386 : FOR_EACH_VEC_SAFE_ELT (constructor, i, elt)
1027 : 3272 : elt->value = fold_convert (value_type, elt->value);
1028 : : }
1029 : 643 : ctor = build_constructor (array_type, constructor);
1030 : 643 : TREE_CONSTANT (ctor) = true;
1031 : 643 : TREE_STATIC (ctor) = true;
1032 : :
1033 : 643 : decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
1034 : 643 : TREE_STATIC (decl) = 1;
1035 : 643 : DECL_INITIAL (decl) = ctor;
1036 : :
1037 : 643 : DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
1038 : 643 : DECL_ARTIFICIAL (decl) = 1;
1039 : 643 : DECL_IGNORED_P (decl) = 1;
1040 : 643 : TREE_CONSTANT (decl) = 1;
1041 : 643 : TREE_READONLY (decl) = 1;
1042 : 643 : DECL_IGNORED_P (decl) = 1;
1043 : : /* The decl is mergeable since we don't take the address ever and
1044 : : just reading from it. */
1045 : 643 : DECL_MERGEABLE (decl) = 1;
1046 : :
1047 : 643 : if (offloading_function_p (cfun->decl))
1048 : 0 : DECL_ATTRIBUTES (decl)
1049 : 0 : = tree_cons (get_identifier ("omp declare target"), NULL_TREE,
1050 : : NULL_TREE);
1051 : 643 : varpool_node::finalize_decl (decl);
1052 : :
1053 : 643 : fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
1054 : : NULL_TREE);
1055 : 643 : if (default_type != value_type)
1056 : : {
1057 : 114 : fetch = fold_convert (default_type, fetch);
1058 : 114 : fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
1059 : : true, GSI_SAME_STMT);
1060 : : }
1061 : 643 : load = gimple_build_assign (name, fetch);
1062 : : }
1063 : :
1064 : 744 : gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1065 : 744 : update_stmt (load);
1066 : 744 : m_arr_ref_last = load;
1067 : 744 : }
1068 : :
1069 : : /* Builds and initializes static arrays initialized with values gathered from
1070 : : the switch statement. Also creates statements that load values from
1071 : : them. */
1072 : :
1073 : : void
1074 : 689 : switch_conversion::build_arrays ()
1075 : : {
1076 : 689 : tree arr_index_type;
1077 : 689 : tree tidx, uidx, sub, utype, tidxtype;
1078 : 689 : gimple *stmt;
1079 : 689 : gimple_stmt_iterator gsi;
1080 : 689 : gphi_iterator gpi;
1081 : 689 : int i;
1082 : 689 : location_t loc = gimple_location (m_switch);
1083 : :
1084 : 689 : gsi = gsi_for_stmt (m_switch);
1085 : :
1086 : : /* Make sure we do not generate arithmetics in a subrange. */
1087 : 689 : utype = TREE_TYPE (m_index_expr);
1088 : 689 : if (TREE_TYPE (utype))
1089 : 46 : utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
1090 : 643 : else if (TREE_CODE (utype) == BITINT_TYPE
1091 : 644 : && (TYPE_PRECISION (utype) > MAX_FIXED_MODE_SIZE
1092 : 0 : || TYPE_MODE (utype) == BLKmode))
1093 : 1 : utype = unsigned_type_for (utype);
1094 : : else
1095 : 642 : utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
1096 : 689 : if (TYPE_PRECISION (utype) > TYPE_PRECISION (sizetype))
1097 : 11 : tidxtype = sizetype;
1098 : : else
1099 : : tidxtype = utype;
1100 : :
1101 : 689 : arr_index_type = build_index_type (m_range_size);
1102 : 689 : uidx = make_ssa_name (utype);
1103 : 689 : sub = fold_build2_loc (loc, MINUS_EXPR, utype,
1104 : : fold_convert_loc (loc, utype, m_index_expr),
1105 : : fold_convert_loc (loc, utype, m_range_min));
1106 : 689 : sub = force_gimple_operand_gsi (&gsi, sub,
1107 : : false, NULL, true, GSI_SAME_STMT);
1108 : 689 : stmt = gimple_build_assign (uidx, sub);
1109 : :
1110 : 689 : gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1111 : 689 : m_arr_ref_first = stmt;
1112 : :
1113 : 689 : tidx = uidx;
1114 : 689 : if (tidxtype != utype)
1115 : : {
1116 : 11 : tidx = make_ssa_name (tidxtype);
1117 : 11 : stmt = gimple_build_assign (tidx, NOP_EXPR, uidx);
1118 : 11 : gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1119 : : }
1120 : :
1121 : 689 : for (gpi = gsi_start_phis (m_final_bb), i = 0;
1122 : 1453 : !gsi_end_p (gpi); gsi_next (&gpi))
1123 : : {
1124 : 764 : gphi *phi = gpi.phi ();
1125 : 1528 : if (!virtual_operand_p (gimple_phi_result (phi)))
1126 : 744 : build_one_array (i++, arr_index_type, phi, tidx);
1127 : : else
1128 : : {
1129 : 20 : edge e;
1130 : 20 : edge_iterator ei;
1131 : 24 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
1132 : : {
1133 : 24 : if (e->dest == m_final_bb)
1134 : : break;
1135 : 14 : if (!m_default_case_nonstandard
1136 : 4 : || e->dest != m_default_bb)
1137 : : {
1138 : 10 : e = single_succ_edge (e->dest);
1139 : 10 : break;
1140 : : }
1141 : : }
1142 : 20 : gcc_assert (e && e->dest == m_final_bb);
1143 : 20 : m_target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
1144 : : }
1145 : : }
1146 : 689 : }
1147 : :
1148 : : /* Generates and appropriately inserts loads of default values at the position
1149 : : given by GSI. Returns the last inserted statement. */
1150 : :
1151 : : gassign *
1152 : 585 : switch_conversion::gen_def_assigns (gimple_stmt_iterator *gsi)
1153 : : {
1154 : 585 : int i;
1155 : 585 : gassign *assign = NULL;
1156 : :
1157 : 1213 : for (i = 0; i < m_phi_count; i++)
1158 : : {
1159 : 628 : tree name = copy_ssa_name (m_target_inbound_names[i]);
1160 : 628 : m_target_outbound_names[i] = name;
1161 : 628 : assign = gimple_build_assign (name, m_default_values[i]);
1162 : 628 : gsi_insert_before (gsi, assign, GSI_SAME_STMT);
1163 : 628 : update_stmt (assign);
1164 : : }
1165 : 585 : return assign;
1166 : : }
1167 : :
1168 : : /* Deletes the unused bbs and edges that now contain the switch statement and
1169 : : its empty branch bbs. BBD is the now dead BB containing
1170 : : the original switch statement, FINAL is the last BB of the converted
1171 : : switch statement (in terms of succession). */
1172 : :
1173 : : void
1174 : 689 : switch_conversion::prune_bbs (basic_block bbd, basic_block final,
1175 : : basic_block default_bb)
1176 : : {
1177 : 689 : edge_iterator ei;
1178 : 689 : edge e;
1179 : :
1180 : 10087 : for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
1181 : : {
1182 : 8709 : basic_block bb;
1183 : 8709 : bb = e->dest;
1184 : 8709 : remove_edge (e);
1185 : 8709 : if (bb != final && bb != default_bb)
1186 : 7927 : delete_basic_block (bb);
1187 : : }
1188 : 689 : delete_basic_block (bbd);
1189 : 689 : }
1190 : :
1191 : : /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
1192 : : from the basic block loading values from an array and E2F from the basic
1193 : : block loading default values. BBF is the last switch basic block (see the
1194 : : bbf description in the comment below). */
1195 : :
1196 : : void
1197 : 689 : switch_conversion::fix_phi_nodes (edge e1f, edge e2f, basic_block bbf)
1198 : : {
1199 : 689 : gphi_iterator gsi;
1200 : 689 : int i;
1201 : :
1202 : 689 : for (gsi = gsi_start_phis (bbf), i = 0;
1203 : 1453 : !gsi_end_p (gsi); gsi_next (&gsi))
1204 : : {
1205 : 764 : gphi *phi = gsi.phi ();
1206 : 764 : tree inbound, outbound;
1207 : 1528 : if (virtual_operand_p (gimple_phi_result (phi)))
1208 : 20 : inbound = outbound = m_target_vop;
1209 : : else
1210 : : {
1211 : 744 : inbound = m_target_inbound_names[i];
1212 : 744 : outbound = m_target_outbound_names[i++];
1213 : : }
1214 : 764 : add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
1215 : 764 : if (!m_default_case_nonstandard)
1216 : 644 : add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
1217 : : }
1218 : 689 : }
1219 : :
1220 : : /* Creates a check whether the switch expression value actually falls into the
1221 : : range given by all the cases. If it does not, the temporaries are loaded
1222 : : with default values instead. */
1223 : :
1224 : : void
1225 : 689 : switch_conversion::gen_inbound_check ()
1226 : : {
1227 : 689 : tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
1228 : 689 : tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
1229 : 689 : tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
1230 : 689 : glabel *label1, *label2, *label3;
1231 : 689 : tree utype, tidx;
1232 : 689 : tree bound;
1233 : :
1234 : 689 : gcond *cond_stmt;
1235 : :
1236 : 689 : gassign *last_assign = NULL;
1237 : 689 : gimple_stmt_iterator gsi;
1238 : 689 : basic_block bb0, bb1, bb2, bbf, bbd;
1239 : 689 : edge e01 = NULL, e02, e21, e1d, e1f, e2f;
1240 : 689 : location_t loc = gimple_location (m_switch);
1241 : :
1242 : 689 : gcc_assert (m_default_values);
1243 : :
1244 : 689 : bb0 = gimple_bb (m_switch);
1245 : :
1246 : 689 : tidx = gimple_assign_lhs (m_arr_ref_first);
1247 : 689 : utype = TREE_TYPE (tidx);
1248 : :
1249 : : /* (end of) block 0 */
1250 : 689 : gsi = gsi_for_stmt (m_arr_ref_first);
1251 : 689 : gsi_next (&gsi);
1252 : :
1253 : 689 : bound = fold_convert_loc (loc, utype, m_range_size);
1254 : 689 : cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
1255 : 689 : gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
1256 : 689 : update_stmt (cond_stmt);
1257 : :
1258 : : /* block 2 */
1259 : 689 : if (!m_default_case_nonstandard)
1260 : : {
1261 : 585 : label2 = gimple_build_label (label_decl2);
1262 : 585 : gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
1263 : 585 : last_assign = gen_def_assigns (&gsi);
1264 : : }
1265 : :
1266 : : /* block 1 */
1267 : 689 : label1 = gimple_build_label (label_decl1);
1268 : 689 : gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
1269 : :
1270 : : /* block F */
1271 : 689 : gsi = gsi_start_bb (m_final_bb);
1272 : 689 : label3 = gimple_build_label (label_decl3);
1273 : 689 : gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
1274 : :
1275 : : /* cfg fix */
1276 : 689 : e02 = split_block (bb0, cond_stmt);
1277 : 689 : bb2 = e02->dest;
1278 : :
1279 : 689 : if (m_default_case_nonstandard)
1280 : : {
1281 : 104 : bb1 = bb2;
1282 : 104 : bb2 = m_default_bb;
1283 : 104 : e01 = e02;
1284 : 104 : e01->flags = EDGE_TRUE_VALUE;
1285 : 104 : e02 = make_edge (bb0, bb2, EDGE_FALSE_VALUE);
1286 : 104 : edge e_default = find_edge (bb1, bb2);
1287 : 104 : for (gphi_iterator gsi = gsi_start_phis (bb2);
1288 : 141 : !gsi_end_p (gsi); gsi_next (&gsi))
1289 : : {
1290 : 37 : gphi *phi = gsi.phi ();
1291 : 37 : tree arg = PHI_ARG_DEF_FROM_EDGE (phi, e_default);
1292 : 37 : add_phi_arg (phi, arg, e02,
1293 : : gimple_phi_arg_location_from_edge (phi, e_default));
1294 : : }
1295 : : /* Partially fix the dominator tree, if it is available. */
1296 : 104 : if (dom_info_available_p (CDI_DOMINATORS))
1297 : 104 : redirect_immediate_dominators (CDI_DOMINATORS, bb1, bb0);
1298 : : }
1299 : : else
1300 : : {
1301 : 585 : e21 = split_block (bb2, last_assign);
1302 : 585 : bb1 = e21->dest;
1303 : 585 : remove_edge (e21);
1304 : : }
1305 : :
1306 : 689 : e1d = split_block (bb1, m_arr_ref_last);
1307 : 689 : bbd = e1d->dest;
1308 : 689 : remove_edge (e1d);
1309 : :
1310 : : /* Flags and profiles of the edge for in-range values. */
1311 : 689 : if (!m_default_case_nonstandard)
1312 : 585 : e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
1313 : 689 : e01->probability = m_default_prob.invert ();
1314 : :
1315 : : /* Flags and profiles of the edge taking care of out-of-range values. */
1316 : 689 : e02->flags &= ~EDGE_FALLTHRU;
1317 : 689 : e02->flags |= EDGE_FALSE_VALUE;
1318 : 689 : e02->probability = m_default_prob;
1319 : :
1320 : 689 : bbf = m_final_bb;
1321 : :
1322 : 689 : e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
1323 : 689 : e1f->probability = profile_probability::always ();
1324 : :
1325 : 689 : if (m_default_case_nonstandard)
1326 : : e2f = NULL;
1327 : : else
1328 : : {
1329 : 585 : e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
1330 : 585 : e2f->probability = profile_probability::always ();
1331 : : }
1332 : :
1333 : : /* frequencies of the new BBs */
1334 : 689 : bb1->count = e01->count ();
1335 : 689 : bb2->count = e02->count ();
1336 : 689 : if (!m_default_case_nonstandard)
1337 : 585 : bbf->count = e1f->count () + e2f->count ();
1338 : :
1339 : : /* Tidy blocks that have become unreachable. */
1340 : 1503 : bool prune_default_bb = !m_default_case_nonstandard
1341 : 689 : && !m_exp_index_transform_applied;
1342 : 689 : prune_bbs (bbd, m_final_bb, prune_default_bb ? NULL : m_default_bb);
1343 : :
1344 : : /* Fixup the PHI nodes in bbF. */
1345 : 689 : fix_phi_nodes (e1f, e2f, bbf);
1346 : :
1347 : : /* Fix the dominator tree, if it is available. */
1348 : 689 : if (dom_info_available_p (CDI_DOMINATORS))
1349 : : {
1350 : 689 : vec<basic_block> bbs_to_fix_dom;
1351 : :
1352 : 689 : set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
1353 : 689 : if (!m_default_case_nonstandard)
1354 : 585 : set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
1355 : 689 : if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
1356 : : /* If bbD was the immediate dominator ... */
1357 : 458 : set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
1358 : :
1359 : 704 : bbs_to_fix_dom.create (3 + (bb2 != bbf));
1360 : 689 : bbs_to_fix_dom.quick_push (bb0);
1361 : 689 : bbs_to_fix_dom.quick_push (bb1);
1362 : 689 : if (bb2 != bbf)
1363 : 674 : bbs_to_fix_dom.quick_push (bb2);
1364 : 689 : bbs_to_fix_dom.quick_push (bbf);
1365 : :
1366 : 689 : iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
1367 : 689 : bbs_to_fix_dom.release ();
1368 : : }
1369 : 689 : }
1370 : :
1371 : : /* The following function is invoked on every switch statement (the current
1372 : : one is given in SWTCH) and runs the individual phases of switch
1373 : : conversion on it one after another until one fails or the conversion
1374 : : is completed. On success, NULL is in m_reason, otherwise points
1375 : : to a string with the reason why the conversion failed. */
1376 : :
1377 : : void
1378 : 29447 : switch_conversion::expand (gswitch *swtch)
1379 : : {
1380 : : /* Group case labels so that we get the right results from the heuristics
1381 : : that decide on the code generation approach for this switch. */
1382 : 29447 : m_cfg_altered |= group_case_labels_stmt (swtch);
1383 : :
1384 : : /* If this switch is now a degenerate case with only a default label,
1385 : : there is nothing left for us to do. */
1386 : 29447 : if (gimple_switch_num_labels (swtch) < 2)
1387 : : {
1388 : 0 : m_reason = "switch is a degenerate case";
1389 : 0 : return;
1390 : : }
1391 : :
1392 : 29447 : collect (swtch);
1393 : :
1394 : : /* No error markers should reach here (they should be filtered out
1395 : : during gimplification). */
1396 : 29447 : gcc_checking_assert (TREE_TYPE (m_index_expr) != error_mark_node);
1397 : :
1398 : : /* Prefer bit test if possible. */
1399 : 29447 : if (tree_fits_uhwi_p (m_range_size)
1400 : 29377 : && bit_test_cluster::can_be_handled (tree_to_uhwi (m_range_size), m_uniq)
1401 : 44612 : && bit_test_cluster::is_beneficial (m_count, m_uniq))
1402 : : {
1403 : 3060 : m_reason = "expanding as bit test is preferable";
1404 : 3060 : return;
1405 : : }
1406 : :
1407 : 26387 : if (m_uniq <= 2)
1408 : : {
1409 : : /* This will be expanded as a decision tree . */
1410 : 8032 : m_reason = "expanding as jumps is preferable";
1411 : 8032 : return;
1412 : : }
1413 : :
1414 : : /* If there is no common successor, we cannot do the transformation. */
1415 : 18355 : if (!m_final_bb)
1416 : : {
1417 : 10906 : m_reason = "no common successor to all case label target blocks found";
1418 : 10906 : return;
1419 : : }
1420 : :
1421 : : /* Sometimes it is possible to use the "exponential index transform" to help
1422 : : switch conversion convert switches which it otherwise could not convert.
1423 : : However, we want to do this transform only when we know that switch
1424 : : conversion will then really be able to convert the switch. So we first
1425 : : check if the transformation is applicable and then maybe later do the
1426 : : transformation. */
1427 : 7449 : bool exp_transform_viable = is_exp_index_transform_viable (swtch);
1428 : :
1429 : : /* Check the case label values are within reasonable range.
1430 : :
1431 : : If we will be doing exponential index transform, the range will be always
1432 : : reasonable. */
1433 : 7449 : if (!exp_transform_viable && !check_range ())
1434 : : {
1435 : 766 : gcc_assert (m_reason);
1436 : : return;
1437 : : }
1438 : :
1439 : : /* For all the cases, see whether they are empty, the assignments they
1440 : : represent constant and so on... */
1441 : 6683 : if (!check_all_empty_except_final ())
1442 : : {
1443 : 5907 : gcc_assert (m_reason);
1444 : : return;
1445 : : }
1446 : 776 : if (!check_final_bb ())
1447 : : {
1448 : 87 : gcc_assert (m_reason);
1449 : : return;
1450 : : }
1451 : :
1452 : : /* At this point all checks have passed and we can proceed with the
1453 : : transformation. */
1454 : :
1455 : 689 : if (exp_transform_viable)
1456 : 21 : exp_index_transform (swtch);
1457 : :
1458 : 689 : create_temp_arrays ();
1459 : 1378 : gather_default_values (m_default_case_nonstandard
1460 : 104 : ? gimple_switch_label (swtch, 1)
1461 : 585 : : gimple_switch_default_label (swtch));
1462 : 689 : build_constructors ();
1463 : :
1464 : 689 : build_arrays (); /* Build the static arrays and assignments. */
1465 : 689 : gen_inbound_check (); /* Build the bounds check. */
1466 : :
1467 : 689 : m_cfg_altered = true;
1468 : : }
1469 : :
1470 : : /* Destructor. */
1471 : :
1472 : 29447 : switch_conversion::~switch_conversion ()
1473 : : {
1474 : 29447 : XDELETEVEC (m_constructors);
1475 : 29447 : XDELETEVEC (m_default_values);
1476 : 29447 : }
1477 : :
1478 : : /* Constructor. */
1479 : :
1480 : 14736 : group_cluster::group_cluster (vec<cluster *> &clusters,
1481 : 14736 : unsigned start, unsigned end)
1482 : : {
1483 : 14736 : gcc_checking_assert (end - start + 1 >= 1);
1484 : 14736 : m_prob = profile_probability::never ();
1485 : 14736 : m_cases.create (end - start + 1);
1486 : 127074 : for (unsigned i = start; i <= end; i++)
1487 : : {
1488 : 112338 : m_cases.quick_push (static_cast<simple_cluster *> (clusters[i]));
1489 : 112338 : m_prob += clusters[i]->m_prob;
1490 : : }
1491 : 14736 : m_subtree_prob = m_prob;
1492 : 14736 : }
1493 : :
1494 : : /* Destructor. */
1495 : :
1496 : 14736 : group_cluster::~group_cluster ()
1497 : : {
1498 : 127074 : for (unsigned i = 0; i < m_cases.length (); i++)
1499 : 112338 : delete m_cases[i];
1500 : :
1501 : 14736 : m_cases.release ();
1502 : 14736 : }
1503 : :
1504 : : /* Dump content of a cluster. */
1505 : :
1506 : : void
1507 : 28 : group_cluster::dump (FILE *f, bool details)
1508 : : {
1509 : 28 : unsigned total_values = 0;
1510 : 390 : for (unsigned i = 0; i < m_cases.length (); i++)
1511 : 334 : total_values += m_cases[i]->get_range (m_cases[i]->get_low (),
1512 : 167 : m_cases[i]->get_high ());
1513 : :
1514 : : unsigned comparison_count = 0;
1515 : 195 : for (unsigned i = 0; i < m_cases.length (); i++)
1516 : : {
1517 : 167 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1518 : 279 : comparison_count += sc->get_comparison_count ();
1519 : : }
1520 : :
1521 : 28 : unsigned HOST_WIDE_INT range = get_range (get_low (), get_high ());
1522 : 46 : fprintf (f, "%s", get_type () == JUMP_TABLE ? "JT" : "BT");
1523 : :
1524 : 28 : if (details)
1525 : 0 : fprintf (f, "(values:%d comparisons:%d range:" HOST_WIDE_INT_PRINT_DEC
1526 : : " density: %.2f%%)", total_values, comparison_count, range,
1527 : 0 : 100.0f * comparison_count / range);
1528 : :
1529 : 28 : fprintf (f, ":");
1530 : 28 : PRINT_CASE (f, get_low ());
1531 : 28 : fprintf (f, "-");
1532 : 28 : PRINT_CASE (f, get_high ());
1533 : 28 : fprintf (f, " ");
1534 : 28 : }
1535 : :
1536 : : /* Emit GIMPLE code to handle the cluster. */
1537 : :
1538 : : void
1539 : 8572 : jump_table_cluster::emit (tree index_expr, tree,
1540 : : tree default_label_expr, basic_block default_bb,
1541 : : location_t loc)
1542 : : {
1543 : 8572 : tree low = get_low ();
1544 : 8572 : unsigned HOST_WIDE_INT range = get_range (low, get_high ());
1545 : 8572 : unsigned HOST_WIDE_INT nondefault_range = 0;
1546 : 8572 : bool bitint = false;
1547 : 8572 : gimple_stmt_iterator gsi = gsi_start_bb (m_case_bb);
1548 : :
1549 : : /* For large/huge _BitInt, subtract low from index_expr, cast to unsigned
1550 : : DImode type (get_range doesn't support ranges larger than 64-bits)
1551 : : and subtract low from all case values as well. */
1552 : 8572 : if (TREE_CODE (TREE_TYPE (index_expr)) == BITINT_TYPE
1553 : 8572 : && TYPE_PRECISION (TREE_TYPE (index_expr)) > GET_MODE_PRECISION (DImode))
1554 : : {
1555 : 2 : bitint = true;
1556 : 2 : tree this_low = low, type;
1557 : 2 : gimple *g;
1558 : 2 : gimple_seq seq = NULL;
1559 : 2 : if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (index_expr)))
1560 : : {
1561 : 1 : type = unsigned_type_for (TREE_TYPE (index_expr));
1562 : 1 : index_expr = gimple_convert (&seq, type, index_expr);
1563 : 1 : this_low = fold_convert (type, this_low);
1564 : : }
1565 : 2 : this_low = const_unop (NEGATE_EXPR, TREE_TYPE (this_low), this_low);
1566 : 2 : index_expr = gimple_build (&seq, PLUS_EXPR, TREE_TYPE (index_expr),
1567 : : index_expr, this_low);
1568 : 2 : type = build_nonstandard_integer_type (GET_MODE_PRECISION (DImode), 1);
1569 : 2 : g = gimple_build_cond (GT_EXPR, index_expr,
1570 : 2 : fold_convert (TREE_TYPE (index_expr),
1571 : : TYPE_MAX_VALUE (type)),
1572 : : NULL_TREE, NULL_TREE);
1573 : 2 : gimple_seq_add_stmt (&seq, g);
1574 : 2 : gimple_seq_set_location (seq, loc);
1575 : 2 : gsi_insert_seq_after (&gsi, seq, GSI_NEW_STMT);
1576 : 2 : edge e1 = split_block (m_case_bb, g);
1577 : 2 : e1->flags = EDGE_FALSE_VALUE;
1578 : 2 : e1->probability = profile_probability::likely ();
1579 : 2 : edge e2 = make_edge (e1->src, default_bb, EDGE_TRUE_VALUE);
1580 : 2 : e2->probability = e1->probability.invert ();
1581 : 2 : gsi = gsi_start_bb (e1->dest);
1582 : 2 : seq = NULL;
1583 : 2 : index_expr = gimple_convert (&seq, type, index_expr);
1584 : 2 : gimple_seq_set_location (seq, loc);
1585 : 2 : gsi_insert_seq_after (&gsi, seq, GSI_NEW_STMT);
1586 : : }
1587 : :
1588 : : /* For jump table we just emit a new gswitch statement that will
1589 : : be latter lowered to jump table. */
1590 : 8572 : auto_vec <tree> labels;
1591 : 17144 : labels.create (m_cases.length ());
1592 : :
1593 : 8572 : basic_block case_bb = gsi_bb (gsi);
1594 : 8572 : make_edge (case_bb, default_bb, 0);
1595 : 93885 : for (unsigned i = 0; i < m_cases.length (); i++)
1596 : : {
1597 : 85313 : tree lab = unshare_expr (m_cases[i]->m_case_label_expr);
1598 : 85313 : if (bitint)
1599 : : {
1600 : 13 : CASE_LOW (lab)
1601 : 13 : = fold_convert (TREE_TYPE (index_expr),
1602 : : const_binop (MINUS_EXPR,
1603 : : TREE_TYPE (CASE_LOW (lab)),
1604 : : CASE_LOW (lab), low));
1605 : 13 : if (CASE_HIGH (lab))
1606 : 0 : CASE_HIGH (lab)
1607 : 0 : = fold_convert (TREE_TYPE (index_expr),
1608 : : const_binop (MINUS_EXPR,
1609 : : TREE_TYPE (CASE_HIGH (lab)),
1610 : : CASE_HIGH (lab), low));
1611 : : }
1612 : 85313 : labels.quick_push (lab);
1613 : 85313 : make_edge (case_bb, m_cases[i]->m_case_bb, 0);
1614 : : }
1615 : :
1616 : 8572 : gswitch *s = gimple_build_switch (index_expr,
1617 : : unshare_expr (default_label_expr), labels);
1618 : 8572 : gimple_set_location (s, loc);
1619 : 8572 : gsi_insert_after (&gsi, s, GSI_NEW_STMT);
1620 : :
1621 : : /* Set up even probabilities for all cases. */
1622 : 93885 : for (unsigned i = 0; i < m_cases.length (); i++)
1623 : : {
1624 : 85313 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1625 : 85313 : edge case_edge = find_edge (case_bb, sc->m_case_bb);
1626 : 85313 : unsigned HOST_WIDE_INT case_range
1627 : 85313 : = sc->get_range (sc->get_low (), sc->get_high ());
1628 : 85313 : nondefault_range += case_range;
1629 : :
1630 : : /* case_edge->aux is number of values in a jump-table that are covered
1631 : : by the case_edge. */
1632 : 85313 : case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + case_range);
1633 : : }
1634 : :
1635 : 8572 : edge default_edge = gimple_switch_default_edge (cfun, s);
1636 : 8572 : default_edge->probability = profile_probability::never ();
1637 : :
1638 : 93885 : for (unsigned i = 0; i < m_cases.length (); i++)
1639 : : {
1640 : 85313 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1641 : 85313 : edge case_edge = find_edge (case_bb, sc->m_case_bb);
1642 : 85313 : case_edge->probability
1643 : 85313 : = profile_probability::always ().apply_scale ((intptr_t)case_edge->aux,
1644 : : range);
1645 : : }
1646 : :
1647 : : /* Number of non-default values is probability of default edge. */
1648 : 8572 : default_edge->probability
1649 : 8572 : += profile_probability::always ().apply_scale (nondefault_range,
1650 : 8572 : range).invert ();
1651 : :
1652 : 8572 : switch_decision_tree::reset_out_edges_aux (s);
1653 : 8572 : }
1654 : :
1655 : : /* Find jump tables of given CLUSTERS, where all members of the vector
1656 : : are of type simple_cluster. New clusters are returned. */
1657 : :
1658 : : vec<cluster *>
1659 : 74334 : jump_table_cluster::find_jump_tables (vec<cluster *> &clusters)
1660 : : {
1661 : 74334 : if (!is_enabled ())
1662 : 15275 : return clusters.copy ();
1663 : :
1664 : 59059 : unsigned l = clusters.length ();
1665 : :
1666 : 59059 : auto_vec<min_cluster_item> min;
1667 : 59059 : min.reserve (l + 1);
1668 : :
1669 : 59059 : min.quick_push (min_cluster_item (0, 0, 0));
1670 : :
1671 : 59059 : unsigned HOST_WIDE_INT max_ratio
1672 : 59059 : = (optimize_insn_for_size_p ()
1673 : 59059 : ? param_jump_table_max_growth_ratio_for_size
1674 : 59059 : : param_jump_table_max_growth_ratio_for_speed);
1675 : :
1676 : 272414 : for (unsigned i = 1; i <= l; i++)
1677 : : {
1678 : : /* Set minimal # of clusters with i-th item to infinite. */
1679 : 213355 : min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1680 : :
1681 : : /* Pre-calculate number of comparisons for the clusters. */
1682 : 213355 : HOST_WIDE_INT comparison_count = 0;
1683 : 7024930 : for (unsigned k = 0; k <= i - 1; k++)
1684 : : {
1685 : 6811575 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[k]);
1686 : 13436279 : comparison_count += sc->get_comparison_count ();
1687 : : }
1688 : :
1689 : 7024930 : for (unsigned j = 0; j < i; j++)
1690 : : {
1691 : 6811575 : unsigned HOST_WIDE_INT s = min[j].m_non_jt_cases;
1692 : 13622786 : if (i - j < case_values_threshold ())
1693 : 537770 : s += i - j;
1694 : :
1695 : : /* Prefer clusters with smaller number of numbers covered. */
1696 : 6811575 : if ((min[j].m_count + 1 < min[i].m_count
1697 : 1859143 : || (min[j].m_count + 1 == min[i].m_count
1698 : 971 : && s < min[i].m_non_jt_cases))
1699 : 6811612 : && can_be_handled (clusters, j, i - 1, max_ratio,
1700 : : comparison_count))
1701 : 213381 : min[i] = min_cluster_item (min[j].m_count + 1, j, s);
1702 : :
1703 : 6811575 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[j]);
1704 : 13436279 : comparison_count -= sc->get_comparison_count ();
1705 : : }
1706 : :
1707 : 213355 : gcc_checking_assert (comparison_count == 0);
1708 : 213355 : gcc_checking_assert (min[i].m_count != INT_MAX);
1709 : : }
1710 : :
1711 : : /* No result. */
1712 : 59059 : if (min[l].m_count == l)
1713 : 8500 : return clusters.copy ();
1714 : :
1715 : 50559 : vec<cluster *> output;
1716 : 50559 : output.create (4);
1717 : :
1718 : : /* Find and build the clusters. */
1719 : 50559 : for (unsigned int end = l;;)
1720 : : {
1721 : 57606 : int start = min[end].m_start;
1722 : :
1723 : : /* Do not allow clusters with small number of cases. */
1724 : 57606 : if (is_beneficial (clusters, start, end - 1))
1725 : 9347 : output.safe_push (new jump_table_cluster (clusters, start, end - 1));
1726 : : else
1727 : 149991 : for (int i = end - 1; i >= start; i--)
1728 : 101732 : output.safe_push (clusters[i]);
1729 : :
1730 : 57606 : end = start;
1731 : :
1732 : 57606 : if (start <= 0)
1733 : : break;
1734 : : }
1735 : :
1736 : 50559 : output.reverse ();
1737 : 50559 : return output;
1738 : 59059 : }
1739 : :
1740 : : /* Return true when cluster starting at START and ending at END (inclusive)
1741 : : can build a jump-table. */
1742 : :
1743 : : bool
1744 : 4952469 : jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1745 : : unsigned start, unsigned end,
1746 : : unsigned HOST_WIDE_INT max_ratio,
1747 : : unsigned HOST_WIDE_INT comparison_count)
1748 : : {
1749 : : /* If the switch is relatively small such that the cost of one
1750 : : indirect jump on the target are higher than the cost of a
1751 : : decision tree, go with the decision tree.
1752 : :
1753 : : If range of values is much bigger than number of values,
1754 : : or if it is too large to represent in a HOST_WIDE_INT,
1755 : : make a sequence of conditional branches instead of a dispatch.
1756 : :
1757 : : The definition of "much bigger" depends on whether we are
1758 : : optimizing for size or for speed.
1759 : :
1760 : : For algorithm correctness, jump table for a single case must return
1761 : : true. We bail out in is_beneficial if it's called just for
1762 : : a single case. */
1763 : 4952469 : if (start == end)
1764 : : return true;
1765 : :
1766 : 9746322 : unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1767 : 4873161 : clusters[end]->get_high ());
1768 : : /* Check overflow. */
1769 : 4873161 : if (range == 0)
1770 : : return false;
1771 : :
1772 : 4869857 : if (range > HOST_WIDE_INT_M1U / 100)
1773 : : return false;
1774 : :
1775 : 659699 : unsigned HOST_WIDE_INT lhs = 100 * range;
1776 : 659699 : if (lhs < range)
1777 : : return false;
1778 : :
1779 : 659699 : return lhs <= max_ratio * comparison_count;
1780 : : }
1781 : :
1782 : : /* Return true if cluster starting at START and ending at END (inclusive)
1783 : : is profitable transformation. */
1784 : :
1785 : : bool
1786 : 57606 : jump_table_cluster::is_beneficial (const vec<cluster *> &,
1787 : : unsigned start, unsigned end)
1788 : : {
1789 : : /* Single case bail out. */
1790 : 57606 : if (start == end)
1791 : : return false;
1792 : :
1793 : 102546 : return end - start + 1 >= case_values_threshold ();
1794 : : }
1795 : :
1796 : : /* Find bit tests of given CLUSTERS, where all members of the vector
1797 : : are of type simple_cluster. MAX_C is the approx max number of cases per
1798 : : label. New clusters are returned. */
1799 : :
1800 : : vec<cluster *>
1801 : 75827 : bit_test_cluster::find_bit_tests (vec<cluster *> &clusters, int max_c)
1802 : : {
1803 : 75827 : if (!is_enabled () || max_c == 1)
1804 : 37526 : return clusters.copy ();
1805 : :
1806 : : /* Dynamic programming algorithm.
1807 : :
1808 : : In: List of simple clusters
1809 : : Out: List of simple clusters and bit test clusters such that each bit test
1810 : : cluster can_be_handled() and is_beneficial()
1811 : :
1812 : : Tries to merge consecutive clusters into bigger (bit test) ones. Tries to
1813 : : end up with as few clusters as possible. */
1814 : :
1815 : 38301 : unsigned l = clusters.length ();
1816 : :
1817 : 38300 : if (l == 0)
1818 : 1 : return clusters.copy ();
1819 : 38300 : gcc_checking_assert (l <= INT_MAX);
1820 : :
1821 : 38300 : auto_vec<min_cluster_item> min;
1822 : 38300 : min.reserve (l + 1);
1823 : :
1824 : 38300 : int bits_in_word = GET_MODE_BITSIZE (word_mode);
1825 : :
1826 : : /* First phase: Compute the minimum number of clusters for each prefix of the
1827 : : input list incrementally
1828 : :
1829 : : min[i] = (count, j, _) means that the prefix ending with the (i-1)-th
1830 : : element can be made to contain as few as count clusters and that in such
1831 : : clustering the last cluster is made up of input clusters [j, i-1]
1832 : : (inclusive). */
1833 : 38300 : min.quick_push (min_cluster_item (0, 0, INT_MAX));
1834 : 38300 : min.quick_push (min_cluster_item (1, 0, INT_MAX));
1835 : 131784 : for (int i = 2; i <= (int) l; i++)
1836 : : {
1837 : 93484 : auto_vec<unsigned, m_max_case_bit_tests> unique_labels;
1838 : :
1839 : : /* Since each cluster contains at least one case number and one bit test
1840 : : cluster can cover at most bits_in_word case numbers, we don't need to
1841 : : look farther than bits_in_word clusters back. */
1842 : 385366 : for (int j = i - 1; j >= 0 && j >= i - bits_in_word; j--)
1843 : : {
1844 : : /* Consider creating a bit test cluster from input clusters [j, i-1]
1845 : : (inclusive) */
1846 : :
1847 : 323035 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[j]);
1848 : 323035 : unsigned label = sc->m_case_bb->index;
1849 : 323035 : if (!unique_labels.contains (label))
1850 : : {
1851 : 240726 : if (unique_labels.length () >= m_max_case_bit_tests)
1852 : : /* is_beneficial() will be false for this and the following
1853 : : iterations. */
1854 : : break;
1855 : 209573 : unique_labels.quick_push (label);
1856 : : }
1857 : :
1858 : 291882 : unsigned new_count = min[j].m_count + 1;
1859 : :
1860 : 291882 : if (j == i - 1)
1861 : : {
1862 : 93484 : min.quick_push (min_cluster_item (new_count, j, INT_MAX));
1863 : 93484 : continue;
1864 : : }
1865 : :
1866 : 198398 : unsigned HOST_WIDE_INT range
1867 : 198398 : = get_range (clusters[j]->get_low (), clusters[i-1]->get_high ());
1868 : 198398 : if (new_count < min[i].m_count
1869 : 176309 : && can_be_handled (range, unique_labels.length ())
1870 : 343421 : && is_beneficial (i - j, unique_labels.length ()))
1871 : 9407 : min[i] = min_cluster_item (new_count, j, INT_MAX);
1872 : : }
1873 : 93484 : }
1874 : :
1875 : 38300 : if (min[l].m_count == l)
1876 : : /* No bit test clustering opportunities. */
1877 : 33446 : return clusters.copy ();
1878 : :
1879 : 4854 : vec<cluster *> output;
1880 : 4854 : output.create (4);
1881 : :
1882 : : /* Second phase: Find and build the bit test clusters by traversing min
1883 : : array backwards. */
1884 : 4854 : for (unsigned end = l;;)
1885 : : {
1886 : 9601 : unsigned start = min[end].m_start;
1887 : 9601 : gcc_checking_assert (start < end);
1888 : :
1889 : : /* This cluster will be made out of input clusters [start, end - 1]. */
1890 : :
1891 : 9601 : if (start == end - 1)
1892 : : /* Let the cluster be a simple cluster. */
1893 : 4212 : output.safe_push (clusters[start]);
1894 : : else
1895 : : {
1896 : 5389 : bool entire = start == 0 && end == l;
1897 : 5389 : output.safe_push (new bit_test_cluster (clusters, start, end - 1,
1898 : 5389 : entire));
1899 : : }
1900 : :
1901 : 9601 : end = start;
1902 : :
1903 : 9601 : if (start <= 0)
1904 : : break;
1905 : : }
1906 : :
1907 : 4854 : output.reverse ();
1908 : 4854 : return output;
1909 : 38300 : }
1910 : :
1911 : : /* Return true when RANGE of case values with UNIQ labels
1912 : : can build a bit test. */
1913 : :
1914 : : bool
1915 : 205686 : bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1916 : : unsigned int uniq)
1917 : : {
1918 : : /* Check overflow. */
1919 : 205686 : if (range == 0)
1920 : : return false;
1921 : :
1922 : 407324 : if (range > GET_MODE_BITSIZE (word_mode))
1923 : : return false;
1924 : :
1925 : 171244 : return uniq <= m_max_case_bit_tests;
1926 : : }
1927 : :
1928 : : /* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1929 : : transformation. */
1930 : :
1931 : : bool
1932 : 160188 : bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
1933 : : {
1934 : : /* NOTE: When modifying this, keep in mind the value of
1935 : : m_max_case_bit_tests. */
1936 : 160188 : return (((uniq == 1 && count >= 3)
1937 : 151022 : || (uniq == 2 && count >= 5)
1938 : 309586 : || (uniq == 3 && count >= 6)));
1939 : : }
1940 : :
1941 : : /* Comparison function for qsort to order bit tests by decreasing
1942 : : probability of execution. */
1943 : :
1944 : : int
1945 : 8664 : case_bit_test::cmp (const void *p1, const void *p2)
1946 : : {
1947 : 8664 : const case_bit_test *const d1 = (const case_bit_test *) p1;
1948 : 8664 : const case_bit_test *const d2 = (const case_bit_test *) p2;
1949 : :
1950 : 8664 : if (d2->bits != d1->bits)
1951 : 7619 : return d2->bits - d1->bits;
1952 : :
1953 : : /* Stabilize the sort. */
1954 : 1045 : return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1955 : 1045 : - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1956 : : }
1957 : :
1958 : : /* Expand a switch statement by a short sequence of bit-wise
1959 : : comparisons. "switch(x)" is effectively converted into
1960 : : "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1961 : : integer constants.
1962 : :
1963 : : INDEX_EXPR is the value being switched on.
1964 : :
1965 : : MINVAL is the lowest case value of in the case nodes,
1966 : : and RANGE is highest value minus MINVAL. MINVAL and RANGE
1967 : : are not guaranteed to be of the same type as INDEX_EXPR
1968 : : (the gimplifier doesn't change the type of case label values,
1969 : : and MINVAL and RANGE are derived from those values).
1970 : : MAXVAL is MINVAL + RANGE.
1971 : :
1972 : : There *MUST* be max_case_bit_tests or less unique case
1973 : : node targets. */
1974 : :
1975 : : void
1976 : 4352 : bit_test_cluster::emit (tree index_expr, tree index_type,
1977 : : tree, basic_block default_bb, location_t loc)
1978 : : {
1979 : 26112 : case_bit_test test[m_max_case_bit_tests] = { {} };
1980 : 4352 : unsigned int i, j, k;
1981 : 4352 : unsigned int count;
1982 : :
1983 : 4352 : tree unsigned_index_type = range_check_type (index_type);
1984 : :
1985 : 4352 : gimple_stmt_iterator gsi;
1986 : 4352 : gassign *shift_stmt;
1987 : :
1988 : 4352 : tree idx, tmp, csui;
1989 : 4352 : tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1990 : 4352 : tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1991 : 4352 : tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1992 : 4352 : int prec = TYPE_PRECISION (word_type_node);
1993 : 4352 : wide_int wone = wi::one (prec);
1994 : :
1995 : 4352 : tree minval = get_low ();
1996 : 4352 : tree maxval = get_high ();
1997 : :
1998 : : /* Go through all case labels, and collect the case labels, profile
1999 : : counts, and other information we need to build the branch tests. */
2000 : 4352 : count = 0;
2001 : 22713 : for (i = 0; i < m_cases.length (); i++)
2002 : : {
2003 : 18361 : unsigned int lo, hi;
2004 : 18361 : simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
2005 : 23148 : for (k = 0; k < count; k++)
2006 : 17092 : if (n->m_case_bb == test[k].target_bb)
2007 : : break;
2008 : :
2009 : 18361 : if (k == count)
2010 : : {
2011 : 6056 : gcc_checking_assert (count < m_max_case_bit_tests);
2012 : 6056 : test[k].mask = wi::zero (prec);
2013 : 6056 : test[k].target_bb = n->m_case_bb;
2014 : 6056 : test[k].label = n->m_case_label_expr;
2015 : 6056 : test[k].bits = 0;
2016 : 6056 : test[k].prob = profile_probability::never ();
2017 : 6056 : count++;
2018 : : }
2019 : :
2020 : 18361 : test[k].bits += n->get_range (n->get_low (), n->get_high ());
2021 : 18361 : test[k].prob += n->m_prob;
2022 : :
2023 : 18361 : lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
2024 : 18361 : if (n->get_high () == NULL_TREE)
2025 : : hi = lo;
2026 : : else
2027 : 18361 : hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
2028 : : minval));
2029 : :
2030 : 43298 : for (j = lo; j <= hi; j++)
2031 : 24937 : test[k].mask |= wi::lshift (wone, j);
2032 : : }
2033 : :
2034 : 4352 : qsort (test, count, sizeof (*test), case_bit_test::cmp);
2035 : :
2036 : : /* If every possible relative value of the index expression is a valid shift
2037 : : amount, then we can merge the entry test in the bit test. */
2038 : 4352 : bool entry_test_needed;
2039 : 4352 : int_range_max r;
2040 : 8704 : if (TREE_CODE (index_expr) == SSA_NAME
2041 : 8704 : && get_range_query (cfun)->range_of_expr (r, index_expr)
2042 : 4352 : && !r.undefined_p ()
2043 : 4351 : && !r.varying_p ()
2044 : 10090 : && wi::leu_p (r.upper_bound () - r.lower_bound (), prec - 1))
2045 : : {
2046 : 62 : wide_int min = r.lower_bound ();
2047 : 62 : wide_int max = r.upper_bound ();
2048 : 62 : tree index_type = TREE_TYPE (index_expr);
2049 : 62 : minval = fold_convert (index_type, minval);
2050 : 62 : wide_int iminval = wi::to_wide (minval);
2051 : 62 : if (wi::lt_p (min, iminval, TYPE_SIGN (index_type)))
2052 : : {
2053 : 57 : minval = wide_int_to_tree (index_type, min);
2054 : 181 : for (i = 0; i < count; i++)
2055 : 124 : test[i].mask = wi::lshift (test[i].mask, iminval - min);
2056 : : }
2057 : 5 : else if (wi::gt_p (min, iminval, TYPE_SIGN (index_type)))
2058 : : {
2059 : 0 : minval = wide_int_to_tree (index_type, min);
2060 : 0 : for (i = 0; i < count; i++)
2061 : 0 : test[i].mask = wi::lrshift (test[i].mask, min - iminval);
2062 : : }
2063 : 62 : maxval = wide_int_to_tree (index_type, max);
2064 : 62 : entry_test_needed = false;
2065 : 62 : }
2066 : : else
2067 : : entry_test_needed = true;
2068 : :
2069 : : /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
2070 : : the minval subtractions, but it might make the mask constants more
2071 : : expensive. So, compare the costs. */
2072 : 4352 : if (compare_tree_int (minval, 0) > 0 && compare_tree_int (maxval, prec) < 0)
2073 : : {
2074 : 2265 : int cost_diff;
2075 : 2265 : HOST_WIDE_INT m = tree_to_uhwi (minval);
2076 : 2265 : rtx reg = gen_raw_REG (word_mode, 10000);
2077 : 2265 : bool speed_p = optimize_insn_for_speed_p ();
2078 : 2265 : cost_diff = set_src_cost (gen_rtx_PLUS (word_mode, reg,
2079 : : GEN_INT (-m)),
2080 : : word_mode, speed_p);
2081 : 4880 : for (i = 0; i < count; i++)
2082 : : {
2083 : 2615 : rtx r = immed_wide_int_const (test[i].mask, word_mode);
2084 : 2615 : cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
2085 : : word_mode, speed_p);
2086 : 2615 : r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
2087 : 2615 : cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
2088 : : word_mode, speed_p);
2089 : : }
2090 : 2265 : if (cost_diff > 0)
2091 : : {
2092 : 4136 : for (i = 0; i < count; i++)
2093 : 2212 : test[i].mask = wi::lshift (test[i].mask, m);
2094 : 1924 : minval = build_zero_cst (TREE_TYPE (minval));
2095 : : }
2096 : : }
2097 : :
2098 : : /* Now build the test-and-branch code. */
2099 : :
2100 : 4352 : gsi = gsi_last_bb (m_case_bb);
2101 : :
2102 : : /* idx = (unsigned)x - minval. */
2103 : 4352 : idx = fold_convert_loc (loc, unsigned_index_type, index_expr);
2104 : 4352 : idx = fold_build2_loc (loc, MINUS_EXPR, unsigned_index_type, idx,
2105 : : fold_convert_loc (loc, unsigned_index_type, minval));
2106 : 4352 : idx = force_gimple_operand_gsi (&gsi, idx,
2107 : : /*simple=*/true, NULL_TREE,
2108 : : /*before=*/true, GSI_SAME_STMT);
2109 : :
2110 : 4352 : profile_probability subtree_prob = m_subtree_prob;
2111 : 4352 : profile_probability default_prob = m_default_prob;
2112 : 4352 : if (!default_prob.initialized_p ())
2113 : 2779 : default_prob = m_subtree_prob.invert ();
2114 : :
2115 : 4352 : if (m_handles_entire_switch && entry_test_needed)
2116 : : {
2117 : 2737 : tree range = int_const_binop (MINUS_EXPR, maxval, minval);
2118 : : /* if (idx > range) goto default */
2119 : 2737 : range
2120 : 2737 : = force_gimple_operand_gsi (&gsi,
2121 : : fold_convert (unsigned_index_type, range),
2122 : : /*simple=*/true, NULL_TREE,
2123 : : /*before=*/true, GSI_SAME_STMT);
2124 : 2737 : tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
2125 : 2737 : default_prob = default_prob / 2;
2126 : 2737 : basic_block new_bb
2127 : 2737 : = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb,
2128 : : default_prob, loc);
2129 : 5474 : gsi = gsi_last_bb (new_bb);
2130 : : }
2131 : :
2132 : 4352 : tmp = fold_build2_loc (loc, LSHIFT_EXPR, word_type_node, word_mode_one,
2133 : : fold_convert_loc (loc, word_type_node, idx));
2134 : :
2135 : : /* csui = (1 << (word_mode) idx) */
2136 : 4352 : if (count > 1)
2137 : : {
2138 : 1088 : csui = make_ssa_name (word_type_node);
2139 : 1088 : tmp = force_gimple_operand_gsi (&gsi, tmp,
2140 : : /*simple=*/false, NULL_TREE,
2141 : : /*before=*/true, GSI_SAME_STMT);
2142 : 1088 : shift_stmt = gimple_build_assign (csui, tmp);
2143 : 1088 : gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
2144 : 1088 : update_stmt (shift_stmt);
2145 : : }
2146 : : else
2147 : : csui = tmp;
2148 : :
2149 : : /* for each unique set of cases:
2150 : : if (const & csui) goto target */
2151 : 10408 : for (k = 0; k < count; k++)
2152 : : {
2153 : 6056 : profile_probability prob = test[k].prob / (subtree_prob + default_prob);
2154 : 6056 : subtree_prob -= test[k].prob;
2155 : 6056 : tmp = wide_int_to_tree (word_type_node, test[k].mask);
2156 : 6056 : tmp = fold_build2_loc (loc, BIT_AND_EXPR, word_type_node, csui, tmp);
2157 : 6056 : tmp = fold_build2_loc (loc, NE_EXPR, boolean_type_node,
2158 : : tmp, word_mode_zero);
2159 : 6056 : tmp = force_gimple_operand_gsi (&gsi, tmp,
2160 : : /*simple=*/true, NULL_TREE,
2161 : : /*before=*/true, GSI_SAME_STMT);
2162 : 6056 : basic_block new_bb
2163 : 6056 : = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb,
2164 : : prob, loc);
2165 : 12112 : gsi = gsi_last_bb (new_bb);
2166 : : }
2167 : :
2168 : : /* We should have removed all edges now. */
2169 : 4352 : gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
2170 : :
2171 : : /* If nothing matched, go to the default label. */
2172 : 4352 : edge e = make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
2173 : 4352 : e->probability = profile_probability::always ();
2174 : 17408 : }
2175 : :
2176 : : /* Split the basic block at the statement pointed to by GSIP, and insert
2177 : : a branch to the target basic block of E_TRUE conditional on tree
2178 : : expression COND.
2179 : :
2180 : : It is assumed that there is already an edge from the to-be-split
2181 : : basic block to E_TRUE->dest block. This edge is removed, and the
2182 : : profile information on the edge is re-used for the new conditional
2183 : : jump.
2184 : :
2185 : : The CFG is updated. The dominator tree will not be valid after
2186 : : this transformation, but the immediate dominators are updated if
2187 : : UPDATE_DOMINATORS is true.
2188 : :
2189 : : Returns the newly created basic block. */
2190 : :
2191 : : basic_block
2192 : 8793 : bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
2193 : : tree cond, basic_block case_bb,
2194 : : profile_probability prob,
2195 : : location_t loc)
2196 : : {
2197 : 8793 : tree tmp;
2198 : 8793 : gcond *cond_stmt;
2199 : 8793 : edge e_false;
2200 : 8793 : basic_block new_bb, split_bb = gsi_bb (*gsip);
2201 : :
2202 : 8793 : edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
2203 : 8793 : e_true->probability = prob;
2204 : 8793 : gcc_assert (e_true->src == split_bb);
2205 : :
2206 : 8793 : tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
2207 : : /*before=*/true, GSI_SAME_STMT);
2208 : 8793 : cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
2209 : 8793 : gimple_set_location (cond_stmt, loc);
2210 : 8793 : gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
2211 : :
2212 : 8793 : e_false = split_block (split_bb, cond_stmt);
2213 : 8793 : new_bb = e_false->dest;
2214 : 8793 : redirect_edge_pred (e_true, split_bb);
2215 : :
2216 : 8793 : e_false->flags &= ~EDGE_FALLTHRU;
2217 : 8793 : e_false->flags |= EDGE_FALSE_VALUE;
2218 : 8793 : e_false->probability = e_true->probability.invert ();
2219 : 8793 : new_bb->count = e_false->count ();
2220 : :
2221 : 8793 : return new_bb;
2222 : : }
2223 : :
2224 : : /* Compute the number of case labels that correspond to each outgoing edge of
2225 : : switch statement. Record this information in the aux field of the edge.
2226 : : Return the approx max number of cases per edge. */
2227 : :
2228 : : int
2229 : 48095 : switch_decision_tree::compute_cases_per_edge ()
2230 : : {
2231 : 48095 : int max_c = 0;
2232 : 48095 : reset_out_edges_aux (m_switch);
2233 : 48095 : int ncases = gimple_switch_num_labels (m_switch);
2234 : 312506 : for (int i = ncases - 1; i >= 1; --i)
2235 : : {
2236 : 264411 : edge case_edge = gimple_switch_edge (cfun, m_switch, i);
2237 : 264411 : case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
2238 : : /* For a range case add one extra. That's enough for the bit
2239 : : cluster heuristic. */
2240 : 264411 : if ((intptr_t)case_edge->aux > max_c)
2241 : 149018 : max_c = (intptr_t)case_edge->aux +
2242 : 74509 : !!CASE_HIGH (gimple_switch_label (m_switch, i));
2243 : : }
2244 : 48095 : return max_c;
2245 : : }
2246 : :
2247 : : /* Analyze switch statement and return true when the statement is expanded
2248 : : as decision tree. */
2249 : :
2250 : : bool
2251 : 48095 : switch_decision_tree::analyze_switch_statement ()
2252 : : {
2253 : 48095 : unsigned l = gimple_switch_num_labels (m_switch);
2254 : 48095 : basic_block bb = gimple_bb (m_switch);
2255 : 48095 : auto_vec<cluster *> clusters;
2256 : 48095 : clusters.create (l - 1);
2257 : :
2258 : 48095 : basic_block default_bb = gimple_switch_default_bb (cfun, m_switch);
2259 : 48095 : m_case_bbs.reserve (l);
2260 : 48095 : m_case_bbs.quick_push (default_bb);
2261 : :
2262 : 48095 : int max_c = compute_cases_per_edge ();
2263 : :
2264 : 312506 : for (unsigned i = 1; i < l; i++)
2265 : : {
2266 : 264411 : tree elt = gimple_switch_label (m_switch, i);
2267 : 264411 : tree lab = CASE_LABEL (elt);
2268 : 264411 : basic_block case_bb = label_to_block (cfun, lab);
2269 : 264411 : edge case_edge = find_edge (bb, case_bb);
2270 : 264411 : tree low = CASE_LOW (elt);
2271 : 264411 : tree high = CASE_HIGH (elt);
2272 : :
2273 : 264411 : profile_probability p
2274 : 264411 : = case_edge->probability / ((intptr_t) (case_edge->aux));
2275 : 264411 : clusters.quick_push (new simple_cluster (low, high, elt, case_edge->dest,
2276 : 264411 : p));
2277 : 264411 : m_case_bbs.quick_push (case_edge->dest);
2278 : : }
2279 : :
2280 : 48095 : reset_out_edges_aux (m_switch);
2281 : :
2282 : : /* Find bit-test clusters. */
2283 : 48095 : vec<cluster *> output = bit_test_cluster::find_bit_tests (clusters, max_c);
2284 : :
2285 : : /* Find jump table clusters. We are looking for these in the sequences of
2286 : : simple clusters which we didn't manage to convert into bit-test
2287 : : clusters. */
2288 : 48095 : vec<cluster *> output2;
2289 : 48095 : auto_vec<cluster *> tmp;
2290 : 48095 : output2.create (1);
2291 : 48095 : tmp.create (1);
2292 : :
2293 : 298497 : for (unsigned i = 0; i < output.length (); i++)
2294 : : {
2295 : 250402 : cluster *c = output[i];
2296 : 250402 : if (c->get_type () != SIMPLE_CASE)
2297 : : {
2298 : 4352 : if (!tmp.is_empty ())
2299 : : {
2300 : 1014 : vec<cluster *> n = jump_table_cluster::find_jump_tables (tmp);
2301 : 1014 : output2.safe_splice (n);
2302 : 1014 : n.release ();
2303 : 1014 : tmp.truncate (0);
2304 : : }
2305 : 4352 : output2.safe_push (c);
2306 : : }
2307 : : else
2308 : 246050 : tmp.safe_push (c);
2309 : : }
2310 : :
2311 : : /* We still can have a temporary vector to test. */
2312 : 48095 : if (!tmp.is_empty ())
2313 : : {
2314 : 44819 : vec<cluster *> n = jump_table_cluster::find_jump_tables (tmp);
2315 : 44819 : output2.safe_splice (n);
2316 : 44819 : n.release ();
2317 : : }
2318 : :
2319 : 48095 : if (dump_file)
2320 : : {
2321 : 24 : fprintf (dump_file, ";; GIMPLE switch case clusters: ");
2322 : 111 : for (unsigned i = 0; i < output2.length (); i++)
2323 : 87 : output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
2324 : 24 : fprintf (dump_file, "\n");
2325 : : }
2326 : :
2327 : 48095 : output.release ();
2328 : :
2329 : 48095 : bool expanded = try_switch_expansion (output2);
2330 : 48095 : release_clusters (output2);
2331 : 48095 : return expanded;
2332 : 48095 : }
2333 : :
2334 : : /* Attempt to expand CLUSTERS as a decision tree. Return true when
2335 : : expanded. */
2336 : :
2337 : : bool
2338 : 48095 : switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
2339 : : {
2340 : 48095 : tree index_expr = gimple_switch_index (m_switch);
2341 : 48095 : tree index_type = TREE_TYPE (index_expr);
2342 : 48095 : basic_block bb = gimple_bb (m_switch);
2343 : :
2344 : 48095 : if (gimple_switch_num_labels (m_switch) == 1
2345 : 48095 : || range_check_type (index_type) == NULL_TREE)
2346 : 1 : return false;
2347 : :
2348 : : /* Find the default case target label. */
2349 : 48094 : edge default_edge = gimple_switch_default_edge (cfun, m_switch);
2350 : 48094 : m_default_bb = default_edge->dest;
2351 : :
2352 : : /* Do the insertion of a case label into m_case_list. The labels are
2353 : : fed to us in descending order from the sorted vector of case labels used
2354 : : in the tree part of the middle end. So the list we construct is
2355 : : sorted in ascending order. */
2356 : :
2357 : 269849 : for (int i = clusters.length () - 1; i >= 0; i--)
2358 : : {
2359 : 173661 : case_tree_node *r = m_case_list;
2360 : 173661 : m_case_list = m_case_node_pool.allocate ();
2361 : 173661 : m_case_list->m_right = r;
2362 : 173661 : m_case_list->m_c = clusters[i];
2363 : : }
2364 : :
2365 : 48094 : record_phi_operand_mapping ();
2366 : :
2367 : : /* Split basic block that contains the gswitch statement. */
2368 : 48094 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2369 : 48094 : edge e;
2370 : 48094 : if (gsi_end_p (gsi))
2371 : 0 : e = split_block_after_labels (bb);
2372 : : else
2373 : : {
2374 : 48094 : gsi_prev (&gsi);
2375 : 48094 : e = split_block (bb, gsi_stmt (gsi));
2376 : : }
2377 : 48094 : bb = split_edge (e);
2378 : :
2379 : : /* Create new basic blocks for non-case clusters where specific expansion
2380 : : needs to happen. */
2381 : 221755 : for (unsigned i = 0; i < clusters.length (); i++)
2382 : 173661 : if (clusters[i]->get_type () != SIMPLE_CASE)
2383 : : {
2384 : 12924 : clusters[i]->m_case_bb = create_empty_bb (bb);
2385 : 12924 : clusters[i]->m_case_bb->count = bb->count;
2386 : 12924 : clusters[i]->m_case_bb->loop_father = bb->loop_father;
2387 : : }
2388 : :
2389 : : /* Do not do an extra work for a single cluster. */
2390 : 48094 : if (clusters.length () == 1
2391 : 59807 : && clusters[0]->get_type () != SIMPLE_CASE)
2392 : : {
2393 : 10642 : cluster *c = clusters[0];
2394 : 10642 : c->emit (index_expr, index_type,
2395 : : gimple_switch_default_label (m_switch), m_default_bb,
2396 : 10642 : gimple_location (m_switch));
2397 : 10642 : redirect_edge_succ (single_succ_edge (bb), c->m_case_bb);
2398 : : }
2399 : : else
2400 : : {
2401 : 37452 : emit (bb, index_expr, default_edge->probability, index_type);
2402 : :
2403 : : /* Emit cluster-specific switch handling. */
2404 : 200471 : for (unsigned i = 0; i < clusters.length (); i++)
2405 : 163019 : if (clusters[i]->get_type () != SIMPLE_CASE)
2406 : : {
2407 : 2282 : edge e = single_pred_edge (clusters[i]->m_case_bb);
2408 : 2282 : e->dest->count = e->src->count.apply_probability (e->probability);
2409 : 4564 : clusters[i]->emit (index_expr, index_type,
2410 : : gimple_switch_default_label (m_switch),
2411 : 2282 : m_default_bb, gimple_location (m_switch));
2412 : : }
2413 : : }
2414 : :
2415 : 48094 : fix_phi_operands_for_edges ();
2416 : :
2417 : 48094 : return true;
2418 : : }
2419 : :
2420 : : /* Before switch transformation, record all SSA_NAMEs defined in switch BB
2421 : : and used in a label basic block. */
2422 : :
2423 : : void
2424 : 48094 : switch_decision_tree::record_phi_operand_mapping ()
2425 : : {
2426 : 48094 : basic_block switch_bb = gimple_bb (m_switch);
2427 : : /* Record all PHI nodes that have to be fixed after conversion. */
2428 : 360599 : for (unsigned i = 0; i < m_case_bbs.length (); i++)
2429 : : {
2430 : 312505 : gphi_iterator gsi;
2431 : 312505 : basic_block bb = m_case_bbs[i];
2432 : 399246 : for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2433 : : {
2434 : 86741 : gphi *phi = gsi.phi ();
2435 : :
2436 : 271795 : for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
2437 : : {
2438 : 271795 : basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
2439 : 271795 : if (phi_src_bb == switch_bb)
2440 : : {
2441 : 86741 : tree def = gimple_phi_arg_def (phi, i);
2442 : 86741 : tree result = gimple_phi_result (phi);
2443 : 86741 : m_phi_mapping.put (result, def);
2444 : 86741 : break;
2445 : : }
2446 : : }
2447 : : }
2448 : : }
2449 : 48094 : }
2450 : :
2451 : : /* Append new operands to PHI statements that were introduced due to
2452 : : addition of new edges to case labels. */
2453 : :
2454 : : void
2455 : 48094 : switch_decision_tree::fix_phi_operands_for_edges ()
2456 : : {
2457 : 48094 : gphi_iterator gsi;
2458 : :
2459 : 360599 : for (unsigned i = 0; i < m_case_bbs.length (); i++)
2460 : : {
2461 : 312505 : basic_block bb = m_case_bbs[i];
2462 : 399246 : for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2463 : : {
2464 : 86741 : gphi *phi = gsi.phi ();
2465 : 700221 : for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
2466 : : {
2467 : 613480 : tree def = gimple_phi_arg_def (phi, j);
2468 : 613480 : if (def == NULL_TREE)
2469 : : {
2470 : 89623 : edge e = gimple_phi_arg_edge (phi, j);
2471 : 89623 : tree *definition
2472 : 89623 : = m_phi_mapping.get (gimple_phi_result (phi));
2473 : 89623 : gcc_assert (definition);
2474 : 89623 : add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
2475 : : }
2476 : : }
2477 : : }
2478 : : }
2479 : 48094 : }
2480 : :
2481 : : /* Generate a decision tree, switching on INDEX_EXPR and jumping to
2482 : : one of the labels in CASE_LIST or to the DEFAULT_LABEL.
2483 : :
2484 : : We generate a binary decision tree to select the appropriate target
2485 : : code. */
2486 : :
2487 : : void
2488 : 37452 : switch_decision_tree::emit (basic_block bb, tree index_expr,
2489 : : profile_probability default_prob, tree index_type)
2490 : : {
2491 : 37452 : balance_case_nodes (&m_case_list, NULL);
2492 : :
2493 : 37452 : if (dump_file)
2494 : 17 : dump_function_to_file (current_function_decl, dump_file, dump_flags);
2495 : 37452 : if (dump_file && (dump_flags & TDF_DETAILS))
2496 : : {
2497 : 0 : int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
2498 : 0 : fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
2499 : 0 : gcc_assert (m_case_list != NULL);
2500 : 0 : dump_case_nodes (dump_file, m_case_list, indent_step, 0);
2501 : : }
2502 : :
2503 : 74904 : bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type,
2504 : 37452 : gimple_location (m_switch));
2505 : :
2506 : 37452 : if (bb)
2507 : 36438 : emit_jump (bb, m_default_bb);
2508 : :
2509 : : /* Remove all edges and do just an edge that will reach default_bb. */
2510 : 37452 : bb = gimple_bb (m_switch);
2511 : 37452 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2512 : 37452 : gsi_remove (&gsi, true);
2513 : :
2514 : 37452 : delete_basic_block (bb);
2515 : 37452 : }
2516 : :
2517 : : /* Take an ordered list of case nodes
2518 : : and transform them into a near optimal binary tree,
2519 : : on the assumption that any target code selection value is as
2520 : : likely as any other.
2521 : :
2522 : : The transformation is performed by splitting the ordered
2523 : : list into two equal sections plus a pivot. The parts are
2524 : : then attached to the pivot as left and right branches. Each
2525 : : branch is then transformed recursively. */
2526 : :
2527 : : void
2528 : 202078 : switch_decision_tree::balance_case_nodes (case_tree_node **head,
2529 : : case_tree_node *parent)
2530 : : {
2531 : 202078 : case_tree_node *np;
2532 : :
2533 : 202078 : np = *head;
2534 : 202078 : if (np)
2535 : : {
2536 : 132233 : int i = 0;
2537 : 132233 : case_tree_node **npp;
2538 : 132233 : case_tree_node *left;
2539 : 132233 : profile_probability prob = profile_probability::never ();
2540 : :
2541 : : /* Count the number of entries on branch. */
2542 : :
2543 : 2356360 : while (np)
2544 : : {
2545 : 2224127 : i++;
2546 : 2224127 : prob += np->m_c->m_prob;
2547 : 2224127 : np = np->m_right;
2548 : : }
2549 : :
2550 : 132233 : if (i > 2)
2551 : : {
2552 : : /* Split this list if it is long enough for that to help. */
2553 : 82313 : npp = head;
2554 : 82313 : left = *npp;
2555 : 82313 : profile_probability pivot_prob = prob / 2;
2556 : :
2557 : : /* Find the place in the list that bisects the list's total cost
2558 : : by probability. */
2559 : 4144803 : while (1)
2560 : : {
2561 : : /* Skip nodes while their probability does not reach
2562 : : that amount. */
2563 : 2113558 : prob -= (*npp)->m_c->m_prob;
2564 : 2113558 : if ((prob.initialized_p () && prob < pivot_prob)
2565 : 2145875 : || ! (*npp)->m_right)
2566 : : break;
2567 : 2031245 : npp = &(*npp)->m_right;
2568 : : }
2569 : :
2570 : 82313 : np = *npp;
2571 : 82313 : *npp = 0;
2572 : 82313 : *head = np;
2573 : 82313 : np->m_parent = parent;
2574 : 82313 : np->m_left = left == np ? NULL : left;
2575 : :
2576 : : /* Optimize each of the two split parts. */
2577 : 82313 : balance_case_nodes (&np->m_left, np);
2578 : 82313 : balance_case_nodes (&np->m_right, np);
2579 : 82313 : np->m_c->m_subtree_prob = np->m_c->m_prob;
2580 : 82313 : if (np->m_left)
2581 : 81679 : np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
2582 : 82313 : if (np->m_right)
2583 : 13102 : np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
2584 : : }
2585 : : else
2586 : : {
2587 : : /* Else leave this branch as one level,
2588 : : but fill in `parent' fields. */
2589 : 49920 : np = *head;
2590 : 49920 : np->m_parent = parent;
2591 : 49920 : np->m_c->m_subtree_prob = np->m_c->m_prob;
2592 : 80706 : for (; np->m_right; np = np->m_right)
2593 : : {
2594 : 30786 : np->m_right->m_parent = np;
2595 : 30786 : (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
2596 : : }
2597 : : }
2598 : : }
2599 : 202078 : }
2600 : :
2601 : : /* Dump ROOT, a list or tree of case nodes, to file. */
2602 : :
2603 : : void
2604 : 0 : switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
2605 : : int indent_step, int indent_level)
2606 : : {
2607 : 0 : if (root == 0)
2608 : 0 : return;
2609 : 0 : indent_level++;
2610 : :
2611 : 0 : dump_case_nodes (f, root->m_left, indent_step, indent_level);
2612 : :
2613 : 0 : fputs (";; ", f);
2614 : 0 : fprintf (f, "%*s", indent_step * indent_level, "");
2615 : 0 : root->m_c->dump (f);
2616 : 0 : root->m_c->m_prob.dump (f);
2617 : 0 : fputs (" subtree: ", f);
2618 : 0 : root->m_c->m_subtree_prob.dump (f);
2619 : 0 : fputs (")\n", f);
2620 : :
2621 : 0 : dump_case_nodes (f, root->m_right, indent_step, indent_level);
2622 : : }
2623 : :
2624 : :
2625 : : /* Add an unconditional jump to CASE_BB that happens in basic block BB. */
2626 : :
2627 : : void
2628 : 64826 : switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
2629 : : {
2630 : 64826 : edge e = single_succ_edge (bb);
2631 : 64826 : redirect_edge_succ (e, case_bb);
2632 : 64826 : }
2633 : :
2634 : : /* Generate code to compare OP0 with OP1 so that the condition codes are
2635 : : set and to jump to LABEL_BB if the condition is true.
2636 : : COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
2637 : : PROB is the probability of jumping to LABEL_BB. */
2638 : :
2639 : : basic_block
2640 : 103559 : switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
2641 : : tree op1, tree_code comparison,
2642 : : basic_block label_bb,
2643 : : profile_probability prob,
2644 : : location_t loc)
2645 : : {
2646 : : // TODO: it's once called with lhs != index.
2647 : 103559 : op1 = fold_convert (TREE_TYPE (op0), op1);
2648 : :
2649 : 103559 : gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
2650 : 103559 : gimple_set_location (cond, loc);
2651 : 103559 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2652 : 103559 : gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
2653 : :
2654 : 103559 : gcc_assert (single_succ_p (bb));
2655 : :
2656 : : /* Make a new basic block where false branch will take place. */
2657 : 103559 : edge false_edge = split_block (bb, cond);
2658 : 103559 : false_edge->flags = EDGE_FALSE_VALUE;
2659 : 103559 : false_edge->probability = prob.invert ();
2660 : 103559 : false_edge->dest->count = bb->count.apply_probability (prob.invert ());
2661 : :
2662 : 103559 : edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2663 : 103559 : true_edge->probability = prob;
2664 : :
2665 : 103559 : return false_edge->dest;
2666 : : }
2667 : :
2668 : : /* Generate code to jump to LABEL if OP0 and OP1 are equal.
2669 : : PROB is the probability of jumping to LABEL_BB.
2670 : : BB is a basic block where the new condition will be placed. */
2671 : :
2672 : : basic_block
2673 : 138800 : switch_decision_tree::do_jump_if_equal (basic_block bb, tree op0, tree op1,
2674 : : basic_block label_bb,
2675 : : profile_probability prob,
2676 : : location_t loc)
2677 : : {
2678 : 138800 : op1 = fold_convert (TREE_TYPE (op0), op1);
2679 : :
2680 : 138800 : gcond *cond = gimple_build_cond (EQ_EXPR, op0, op1, NULL_TREE, NULL_TREE);
2681 : 138800 : gimple_set_location (cond, loc);
2682 : 138800 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2683 : 138800 : gsi_insert_before (&gsi, cond, GSI_SAME_STMT);
2684 : :
2685 : 138800 : gcc_assert (single_succ_p (bb));
2686 : :
2687 : : /* Make a new basic block where false branch will take place. */
2688 : 138800 : edge false_edge = split_block (bb, cond);
2689 : 138800 : false_edge->flags = EDGE_FALSE_VALUE;
2690 : 138800 : false_edge->probability = prob.invert ();
2691 : 138800 : false_edge->dest->count = bb->count.apply_probability (prob.invert ());
2692 : :
2693 : 138800 : edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2694 : 138800 : true_edge->probability = prob;
2695 : :
2696 : 138800 : return false_edge->dest;
2697 : : }
2698 : :
2699 : : /* Emit step-by-step code to select a case for the value of INDEX.
2700 : : The thus generated decision tree follows the form of the
2701 : : case-node binary tree NODE, whose nodes represent test conditions.
2702 : : DEFAULT_PROB is probability of cases leading to default BB.
2703 : : INDEX_TYPE is the type of the index of the switch. */
2704 : :
2705 : : basic_block
2706 : 64826 : switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
2707 : : case_tree_node *node,
2708 : : profile_probability default_prob,
2709 : : tree index_type, location_t loc)
2710 : : {
2711 : 144166 : profile_probability p;
2712 : :
2713 : : /* If node is null, we are done. */
2714 : 144166 : if (node == NULL)
2715 : : return bb;
2716 : :
2717 : : /* Single value case. */
2718 : 121780 : if (node->m_c->is_single_value_p ())
2719 : : {
2720 : : /* Node is single valued. First see if the index expression matches
2721 : : this node and then check our children, if any. */
2722 : 97561 : p = node->m_c->m_prob / (node->m_c->m_subtree_prob + default_prob);
2723 : 97561 : bb = do_jump_if_equal (bb, index, node->m_c->get_low (),
2724 : : node->m_c->m_case_bb, p, loc);
2725 : : /* Since this case is taken at this point, reduce its weight from
2726 : : subtree_weight. */
2727 : 97561 : node->m_c->m_subtree_prob -= node->m_c->m_prob;
2728 : :
2729 : 97561 : if (node->m_left != NULL && node->m_right != NULL)
2730 : : {
2731 : : /* 1) the node has both children
2732 : :
2733 : : If both children are single-valued cases with no
2734 : : children, finish up all the work. This way, we can save
2735 : : one ordered comparison. */
2736 : :
2737 : 11821 : if (!node->m_left->has_child ()
2738 : 7660 : && node->m_left->m_c->is_single_value_p ()
2739 : 7021 : && !node->m_right->has_child ()
2740 : 6847 : && node->m_right->m_c->is_single_value_p ())
2741 : : {
2742 : 13540 : p = (node->m_right->m_c->m_prob
2743 : 6770 : / (node->m_c->m_subtree_prob + default_prob));
2744 : 6770 : bb = do_jump_if_equal (bb, index, node->m_right->m_c->get_low (),
2745 : : node->m_right->m_c->m_case_bb, p, loc);
2746 : 6770 : node->m_c->m_subtree_prob -= node->m_right->m_c->m_prob;
2747 : :
2748 : 13540 : p = (node->m_left->m_c->m_prob
2749 : 6770 : / (node->m_c->m_subtree_prob + default_prob));
2750 : 6770 : bb = do_jump_if_equal (bb, index, node->m_left->m_c->get_low (),
2751 : : node->m_left->m_c->m_case_bb, p, loc);
2752 : : }
2753 : : else
2754 : : {
2755 : : /* Branch to a label where we will handle it later. */
2756 : 5051 : basic_block test_bb = split_edge (single_succ_edge (bb));
2757 : 5051 : redirect_edge_succ (single_pred_edge (test_bb),
2758 : 5051 : single_succ_edge (bb)->dest);
2759 : :
2760 : 5051 : p = ((node->m_right->m_c->m_subtree_prob + default_prob / 2)
2761 : 10102 : / (node->m_c->m_subtree_prob + default_prob));
2762 : 5051 : test_bb->count = bb->count.apply_probability (p);
2763 : 5051 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2764 : : GT_EXPR, test_bb, p, loc);
2765 : 5051 : default_prob /= 2;
2766 : :
2767 : : /* Handle the left-hand subtree. */
2768 : 5051 : bb = emit_case_nodes (bb, index, node->m_left,
2769 : : default_prob, index_type, loc);
2770 : :
2771 : : /* If the left-hand subtree fell through,
2772 : : don't let it fall into the right-hand subtree. */
2773 : 5051 : if (bb && m_default_bb)
2774 : 4452 : emit_jump (bb, m_default_bb);
2775 : :
2776 : 5051 : bb = emit_case_nodes (test_bb, index, node->m_right,
2777 : : default_prob, index_type, loc);
2778 : : }
2779 : : }
2780 : 85740 : else if (node->m_left == NULL && node->m_right != NULL)
2781 : : {
2782 : : /* 2) the node has only right child. */
2783 : :
2784 : : /* Here we have a right child but no left so we issue a conditional
2785 : : branch to default and process the right child.
2786 : :
2787 : : Omit the conditional branch to default if the right child
2788 : : does not have any children and is single valued; it would
2789 : : cost too much space to save so little time. */
2790 : :
2791 : 28936 : if (node->m_right->has_child ()
2792 : 28469 : || !node->m_right->m_c->is_single_value_p ())
2793 : : {
2794 : 3711 : p = ((default_prob / 2)
2795 : 1237 : / (node->m_c->m_subtree_prob + default_prob));
2796 : 1237 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (),
2797 : : LT_EXPR, m_default_bb, p, loc);
2798 : 1237 : default_prob /= 2;
2799 : :
2800 : 1237 : bb = emit_case_nodes (bb, index, node->m_right, default_prob,
2801 : : index_type, loc);
2802 : : }
2803 : : else
2804 : : {
2805 : : /* We cannot process node->right normally
2806 : : since we haven't ruled out the numbers less than
2807 : : this node's value. So handle node->right explicitly. */
2808 : 55398 : p = (node->m_right->m_c->m_subtree_prob
2809 : 27699 : / (node->m_c->m_subtree_prob + default_prob));
2810 : 27699 : bb = do_jump_if_equal (bb, index, node->m_right->m_c->get_low (),
2811 : : node->m_right->m_c->m_case_bb, p, loc);
2812 : : }
2813 : : }
2814 : 56804 : else if (node->m_left != NULL && node->m_right == NULL)
2815 : : {
2816 : : /* 3) just one subtree, on the left. Similar case as previous. */
2817 : :
2818 : 50729 : if (node->m_left->has_child ()
2819 : 0 : || !node->m_left->m_c->is_single_value_p ())
2820 : : {
2821 : 152187 : p = ((default_prob / 2)
2822 : 50729 : / (node->m_c->m_subtree_prob + default_prob));
2823 : 50729 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2824 : : GT_EXPR, m_default_bb, p, loc);
2825 : 50729 : default_prob /= 2;
2826 : :
2827 : 50729 : bb = emit_case_nodes (bb, index, node->m_left, default_prob,
2828 : : index_type, loc);
2829 : : }
2830 : : else
2831 : : {
2832 : : /* We cannot process node->left normally
2833 : : since we haven't ruled out the numbers less than
2834 : : this node's value. So handle node->left explicitly. */
2835 : 0 : p = (node->m_left->m_c->m_subtree_prob
2836 : 0 : / (node->m_c->m_subtree_prob + default_prob));
2837 : 0 : bb = do_jump_if_equal (bb, index, node->m_left->m_c->get_low (),
2838 : : node->m_left->m_c->m_case_bb, p, loc);
2839 : : }
2840 : : }
2841 : : }
2842 : : else
2843 : : {
2844 : : /* Node is a range. These cases are very similar to those for a single
2845 : : value, except that we do not start by testing whether this node
2846 : : is the one to branch to. */
2847 : 26825 : if (node->has_child () || node->m_c->get_type () != SIMPLE_CASE)
2848 : : {
2849 : 22323 : bool is_bt = node->m_c->get_type () == BIT_TEST;
2850 : 22323 : int parts = is_bt ? 3 : 2;
2851 : :
2852 : : /* Branch to a label where we will handle it later. */
2853 : 22323 : basic_block test_bb = split_edge (single_succ_edge (bb));
2854 : 22323 : redirect_edge_succ (single_pred_edge (test_bb),
2855 : 22323 : single_succ_edge (bb)->dest);
2856 : :
2857 : 22323 : profile_probability right_prob = profile_probability::never ();
2858 : 22323 : if (node->m_right)
2859 : 3131 : right_prob = node->m_right->m_c->m_subtree_prob;
2860 : 22323 : p = ((right_prob + default_prob / parts)
2861 : 44646 : / (node->m_c->m_subtree_prob + default_prob));
2862 : 22323 : test_bb->count = bb->count.apply_probability (p);
2863 : :
2864 : 22323 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2865 : : GT_EXPR, test_bb, p, loc);
2866 : :
2867 : 22323 : default_prob /= parts;
2868 : 22323 : node->m_c->m_subtree_prob -= right_prob;
2869 : 22323 : if (is_bt)
2870 : 1573 : node->m_c->m_default_prob = default_prob;
2871 : :
2872 : : /* Value belongs to this node or to the left-hand subtree. */
2873 : 22323 : p = node->m_c->m_prob / (node->m_c->m_subtree_prob + default_prob);
2874 : 22323 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (),
2875 : : GE_EXPR, node->m_c->m_case_bb, p, loc);
2876 : :
2877 : : /* Handle the left-hand subtree. */
2878 : 22323 : bb = emit_case_nodes (bb, index, node->m_left, default_prob,
2879 : : index_type, loc);
2880 : :
2881 : : /* If the left-hand subtree fell through,
2882 : : don't let it fall into the right-hand subtree. */
2883 : 22323 : if (bb && m_default_bb)
2884 : 22040 : emit_jump (bb, m_default_bb);
2885 : :
2886 : 22323 : bb = emit_case_nodes (test_bb, index, node->m_right, default_prob,
2887 : : index_type, loc);
2888 : : }
2889 : : else
2890 : : {
2891 : : /* Node has no children so we check low and high bounds to remove
2892 : : redundant tests. Only one of the bounds can exist,
2893 : : since otherwise this node is bounded--a case tested already. */
2894 : 1896 : tree lhs, rhs;
2895 : 1896 : generate_range_test (bb, index, node->m_c->get_low (),
2896 : 1896 : node->m_c->get_high (), &lhs, &rhs);
2897 : 1896 : p = default_prob / (node->m_c->m_subtree_prob + default_prob);
2898 : :
2899 : 1896 : bb = emit_cmp_and_jump_insns (bb, lhs, rhs, GT_EXPR,
2900 : : m_default_bb, p, loc);
2901 : :
2902 : 1896 : emit_jump (bb, node->m_c->m_case_bb);
2903 : 1896 : return NULL;
2904 : : }
2905 : : }
2906 : :
2907 : : return bb;
2908 : : }
2909 : :
2910 : : /* The main function of the pass scans statements for switches and invokes
2911 : : process_switch on them. */
2912 : :
2913 : : namespace {
2914 : :
2915 : : const pass_data pass_data_convert_switch =
2916 : : {
2917 : : GIMPLE_PASS, /* type */
2918 : : "switchconv", /* name */
2919 : : OPTGROUP_NONE, /* optinfo_flags */
2920 : : TV_TREE_SWITCH_CONVERSION, /* tv_id */
2921 : : ( PROP_cfg | PROP_ssa ), /* properties_required */
2922 : : 0, /* properties_provided */
2923 : : 0, /* properties_destroyed */
2924 : : 0, /* todo_flags_start */
2925 : : TODO_update_ssa, /* todo_flags_finish */
2926 : : };
2927 : :
2928 : : class pass_convert_switch : public gimple_opt_pass
2929 : : {
2930 : : public:
2931 : 290033 : pass_convert_switch (gcc::context *ctxt)
2932 : 580066 : : gimple_opt_pass (pass_data_convert_switch, ctxt)
2933 : : {}
2934 : :
2935 : : /* opt_pass methods: */
2936 : 2498533 : bool gate (function *) final override
2937 : : {
2938 : 2498533 : return flag_tree_switch_conversion != 0;
2939 : : }
2940 : : unsigned int execute (function *) final override;
2941 : :
2942 : : }; // class pass_convert_switch
2943 : :
2944 : : unsigned int
2945 : 2393424 : pass_convert_switch::execute (function *fun)
2946 : : {
2947 : 2393424 : basic_block bb;
2948 : 2393424 : bool cfg_altered = false;
2949 : :
2950 : 12948675 : FOR_EACH_BB_FN (bb, fun)
2951 : : {
2952 : 31471697 : if (gswitch *stmt = safe_dyn_cast <gswitch *> (*gsi_last_bb (bb)))
2953 : : {
2954 : 29447 : if (dump_file)
2955 : : {
2956 : 43 : expanded_location loc = expand_location (gimple_location (stmt));
2957 : :
2958 : 43 : fprintf (dump_file, "beginning to process the following "
2959 : : "SWITCH statement (%s:%d) : ------- \n",
2960 : : loc.file, loc.line);
2961 : 43 : print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2962 : 43 : putc ('\n', dump_file);
2963 : : }
2964 : :
2965 : 29447 : switch_conversion sconv;
2966 : 29447 : sconv.expand (stmt);
2967 : 29447 : cfg_altered |= sconv.m_cfg_altered;
2968 : 29447 : if (!sconv.m_reason)
2969 : : {
2970 : 689 : if (dump_file)
2971 : : {
2972 : 39 : fputs ("Switch converted\n", dump_file);
2973 : 39 : fputs ("--------------------------------\n", dump_file);
2974 : : }
2975 : :
2976 : : /* Make no effort to update the post-dominator tree.
2977 : : It is actually not that hard for the transformations
2978 : : we have performed, but it is not supported
2979 : : by iterate_fix_dominators. */
2980 : 689 : free_dominance_info (CDI_POST_DOMINATORS);
2981 : : }
2982 : : else
2983 : : {
2984 : 28758 : if (dump_file)
2985 : : {
2986 : 4 : fputs ("Bailing out - ", dump_file);
2987 : 4 : fputs (sconv.m_reason, dump_file);
2988 : 4 : fputs ("\n--------------------------------\n", dump_file);
2989 : : }
2990 : : }
2991 : 29447 : }
2992 : : }
2993 : :
2994 : 2393424 : return cfg_altered ? TODO_cleanup_cfg : 0;;
2995 : : }
2996 : :
2997 : : } // anon namespace
2998 : :
2999 : : gimple_opt_pass *
3000 : 290033 : make_pass_convert_switch (gcc::context *ctxt)
3001 : : {
3002 : 290033 : return new pass_convert_switch (ctxt);
3003 : : }
3004 : :
3005 : : /* The main function of the pass scans statements for switches and invokes
3006 : : process_switch on them. */
3007 : :
3008 : : namespace {
3009 : :
3010 : : template <bool O0> class pass_lower_switch: public gimple_opt_pass
3011 : : {
3012 : : public:
3013 : 1740198 : pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
3014 : :
3015 : : static const pass_data data;
3016 : : opt_pass *
3017 : 290033 : clone () final override
3018 : : {
3019 : 290033 : return new pass_lower_switch<O0> (m_ctxt);
3020 : : }
3021 : :
3022 : : bool
3023 : 2525405 : gate (function *) final override
3024 : : {
3025 : 2525405 : return !O0 || !optimize;
3026 : : }
3027 : :
3028 : : unsigned int execute (function *fun) final override;
3029 : : }; // class pass_lower_switch
3030 : :
3031 : : template <bool O0>
3032 : : const pass_data pass_lower_switch<O0>::data = {
3033 : : GIMPLE_PASS, /* type */
3034 : : O0 ? "switchlower_O0" : "switchlower", /* name */
3035 : : OPTGROUP_NONE, /* optinfo_flags */
3036 : : TV_TREE_SWITCH_LOWERING, /* tv_id */
3037 : : ( PROP_cfg | PROP_ssa ), /* properties_required */
3038 : : 0, /* properties_provided */
3039 : : 0, /* properties_destroyed */
3040 : : 0, /* todo_flags_start */
3041 : : TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
3042 : : };
3043 : :
3044 : : template <bool O0>
3045 : : unsigned int
3046 : 1478963 : pass_lower_switch<O0>::execute (function *fun)
3047 : : {
3048 : : basic_block bb;
3049 : 1478963 : bool expanded = false;
3050 : :
3051 : 1478963 : auto_vec<gimple *> switch_statements;
3052 : 1478963 : switch_statements.create (1);
3053 : :
3054 : 15096662 : FOR_EACH_BB_FN (bb, fun)
3055 : : {
3056 : 27009524 : if (gswitch *swtch = safe_dyn_cast <gswitch *> (*gsi_last_bb (bb)))
3057 : : {
3058 : : if (!O0)
3059 : 32847 : group_case_labels_stmt (swtch);
3060 : 48085 : switch_statements.safe_push (swtch);
3061 : : }
3062 : : }
3063 : :
3064 : 1527048 : for (unsigned i = 0; i < switch_statements.length (); i++)
3065 : : {
3066 : 48085 : gimple *stmt = switch_statements[i];
3067 : 48085 : if (dump_file)
3068 : : {
3069 : 24 : expanded_location loc = expand_location (gimple_location (stmt));
3070 : :
3071 : 24 : fprintf (dump_file, "beginning to process the following "
3072 : : "SWITCH statement (%s:%d) : ------- \n",
3073 : : loc.file, loc.line);
3074 : 24 : print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3075 : 24 : putc ('\n', dump_file);
3076 : : }
3077 : :
3078 : 48085 : gswitch *swtch = dyn_cast<gswitch *> (stmt);
3079 : : if (swtch)
3080 : : {
3081 : 48085 : switch_decision_tree dt (swtch);
3082 : 48085 : expanded |= dt.analyze_switch_statement ();
3083 : 48085 : }
3084 : : }
3085 : :
3086 : 1478963 : if (expanded)
3087 : : {
3088 : 34564 : free_dominance_info (CDI_DOMINATORS);
3089 : 34564 : free_dominance_info (CDI_POST_DOMINATORS);
3090 : 34564 : mark_virtual_operands_for_renaming (cfun);
3091 : : }
3092 : :
3093 : 1478963 : return 0;
3094 : 1478963 : }
3095 : :
3096 : : } // anon namespace
3097 : :
3098 : : gimple_opt_pass *
3099 : 290033 : make_pass_lower_switch_O0 (gcc::context *ctxt)
3100 : : {
3101 : 290033 : return new pass_lower_switch<true> (ctxt);
3102 : : }
3103 : : gimple_opt_pass *
3104 : 290033 : make_pass_lower_switch (gcc::context *ctxt)
3105 : : {
3106 : 290033 : return new pass_lower_switch<false> (ctxt);
3107 : : }
|