ddc817b10ae83402fae76d22d0b88a34d00c4cb3
[libfirm] / ir / lower / lower_switch.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Lowering of Switches if necessary or advantageous.
23  * @author  Moritz Kroll
24  */
25 #include "config.h"
26
27 #include <limits.h>
28 #include <stdbool.h>
29
30 #include "array_t.h"
31 #include "ircons.h"
32 #include "irgopt.h"
33 #include "irgwalk.h"
34 #include "irnode_t.h"
35 #include "irouts.h"
36 #include "irpass_t.h"
37 #include "lowering.h"
38 #include "error.h"
39 #include "irnodeset.h"
40
41 #define foreach_out_irn(irn, i, outirn) for (i = get_irn_n_outs(irn) - 1;\
42         i >= 0 && (outirn = get_irn_out(irn, i)); --i)
43
44 typedef struct walk_env_t {
45         unsigned      spare_size; /**< the allowed spare size for table switches */
46         unsigned      small_switch;
47         bool          changed;    /**< indicates whether a change was performed */
48         ir_nodeset_t  processed;
49 } walk_env_t;
50
51 typedef struct case_data_t {
52         const ir_switch_table_entry *entry;
53         ir_node                     *target;
54 } case_data_t;
55
56 typedef struct switch_info_t {
57         ir_node     *switchn;
58         ir_tarval   *switch_min;
59         ir_tarval   *switch_max;
60         ir_node     *default_block;
61         unsigned     num_cases;
62         case_data_t *cases;
63         ir_node    **defusers;    /**< the Projs pointing to the default case */
64 } switch_info_t;
65
66 /**
67  * analyze enough to decide if we should lower the switch
68  */
69 static void analyse_switch0(switch_info_t *info, ir_node *switchn)
70 {
71         const ir_switch_table *table      = get_Switch_table(switchn);
72         size_t                 n_entries  = ir_switch_table_get_n_entries(table);
73         ir_mode               *mode       = get_irn_mode(get_Switch_selector(switchn));
74         ir_tarval             *switch_min = get_mode_max(mode);
75         ir_tarval             *switch_max = get_mode_min(mode);
76         unsigned               num_cases  = 0;
77
78         for (size_t e = 0; e < n_entries; ++e) {
79                 const ir_switch_table_entry *entry
80                         = ir_switch_table_get_entry_const(table, e);
81                 if (entry->pn == 0)
82                         continue;
83
84                 if (tarval_cmp(entry->min, switch_min) == ir_relation_less)
85                         switch_min = entry->min;
86                 if (tarval_cmp(entry->max, switch_max) == ir_relation_greater)
87                         switch_max = entry->max;
88
89                 ++num_cases;
90         }
91
92         info->switchn    = switchn;
93         info->switch_min = switch_min;
94         info->switch_max = switch_max;
95         info->num_cases  = num_cases;
96 }
97
98 static int casecmp(const void *a, const void *b)
99 {
100         const case_data_t           *cda = (const case_data_t*)a;
101         const case_data_t           *cdb = (const case_data_t*)b;
102         const ir_switch_table_entry *ea  = cda->entry;
103         const ir_switch_table_entry *eb  = cdb->entry;
104
105         if (ea == eb)
106                 return 0;
107
108         if (tarval_cmp(ea->max, eb->min) == ir_relation_less)
109                 return -1;
110         /* cases must be non overlapping, so the only remaining case is greater */
111         assert(tarval_cmp(ea->min, eb->max) == ir_relation_greater);
112         return 1;
113 }
114
115 /**
116  * Analyse the stuff that anayse_switch0() left out
117  */
118 static void analyse_switch1(switch_info_t *info)
119 {
120         const ir_node         *switchn   = info->switchn;
121         const ir_switch_table *table     = get_Switch_table(switchn);
122         size_t                 n_entries = ir_switch_table_get_n_entries(table);
123         unsigned               n_outs    = get_Switch_n_outs(switchn);
124         ir_node              **targets   = XMALLOCNZ(ir_node*, n_outs);
125         unsigned               num_cases = info->num_cases;
126         case_data_t           *cases     = XMALLOCN(case_data_t, num_cases);
127         unsigned               c         = 0;
128         size_t                 e;
129         int                    i;
130         ir_node               *proj;
131
132         foreach_out_irn(switchn, i, proj) {
133                 long     pn     = get_Proj_proj(proj);
134                 ir_node *target = get_irn_out(proj, 0);
135
136                 assert((unsigned)pn < n_outs);
137                 assert(targets[(unsigned)pn] == NULL);
138                 targets[(unsigned)pn] = target;
139         }
140
141         for (e = 0; e < n_entries; ++e) {
142                 const ir_switch_table_entry *entry
143                         = ir_switch_table_get_entry_const(table, e);
144                 if (entry->pn == 0)
145                         continue;
146
147                 cases[c].entry  = entry;
148                 cases[c].target = targets[entry->pn];
149                 ++c;
150         }
151         assert(c == num_cases);
152
153         /*
154          * Switch should be transformed into an if cascade.
155          * So first order the cases, so we can do a binary search on them.
156          */
157         qsort(cases, num_cases, sizeof(cases[0]), casecmp);
158
159         info->default_block = targets[pn_Switch_default];
160         info->cases         = cases;
161         free(targets);
162 }
163
164 static void normalize_table(ir_node *switchn, ir_mode *new_mode,
165                             ir_tarval *delta)
166 {
167         ir_switch_table *table     = get_Switch_table(switchn);
168         size_t           n_entries = ir_switch_table_get_n_entries(table);
169         size_t           e;
170         /* adapt switch_table */
171         for (e = 0; e < n_entries; ++e) {
172                 ir_switch_table_entry *entry = ir_switch_table_get_entry(table, e);
173                 ir_tarval *min = entry->min;
174
175                 if (entry->pn == 0)
176                         continue;
177
178                 min = tarval_convert_to(min, new_mode);
179                 if (delta != NULL)
180                         min = tarval_sub(min, delta, NULL);
181
182                 if (entry->min == entry->max) {
183                         entry->min = min;
184                         entry->max = min;
185                 } else {
186                         ir_tarval *max = entry->max;
187                         max = tarval_convert_to(max, new_mode);
188                         if (delta != NULL)
189                                 max = tarval_sub(max, delta, NULL);
190                         entry->min = min;
191                         entry->max = max;
192                 }
193         }
194 }
195
196 /**
197  * normalize switch to work on an unsigned input with the first case at 0
198  */
199 static void normalize_switch(switch_info_t *info)
200 {
201         ir_node   *switchn         = info->switchn;
202         ir_graph  *irg             = get_irn_irg(switchn);
203         ir_node   *block           = get_nodes_block(switchn);
204         ir_node   *selector        = get_Switch_selector(switchn);
205         ir_mode   *switch_mode     = get_irn_mode(selector);
206         ir_mode   *mode            = switch_mode;
207         ir_tarval *delta           = NULL;
208         bool       needs_normalize = false;
209
210         ir_tarval *min = info->switch_min;
211         if (mode_is_signed(mode)) {
212                 mode             = find_unsigned_mode(mode);
213                 selector         = new_r_Conv(block, selector, mode);
214                 min              = tarval_convert_to(min, mode);
215                 needs_normalize  = true;
216                 info->switch_max = tarval_convert_to(info->switch_max, mode);
217         }
218
219         /* normalize so switch_min is at 0 */
220         if (min != get_mode_null(mode)) {
221                 ir_node  *min_const = new_r_Const(irg, min);
222                 dbg_info *dbgi      = get_irn_dbg_info(switchn);
223                 selector = new_rd_Sub(dbgi, block, selector, min_const, mode);
224
225                 info->switch_max = tarval_sub(info->switch_max, min, mode);
226                 info->switch_min = get_mode_null(mode);
227                 delta            = min;
228
229                 needs_normalize = true;
230         }
231
232         if (needs_normalize) {
233                 set_Switch_selector(switchn, selector);
234                 normalize_table(switchn, mode, delta);
235         }
236 }
237
238 /**
239  * Create an if (selector == caseval) Cond node (and handle the special case
240  * of ranged cases)
241  */
242 static ir_node *create_case_cond(const ir_switch_table_entry *entry,
243                                  dbg_info *dbgi, ir_node *block,
244                                  ir_node *selector)
245 {
246         ir_graph *irg      = get_irn_irg(block);
247         ir_node  *minconst = new_r_Const(irg, entry->min);
248         ir_node  *cmp;
249
250         if (entry->min == entry->max) {
251                 cmp = new_rd_Cmp(dbgi, block, selector, minconst, ir_relation_equal);
252         } else {
253                 ir_tarval *adjusted_max = tarval_sub(entry->max, entry->min, NULL);
254                 ir_node   *sub          = new_rd_Sub(dbgi, block, selector, minconst,
255                                                      get_tarval_mode(adjusted_max));
256                 ir_node   *maxconst     = new_r_Const(irg, adjusted_max);
257                 cmp = new_rd_Cmp(dbgi, block, sub, maxconst, ir_relation_less_equal);
258         }
259
260         return new_rd_Cond(dbgi, block, cmp);
261 }
262
263 /**
264  * Creates an if cascade realizing binary search.
265  */
266 static void create_if_cascade(switch_info_t *info, ir_node *block,
267                               case_data_t *curcases, unsigned numcases)
268 {
269         ir_graph      *irg      = get_irn_irg(block);
270         const ir_node *switchn  = info->switchn;
271         dbg_info      *dbgi     = get_irn_dbg_info(switchn);
272         ir_node       *selector = get_Switch_selector(switchn);
273
274         if (numcases == 0) {
275                 /* zero cases: "goto default;" */
276                 ARR_APP1(ir_node*, info->defusers, new_r_Jmp(block));
277         } else if (numcases == 1) {
278                 /*only one case: "if (sel == val) goto target else goto default;"*/
279                 const ir_switch_table_entry *entry = curcases[0].entry;
280                 ir_node *cond      = create_case_cond(entry, dbgi, block, selector);
281                 ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
282                 ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
283
284                 set_Block_cfgpred(curcases[0].target, 0, trueproj);
285                 ARR_APP1(ir_node*, info->defusers, falseproj);
286         } else if (numcases == 2) {
287                 /* only two cases: "if (sel == val[0]) goto target[0];" */
288                 const ir_switch_table_entry *entry0 = curcases[0].entry;
289                 const ir_switch_table_entry *entry1 = curcases[1].entry;
290                 ir_node *cond      = create_case_cond(entry0, dbgi, block, selector);
291                 ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
292                 ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
293                 ir_node *in[1];
294                 ir_node *neblock;
295
296                 set_Block_cfgpred(curcases[0].target, 0, trueproj);
297
298                 in[0] = falseproj;
299                 neblock = new_r_Block(irg, 1, in);
300
301                 /* second part: "else if (sel == val[1]) goto target[1] else goto default;" */
302                 cond      = create_case_cond(entry1, dbgi, neblock, selector);
303                 trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
304                 falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
305                 set_Block_cfgpred(curcases[1].target, 0, trueproj);
306                 ARR_APP1(ir_node*, info->defusers, falseproj);
307         } else {
308                 /* recursive case: split cases in the middle */
309                 unsigned midcase = numcases / 2;
310                 const ir_switch_table_entry *entry = curcases[midcase].entry;
311                 ir_node *val = new_r_Const(irg, entry->min);
312                 ir_node *cmp = new_rd_Cmp(dbgi, block, selector, val, ir_relation_less);
313                 ir_node *cond = new_rd_Cond(dbgi, block, cmp);
314                 ir_node *in[1];
315                 ir_node *ltblock;
316                 ir_node *geblock;
317
318                 in[0]   = new_r_Proj(cond, mode_X, pn_Cond_true);
319                 ltblock = new_r_Block(irg, 1, in);
320
321                 in[0]   = new_r_Proj(cond, mode_X, pn_Cond_false);
322                 geblock = new_r_Block(irg, 1, in);
323
324                 create_if_cascade(info, ltblock, curcases, midcase);
325                 create_if_cascade(info, geblock, curcases + midcase, numcases - midcase);
326         }
327 }
328
329 static void create_out_of_bounds_check(switch_info_t *info)
330 {
331         ir_node    *switchn       = info->switchn;
332         ir_graph   *irg           = get_irn_irg(switchn);
333         dbg_info   *dbgi          = get_irn_dbg_info(switchn);
334         ir_node    *selector      = get_Switch_selector(switchn);
335         ir_node    *block         = get_nodes_block(switchn);
336         ir_node   **default_preds = NEW_ARR_F(ir_node*, 0);
337         ir_node    *default_block = NULL;
338         ir_node    *max_const;
339         ir_node    *proj_true;
340         ir_node    *proj_false;
341         ir_node    *cmp;
342         ir_node    *oob_cond;
343         ir_node    *in[1];
344         ir_node    *new_block;
345         int         i;
346         ir_node    *proj;
347         size_t      n_default_preds;
348
349         assert(tarval_is_null(info->switch_min));
350
351         /* check for out-of-bounds */
352         max_const  = new_r_Const(irg, info->switch_max);
353         cmp        = new_rd_Cmp(dbgi, block, selector, max_const, ir_relation_less_equal);
354         oob_cond   = new_rd_Cond(dbgi, block, cmp);
355         proj_true  = new_r_Proj(oob_cond, mode_X, pn_Cond_true);
356         proj_false = new_r_Proj(oob_cond, mode_X, pn_Cond_false);
357
358         ARR_APP1(ir_node*, default_preds, proj_false);
359
360         /* create new block containing the switch */
361         in[0] = proj_true;
362         new_block = new_r_Block(irg, 1, in);
363         set_nodes_block(switchn, new_block);
364
365         /* adjust projs */
366         foreach_out_irn(switchn, i, proj) {
367                 long pn = get_Proj_proj(proj);
368                 if (pn == pn_Switch_default) {
369                         assert(default_block == NULL);
370                         default_block = get_irn_out(proj, 0);
371                         ARR_APP1(ir_node*, default_preds, proj);
372                 }
373                 set_nodes_block(proj, new_block);
374         }
375
376         /* adapt default block */
377         n_default_preds = ARR_LEN(default_preds);
378         if (n_default_preds > 1) {
379                 /* create new intermediate blocks so we don't have critical edges */
380                 size_t p;
381                 for (p = 0; p < n_default_preds; ++p) {
382                         ir_node *pred = default_preds[p];
383                         ir_node *split_block;
384                         ir_node *block_in[1];
385
386                         block_in[0] = pred;
387                         split_block = new_r_Block(irg, 1, block_in);
388
389                         default_preds[p] = new_r_Jmp(split_block);
390                 }
391         }
392         set_irn_in(default_block, n_default_preds, default_preds);
393
394         DEL_ARR_F(default_preds);
395
396         clear_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE);
397 }
398
399 /**
400  * Block-Walker: searches for Switch nodes
401  */
402 static void find_switch_nodes(ir_node *block, void *ctx)
403 {
404         walk_env_t   *env = (walk_env_t *)ctx;
405         ir_node      *projx;
406         ir_node      *switchn;
407         switch_info_t info;
408
409         /* because we split critical blocks only blocks with 1 predecessors may
410          * contain Proj->Cond nodes */
411         if (get_Block_n_cfgpreds(block) != 1)
412                 return;
413
414         projx = get_Block_cfgpred(block, 0);
415         if (!is_Proj(projx))
416                 return;
417         assert(get_irn_mode(projx) == mode_X);
418
419         switchn = get_Proj_pred(projx);
420         if (!is_Switch(switchn))
421                 return;
422
423         if (ir_nodeset_contains(&env->processed, switchn))
424                 return;
425         ir_nodeset_insert(&env->processed, switchn);
426
427         analyse_switch0(&info, switchn);
428
429         /*
430          * Here we have: num_cases and [switch_min, switch_max] interval.
431          * We do an if-cascade if there are too many spare numbers.
432          */
433         ir_mode   *mode  = get_irn_mode(get_Switch_selector(switchn));
434         ir_tarval *spare = tarval_sub(info.switch_max, info.switch_min, mode);
435         mode  = find_unsigned_mode(mode);
436         spare = tarval_convert_to(spare, mode);
437         ir_tarval *num_cases_minus_one
438                 = new_tarval_from_long(info.num_cases-1, mode);
439         spare = tarval_sub(spare, num_cases_minus_one, mode);
440         ir_tarval *spare_size = new_tarval_from_long(env->spare_size, mode);
441         bool lower_switch = (info.num_cases <= env->small_switch
442          || (tarval_cmp(spare, spare_size) & ir_relation_greater_equal));
443
444         if (!lower_switch) {
445                 /* we won't decompose the switch. But we must add an out-of-bounds
446                  * check */
447                 normalize_switch(&info);
448                 create_out_of_bounds_check(&info);
449                 return;
450         }
451
452         normalize_switch(&info);
453         analyse_switch1(&info);
454
455         /* Now create the if cascade */
456         env->changed  = true;
457         info.defusers = NEW_ARR_F(ir_node*, 0);
458         block         = get_nodes_block(switchn);
459         create_if_cascade(&info, block, info.cases, info.num_cases);
460
461         /* Connect new default case users */
462         set_irn_in(info.default_block, ARR_LEN(info.defusers), info.defusers);
463
464         DEL_ARR_F(info.defusers);
465         xfree(info.cases);
466         clear_irg_properties(get_irn_irg(block), IR_GRAPH_PROPERTY_NO_CRITICAL_EDGES
467                                           | IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE);
468 }
469
470 void lower_switch(ir_graph *irg, unsigned small_switch, unsigned spare_size)
471 {
472         walk_env_t env;
473         env.changed             = false;
474         env.spare_size          = spare_size;
475         env.small_switch        = small_switch;
476         ir_nodeset_init(&env.processed);
477
478         remove_critical_cf_edges(irg);
479         assure_irg_outs(irg);
480
481         irg_block_walk_graph(irg, find_switch_nodes, NULL, &env);
482         ir_nodeset_destroy(&env.processed);
483 }