LCOV - code coverage report
Current view: top level - gcc - tree-switch-conversion.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 96.9 % 1442 1397
Test Date: 2026-12-05 16:10:02 Functions: 95.1 % 61 58
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.