]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/stmt.c
2015-07-07 Andrew MacLeod <amacleod@redhat.com>
[thirdparty/gcc.git] / gcc / stmt.c
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 /* This file handles the generation of rtl code from tree structure
21 above the level of expressions, using subroutines in exp*.c and emit-rtl.c.
22 The functions whose names start with `expand_' are called by the
23 expander to generate RTL instructions for various kinds of constructs. */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "backend.h"
29 #include "tree.h"
30 #include "gimple.h"
31 #include "rtl.h"
32
33 #include "alias.h"
34 #include "fold-const.h"
35 #include "varasm.h"
36 #include "stor-layout.h"
37 #include "tm_p.h"
38 #include "flags.h"
39 #include "except.h"
40 #include "insn-config.h"
41 #include "expmed.h"
42 #include "dojump.h"
43 #include "explow.h"
44 #include "calls.h"
45 #include "emit-rtl.h"
46 #include "stmt.h"
47 #include "expr.h"
48 #include "libfuncs.h"
49 #include "recog.h"
50 #include "diagnostic-core.h"
51 #include "output.h"
52 #include "langhooks.h"
53 #include "insn-codes.h"
54 #include "optabs.h"
55 #include "target.h"
56 #include "cfganal.h"
57 #include "internal-fn.h"
58 #include "regs.h"
59 #include "alloc-pool.h"
60 #include "pretty-print.h"
61 #include "params.h"
62 #include "dumpfile.h"
63 #include "builtins.h"
64
65 \f
66 /* Functions and data structures for expanding case statements. */
67
68 /* Case label structure, used to hold info on labels within case
69 statements. We handle "range" labels; for a single-value label
70 as in C, the high and low limits are the same.
71
72 We start with a vector of case nodes sorted in ascending order, and
73 the default label as the last element in the vector. Before expanding
74 to RTL, we transform this vector into a list linked via the RIGHT
75 fields in the case_node struct. Nodes with higher case values are
76 later in the list.
77
78 Switch statements can be output in three forms. A branch table is
79 used if there are more than a few labels and the labels are dense
80 within the range between the smallest and largest case value. If a
81 branch table is used, no further manipulations are done with the case
82 node chain.
83
84 The alternative to the use of a branch table is to generate a series
85 of compare and jump insns. When that is done, we use the LEFT, RIGHT,
86 and PARENT fields to hold a binary tree. Initially the tree is
87 totally unbalanced, with everything on the right. We balance the tree
88 with nodes on the left having lower case values than the parent
89 and nodes on the right having higher values. We then output the tree
90 in order.
91
92 For very small, suitable switch statements, we can generate a series
93 of simple bit test and branches instead. */
94
95 struct case_node
96 {
97 struct case_node *left; /* Left son in binary tree */
98 struct case_node *right; /* Right son in binary tree; also node chain */
99 struct case_node *parent; /* Parent of node in binary tree */
100 tree low; /* Lowest index value for this label */
101 tree high; /* Highest index value for this label */
102 tree code_label; /* Label to jump to when node matches */
103 int prob; /* Probability of taking this case. */
104 /* Probability of reaching subtree rooted at this node */
105 int subtree_prob;
106 };
107
108 typedef struct case_node case_node;
109 typedef struct case_node *case_node_ptr;
110
111 extern basic_block label_to_block_fn (struct function *, tree);
112 \f
113 static bool check_unique_operand_names (tree, tree, tree);
114 static char *resolve_operand_name_1 (char *, tree, tree, tree);
115 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
116 static int node_has_low_bound (case_node_ptr, tree);
117 static int node_has_high_bound (case_node_ptr, tree);
118 static int node_is_bounded (case_node_ptr, tree);
119 static void emit_case_nodes (rtx, case_node_ptr, rtx_code_label *, int, tree);
120 \f
121 /* Return the rtx-label that corresponds to a LABEL_DECL,
122 creating it if necessary. */
123
124 rtx_insn *
125 label_rtx (tree label)
126 {
127 gcc_assert (TREE_CODE (label) == LABEL_DECL);
128
129 if (!DECL_RTL_SET_P (label))
130 {
131 rtx_code_label *r = gen_label_rtx ();
132 SET_DECL_RTL (label, r);
133 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
134 LABEL_PRESERVE_P (r) = 1;
135 }
136
137 return as_a <rtx_insn *> (DECL_RTL (label));
138 }
139
140 /* As above, but also put it on the forced-reference list of the
141 function that contains it. */
142 rtx_insn *
143 force_label_rtx (tree label)
144 {
145 rtx_insn *ref = label_rtx (label);
146 tree function = decl_function_context (label);
147
148 gcc_assert (function);
149
150 forced_labels = gen_rtx_INSN_LIST (VOIDmode, ref, forced_labels);
151 return ref;
152 }
153
154 /* As label_rtx, but ensures (in check build), that returned value is
155 an existing label (i.e. rtx with code CODE_LABEL). */
156 rtx_code_label *
157 jump_target_rtx (tree label)
158 {
159 return as_a <rtx_code_label *> (label_rtx (label));
160 }
161
162 /* Add an unconditional jump to LABEL as the next sequential instruction. */
163
164 void
165 emit_jump (rtx label)
166 {
167 do_pending_stack_adjust ();
168 emit_jump_insn (targetm.gen_jump (label));
169 emit_barrier ();
170 }
171 \f
172 /* Handle goto statements and the labels that they can go to. */
173
174 /* Specify the location in the RTL code of a label LABEL,
175 which is a LABEL_DECL tree node.
176
177 This is used for the kind of label that the user can jump to with a
178 goto statement, and for alternatives of a switch or case statement.
179 RTL labels generated for loops and conditionals don't go through here;
180 they are generated directly at the RTL level, by other functions below.
181
182 Note that this has nothing to do with defining label *names*.
183 Languages vary in how they do that and what that even means. */
184
185 void
186 expand_label (tree label)
187 {
188 rtx_code_label *label_r = jump_target_rtx (label);
189
190 do_pending_stack_adjust ();
191 emit_label (label_r);
192 if (DECL_NAME (label))
193 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
194
195 if (DECL_NONLOCAL (label))
196 {
197 expand_builtin_setjmp_receiver (NULL);
198 nonlocal_goto_handler_labels
199 = gen_rtx_INSN_LIST (VOIDmode, label_r,
200 nonlocal_goto_handler_labels);
201 }
202
203 if (FORCED_LABEL (label))
204 forced_labels = gen_rtx_INSN_LIST (VOIDmode, label_r, forced_labels);
205
206 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
207 maybe_set_first_label_num (label_r);
208 }
209 \f
210 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
211 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
212 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
213 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
214 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
215 constraint allows the use of a register operand. And, *IS_INOUT
216 will be true if the operand is read-write, i.e., if it is used as
217 an input as well as an output. If *CONSTRAINT_P is not in
218 canonical form, it will be made canonical. (Note that `+' will be
219 replaced with `=' as part of this process.)
220
221 Returns TRUE if all went well; FALSE if an error occurred. */
222
223 bool
224 parse_output_constraint (const char **constraint_p, int operand_num,
225 int ninputs, int noutputs, bool *allows_mem,
226 bool *allows_reg, bool *is_inout)
227 {
228 const char *constraint = *constraint_p;
229 const char *p;
230
231 /* Assume the constraint doesn't allow the use of either a register
232 or memory. */
233 *allows_mem = false;
234 *allows_reg = false;
235
236 /* Allow the `=' or `+' to not be at the beginning of the string,
237 since it wasn't explicitly documented that way, and there is a
238 large body of code that puts it last. Swap the character to
239 the front, so as not to uglify any place else. */
240 p = strchr (constraint, '=');
241 if (!p)
242 p = strchr (constraint, '+');
243
244 /* If the string doesn't contain an `=', issue an error
245 message. */
246 if (!p)
247 {
248 error ("output operand constraint lacks %<=%>");
249 return false;
250 }
251
252 /* If the constraint begins with `+', then the operand is both read
253 from and written to. */
254 *is_inout = (*p == '+');
255
256 /* Canonicalize the output constraint so that it begins with `='. */
257 if (p != constraint || *is_inout)
258 {
259 char *buf;
260 size_t c_len = strlen (constraint);
261
262 if (p != constraint)
263 warning (0, "output constraint %qc for operand %d "
264 "is not at the beginning",
265 *p, operand_num);
266
267 /* Make a copy of the constraint. */
268 buf = XALLOCAVEC (char, c_len + 1);
269 strcpy (buf, constraint);
270 /* Swap the first character and the `=' or `+'. */
271 buf[p - constraint] = buf[0];
272 /* Make sure the first character is an `='. (Until we do this,
273 it might be a `+'.) */
274 buf[0] = '=';
275 /* Replace the constraint with the canonicalized string. */
276 *constraint_p = ggc_alloc_string (buf, c_len);
277 constraint = *constraint_p;
278 }
279
280 /* Loop through the constraint string. */
281 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
282 switch (*p)
283 {
284 case '+':
285 case '=':
286 error ("operand constraint contains incorrectly positioned "
287 "%<+%> or %<=%>");
288 return false;
289
290 case '%':
291 if (operand_num + 1 == ninputs + noutputs)
292 {
293 error ("%<%%%> constraint used with last operand");
294 return false;
295 }
296 break;
297
298 case '?': case '!': case '*': case '&': case '#':
299 case '$': case '^':
300 case 'E': case 'F': case 'G': case 'H':
301 case 's': case 'i': case 'n':
302 case 'I': case 'J': case 'K': case 'L': case 'M':
303 case 'N': case 'O': case 'P': case ',':
304 break;
305
306 case '0': case '1': case '2': case '3': case '4':
307 case '5': case '6': case '7': case '8': case '9':
308 case '[':
309 error ("matching constraint not valid in output operand");
310 return false;
311
312 case '<': case '>':
313 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
314 excepting those that expand_call created. So match memory
315 and hope. */
316 *allows_mem = true;
317 break;
318
319 case 'g': case 'X':
320 *allows_reg = true;
321 *allows_mem = true;
322 break;
323
324 default:
325 if (!ISALPHA (*p))
326 break;
327 enum constraint_num cn = lookup_constraint (p);
328 if (reg_class_for_constraint (cn) != NO_REGS
329 || insn_extra_address_constraint (cn))
330 *allows_reg = true;
331 else if (insn_extra_memory_constraint (cn))
332 *allows_mem = true;
333 else
334 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
335 break;
336 }
337
338 return true;
339 }
340
341 /* Similar, but for input constraints. */
342
343 bool
344 parse_input_constraint (const char **constraint_p, int input_num,
345 int ninputs, int noutputs, int ninout,
346 const char * const * constraints,
347 bool *allows_mem, bool *allows_reg)
348 {
349 const char *constraint = *constraint_p;
350 const char *orig_constraint = constraint;
351 size_t c_len = strlen (constraint);
352 size_t j;
353 bool saw_match = false;
354
355 /* Assume the constraint doesn't allow the use of either
356 a register or memory. */
357 *allows_mem = false;
358 *allows_reg = false;
359
360 /* Make sure constraint has neither `=', `+', nor '&'. */
361
362 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
363 switch (constraint[j])
364 {
365 case '+': case '=': case '&':
366 if (constraint == orig_constraint)
367 {
368 error ("input operand constraint contains %qc", constraint[j]);
369 return false;
370 }
371 break;
372
373 case '%':
374 if (constraint == orig_constraint
375 && input_num + 1 == ninputs - ninout)
376 {
377 error ("%<%%%> constraint used with last operand");
378 return false;
379 }
380 break;
381
382 case '<': case '>':
383 case '?': case '!': case '*': case '#':
384 case '$': case '^':
385 case 'E': case 'F': case 'G': case 'H':
386 case 's': case 'i': case 'n':
387 case 'I': case 'J': case 'K': case 'L': case 'M':
388 case 'N': case 'O': case 'P': case ',':
389 break;
390
391 /* Whether or not a numeric constraint allows a register is
392 decided by the matching constraint, and so there is no need
393 to do anything special with them. We must handle them in
394 the default case, so that we don't unnecessarily force
395 operands to memory. */
396 case '0': case '1': case '2': case '3': case '4':
397 case '5': case '6': case '7': case '8': case '9':
398 {
399 char *end;
400 unsigned long match;
401
402 saw_match = true;
403
404 match = strtoul (constraint + j, &end, 10);
405 if (match >= (unsigned long) noutputs)
406 {
407 error ("matching constraint references invalid operand number");
408 return false;
409 }
410
411 /* Try and find the real constraint for this dup. Only do this
412 if the matching constraint is the only alternative. */
413 if (*end == '\0'
414 && (j == 0 || (j == 1 && constraint[0] == '%')))
415 {
416 constraint = constraints[match];
417 *constraint_p = constraint;
418 c_len = strlen (constraint);
419 j = 0;
420 /* ??? At the end of the loop, we will skip the first part of
421 the matched constraint. This assumes not only that the
422 other constraint is an output constraint, but also that
423 the '=' or '+' come first. */
424 break;
425 }
426 else
427 j = end - constraint;
428 /* Anticipate increment at end of loop. */
429 j--;
430 }
431 /* Fall through. */
432
433 case 'g': case 'X':
434 *allows_reg = true;
435 *allows_mem = true;
436 break;
437
438 default:
439 if (! ISALPHA (constraint[j]))
440 {
441 error ("invalid punctuation %qc in constraint", constraint[j]);
442 return false;
443 }
444 enum constraint_num cn = lookup_constraint (constraint + j);
445 if (reg_class_for_constraint (cn) != NO_REGS
446 || insn_extra_address_constraint (cn))
447 *allows_reg = true;
448 else if (insn_extra_memory_constraint (cn))
449 *allows_mem = true;
450 else
451 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
452 break;
453 }
454
455 if (saw_match && !*allows_reg)
456 warning (0, "matching constraint does not allow a register");
457
458 return true;
459 }
460
461 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
462 can be an asm-declared register. Called via walk_tree. */
463
464 static tree
465 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
466 void *data)
467 {
468 tree decl = *declp;
469 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
470
471 if (TREE_CODE (decl) == VAR_DECL)
472 {
473 if (DECL_HARD_REGISTER (decl)
474 && REG_P (DECL_RTL (decl))
475 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
476 {
477 rtx reg = DECL_RTL (decl);
478
479 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
480 return decl;
481 }
482 walk_subtrees = 0;
483 }
484 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
485 walk_subtrees = 0;
486 return NULL_TREE;
487 }
488
489 /* If there is an overlap between *REGS and DECL, return the first overlap
490 found. */
491 tree
492 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
493 {
494 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
495 }
496
497
498 /* A subroutine of expand_asm_operands. Check that all operand names
499 are unique. Return true if so. We rely on the fact that these names
500 are identifiers, and so have been canonicalized by get_identifier,
501 so all we need are pointer comparisons. */
502
503 static bool
504 check_unique_operand_names (tree outputs, tree inputs, tree labels)
505 {
506 tree i, j, i_name = NULL_TREE;
507
508 for (i = outputs; i ; i = TREE_CHAIN (i))
509 {
510 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
511 if (! i_name)
512 continue;
513
514 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
515 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
516 goto failure;
517 }
518
519 for (i = inputs; i ; i = TREE_CHAIN (i))
520 {
521 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
522 if (! i_name)
523 continue;
524
525 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
526 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
527 goto failure;
528 for (j = outputs; j ; j = TREE_CHAIN (j))
529 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
530 goto failure;
531 }
532
533 for (i = labels; i ; i = TREE_CHAIN (i))
534 {
535 i_name = TREE_PURPOSE (i);
536 if (! i_name)
537 continue;
538
539 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
540 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
541 goto failure;
542 for (j = inputs; j ; j = TREE_CHAIN (j))
543 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
544 goto failure;
545 }
546
547 return true;
548
549 failure:
550 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
551 return false;
552 }
553
554 /* Resolve the names of the operands in *POUTPUTS and *PINPUTS to numbers,
555 and replace the name expansions in STRING and in the constraints to
556 those numbers. This is generally done in the front end while creating
557 the ASM_EXPR generic tree that eventually becomes the GIMPLE_ASM. */
558
559 tree
560 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
561 {
562 char *buffer;
563 char *p;
564 const char *c;
565 tree t;
566
567 check_unique_operand_names (outputs, inputs, labels);
568
569 /* Substitute [<name>] in input constraint strings. There should be no
570 named operands in output constraints. */
571 for (t = inputs; t ; t = TREE_CHAIN (t))
572 {
573 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
574 if (strchr (c, '[') != NULL)
575 {
576 p = buffer = xstrdup (c);
577 while ((p = strchr (p, '[')) != NULL)
578 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
579 TREE_VALUE (TREE_PURPOSE (t))
580 = build_string (strlen (buffer), buffer);
581 free (buffer);
582 }
583 }
584
585 /* Now check for any needed substitutions in the template. */
586 c = TREE_STRING_POINTER (string);
587 while ((c = strchr (c, '%')) != NULL)
588 {
589 if (c[1] == '[')
590 break;
591 else if (ISALPHA (c[1]) && c[2] == '[')
592 break;
593 else
594 {
595 c += 1 + (c[1] == '%');
596 continue;
597 }
598 }
599
600 if (c)
601 {
602 /* OK, we need to make a copy so we can perform the substitutions.
603 Assume that we will not need extra space--we get to remove '['
604 and ']', which means we cannot have a problem until we have more
605 than 999 operands. */
606 buffer = xstrdup (TREE_STRING_POINTER (string));
607 p = buffer + (c - TREE_STRING_POINTER (string));
608
609 while ((p = strchr (p, '%')) != NULL)
610 {
611 if (p[1] == '[')
612 p += 1;
613 else if (ISALPHA (p[1]) && p[2] == '[')
614 p += 2;
615 else
616 {
617 p += 1 + (p[1] == '%');
618 continue;
619 }
620
621 p = resolve_operand_name_1 (p, outputs, inputs, labels);
622 }
623
624 string = build_string (strlen (buffer), buffer);
625 free (buffer);
626 }
627
628 return string;
629 }
630
631 /* A subroutine of resolve_operand_names. P points to the '[' for a
632 potential named operand of the form [<name>]. In place, replace
633 the name and brackets with a number. Return a pointer to the
634 balance of the string after substitution. */
635
636 static char *
637 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
638 {
639 char *q;
640 int op;
641 tree t;
642
643 /* Collect the operand name. */
644 q = strchr (++p, ']');
645 if (!q)
646 {
647 error ("missing close brace for named operand");
648 return strchr (p, '\0');
649 }
650 *q = '\0';
651
652 /* Resolve the name to a number. */
653 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
654 {
655 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
656 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
657 goto found;
658 }
659 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
660 {
661 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
662 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
663 goto found;
664 }
665 for (t = labels; t ; t = TREE_CHAIN (t), op++)
666 {
667 tree name = TREE_PURPOSE (t);
668 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
669 goto found;
670 }
671
672 error ("undefined named operand %qs", identifier_to_locale (p));
673 op = 0;
674
675 found:
676 /* Replace the name with the number. Unfortunately, not all libraries
677 get the return value of sprintf correct, so search for the end of the
678 generated string by hand. */
679 sprintf (--p, "%d", op);
680 p = strchr (p, '\0');
681
682 /* Verify the no extra buffer space assumption. */
683 gcc_assert (p <= q);
684
685 /* Shift the rest of the buffer down to fill the gap. */
686 memmove (p, q + 1, strlen (q + 1) + 1);
687
688 return p;
689 }
690 \f
691
692 /* Generate RTL to return directly from the current function.
693 (That is, we bypass any return value.) */
694
695 void
696 expand_naked_return (void)
697 {
698 rtx_code_label *end_label;
699
700 clear_pending_stack_adjust ();
701 do_pending_stack_adjust ();
702
703 end_label = naked_return_label;
704 if (end_label == 0)
705 end_label = naked_return_label = gen_label_rtx ();
706
707 emit_jump (end_label);
708 }
709
710 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
711 is the probability of jumping to LABEL. */
712 static void
713 do_jump_if_equal (machine_mode mode, rtx op0, rtx op1, rtx_code_label *label,
714 int unsignedp, int prob)
715 {
716 gcc_assert (prob <= REG_BR_PROB_BASE);
717 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
718 NULL_RTX, NULL, label, prob);
719 }
720 \f
721 /* Do the insertion of a case label into case_list. The labels are
722 fed to us in descending order from the sorted vector of case labels used
723 in the tree part of the middle end. So the list we construct is
724 sorted in ascending order.
725
726 LABEL is the case label to be inserted. LOW and HIGH are the bounds
727 against which the index is compared to jump to LABEL and PROB is the
728 estimated probability LABEL is reached from the switch statement. */
729
730 static struct case_node *
731 add_case_node (struct case_node *head, tree low, tree high,
732 tree label, int prob, pool_allocator<case_node> &case_node_pool)
733 {
734 struct case_node *r;
735
736 gcc_checking_assert (low);
737 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
738
739 /* Add this label to the chain. */
740 r = case_node_pool.allocate ();
741 r->low = low;
742 r->high = high;
743 r->code_label = label;
744 r->parent = r->left = NULL;
745 r->prob = prob;
746 r->subtree_prob = prob;
747 r->right = head;
748 return r;
749 }
750 \f
751 /* Dump ROOT, a list or tree of case nodes, to file. */
752
753 static void
754 dump_case_nodes (FILE *f, struct case_node *root,
755 int indent_step, int indent_level)
756 {
757 if (root == 0)
758 return;
759 indent_level++;
760
761 dump_case_nodes (f, root->left, indent_step, indent_level);
762
763 fputs (";; ", f);
764 fprintf (f, "%*s", indent_step * indent_level, "");
765 print_dec (root->low, f, TYPE_SIGN (TREE_TYPE (root->low)));
766 if (!tree_int_cst_equal (root->low, root->high))
767 {
768 fprintf (f, " ... ");
769 print_dec (root->high, f, TYPE_SIGN (TREE_TYPE (root->high)));
770 }
771 fputs ("\n", f);
772
773 dump_case_nodes (f, root->right, indent_step, indent_level);
774 }
775 \f
776 /* Return the smallest number of different values for which it is best to use a
777 jump-table instead of a tree of conditional branches. */
778
779 static unsigned int
780 case_values_threshold (void)
781 {
782 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
783
784 if (threshold == 0)
785 threshold = targetm.case_values_threshold ();
786
787 return threshold;
788 }
789
790 /* Return true if a switch should be expanded as a decision tree.
791 RANGE is the difference between highest and lowest case.
792 UNIQ is number of unique case node targets, not counting the default case.
793 COUNT is the number of comparisons needed, not counting the default case. */
794
795 static bool
796 expand_switch_as_decision_tree_p (tree range,
797 unsigned int uniq ATTRIBUTE_UNUSED,
798 unsigned int count)
799 {
800 int max_ratio;
801
802 /* If neither casesi or tablejump is available, or flag_jump_tables
803 over-ruled us, we really have no choice. */
804 if (!targetm.have_casesi () && !targetm.have_tablejump ())
805 return true;
806 if (!flag_jump_tables)
807 return true;
808 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
809 if (flag_pic)
810 return true;
811 #endif
812
813 /* If the switch is relatively small such that the cost of one
814 indirect jump on the target are higher than the cost of a
815 decision tree, go with the decision tree.
816
817 If range of values is much bigger than number of values,
818 or if it is too large to represent in a HOST_WIDE_INT,
819 make a sequence of conditional branches instead of a dispatch.
820
821 The definition of "much bigger" depends on whether we are
822 optimizing for size or for speed. If the former, the maximum
823 ratio range/count = 3, because this was found to be the optimal
824 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
825 10 is much older, and was probably selected after an extensive
826 benchmarking investigation on numerous platforms. Or maybe it
827 just made sense to someone at some point in the history of GCC,
828 who knows... */
829 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
830 if (count < case_values_threshold ()
831 || ! tree_fits_uhwi_p (range)
832 || compare_tree_int (range, max_ratio * count) > 0)
833 return true;
834
835 return false;
836 }
837
838 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
839 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
840 DEFAULT_PROB is the estimated probability that it jumps to
841 DEFAULT_LABEL.
842
843 We generate a binary decision tree to select the appropriate target
844 code. This is done as follows:
845
846 If the index is a short or char that we do not have
847 an insn to handle comparisons directly, convert it to
848 a full integer now, rather than letting each comparison
849 generate the conversion.
850
851 Load the index into a register.
852
853 The list of cases is rearranged into a binary tree,
854 nearly optimal assuming equal probability for each case.
855
856 The tree is transformed into RTL, eliminating redundant
857 test conditions at the same time.
858
859 If program flow could reach the end of the decision tree
860 an unconditional jump to the default code is emitted.
861
862 The above process is unaware of the CFG. The caller has to fix up
863 the CFG itself. This is done in cfgexpand.c. */
864
865 static void
866 emit_case_decision_tree (tree index_expr, tree index_type,
867 case_node_ptr case_list, rtx_code_label *default_label,
868 int default_prob)
869 {
870 rtx index = expand_normal (index_expr);
871
872 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
873 && ! have_insn_for (COMPARE, GET_MODE (index)))
874 {
875 int unsignedp = TYPE_UNSIGNED (index_type);
876 machine_mode wider_mode;
877 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
878 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
879 if (have_insn_for (COMPARE, wider_mode))
880 {
881 index = convert_to_mode (wider_mode, index, unsignedp);
882 break;
883 }
884 }
885
886 do_pending_stack_adjust ();
887
888 if (MEM_P (index))
889 {
890 index = copy_to_reg (index);
891 if (TREE_CODE (index_expr) == SSA_NAME)
892 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
893 }
894
895 balance_case_nodes (&case_list, NULL);
896
897 if (dump_file && (dump_flags & TDF_DETAILS))
898 {
899 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
900 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
901 dump_case_nodes (dump_file, case_list, indent_step, 0);
902 }
903
904 emit_case_nodes (index, case_list, default_label, default_prob, index_type);
905 if (default_label)
906 emit_jump (default_label);
907 }
908
909 /* Return the sum of probabilities of outgoing edges of basic block BB. */
910
911 static int
912 get_outgoing_edge_probs (basic_block bb)
913 {
914 edge e;
915 edge_iterator ei;
916 int prob_sum = 0;
917 if (!bb)
918 return 0;
919 FOR_EACH_EDGE (e, ei, bb->succs)
920 prob_sum += e->probability;
921 return prob_sum;
922 }
923
924 /* Computes the conditional probability of jumping to a target if the branch
925 instruction is executed.
926 TARGET_PROB is the estimated probability of jumping to a target relative
927 to some basic block BB.
928 BASE_PROB is the probability of reaching the branch instruction relative
929 to the same basic block BB. */
930
931 static inline int
932 conditional_probability (int target_prob, int base_prob)
933 {
934 if (base_prob > 0)
935 {
936 gcc_assert (target_prob >= 0);
937 gcc_assert (target_prob <= base_prob);
938 return GCOV_COMPUTE_SCALE (target_prob, base_prob);
939 }
940 return -1;
941 }
942
943 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
944 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
945 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
946 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
947
948 First, a jump insn is emitted. First we try "casesi". If that
949 fails, try "tablejump". A target *must* have one of them (or both).
950
951 Then, a table with the target labels is emitted.
952
953 The process is unaware of the CFG. The caller has to fix up
954 the CFG itself. This is done in cfgexpand.c. */
955
956 static void
957 emit_case_dispatch_table (tree index_expr, tree index_type,
958 struct case_node *case_list, rtx default_label,
959 tree minval, tree maxval, tree range,
960 basic_block stmt_bb)
961 {
962 int i, ncases;
963 struct case_node *n;
964 rtx *labelvec;
965 rtx_insn *fallback_label = label_rtx (case_list->code_label);
966 rtx_code_label *table_label = gen_label_rtx ();
967 bool has_gaps = false;
968 edge default_edge = stmt_bb ? EDGE_SUCC (stmt_bb, 0) : NULL;
969 int default_prob = default_edge ? default_edge->probability : 0;
970 int base = get_outgoing_edge_probs (stmt_bb);
971 bool try_with_tablejump = false;
972
973 int new_default_prob = conditional_probability (default_prob,
974 base);
975
976 if (! try_casesi (index_type, index_expr, minval, range,
977 table_label, default_label, fallback_label,
978 new_default_prob))
979 {
980 /* Index jumptables from zero for suitable values of minval to avoid
981 a subtraction. For the rationale see:
982 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
983 if (optimize_insn_for_speed_p ()
984 && compare_tree_int (minval, 0) > 0
985 && compare_tree_int (minval, 3) < 0)
986 {
987 minval = build_int_cst (index_type, 0);
988 range = maxval;
989 has_gaps = true;
990 }
991 try_with_tablejump = true;
992 }
993
994 /* Get table of labels to jump to, in order of case index. */
995
996 ncases = tree_to_shwi (range) + 1;
997 labelvec = XALLOCAVEC (rtx, ncases);
998 memset (labelvec, 0, ncases * sizeof (rtx));
999
1000 for (n = case_list; n; n = n->right)
1001 {
1002 /* Compute the low and high bounds relative to the minimum
1003 value since that should fit in a HOST_WIDE_INT while the
1004 actual values may not. */
1005 HOST_WIDE_INT i_low
1006 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1007 n->low, minval));
1008 HOST_WIDE_INT i_high
1009 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1010 n->high, minval));
1011 HOST_WIDE_INT i;
1012
1013 for (i = i_low; i <= i_high; i ++)
1014 labelvec[i]
1015 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1016 }
1017
1018 /* Fill in the gaps with the default. We may have gaps at
1019 the beginning if we tried to avoid the minval subtraction,
1020 so substitute some label even if the default label was
1021 deemed unreachable. */
1022 if (!default_label)
1023 default_label = fallback_label;
1024 for (i = 0; i < ncases; i++)
1025 if (labelvec[i] == 0)
1026 {
1027 has_gaps = true;
1028 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1029 }
1030
1031 if (has_gaps)
1032 {
1033 /* There is at least one entry in the jump table that jumps
1034 to default label. The default label can either be reached
1035 through the indirect jump or the direct conditional jump
1036 before that. Split the probability of reaching the
1037 default label among these two jumps. */
1038 new_default_prob = conditional_probability (default_prob/2,
1039 base);
1040 default_prob /= 2;
1041 base -= default_prob;
1042 }
1043 else
1044 {
1045 base -= default_prob;
1046 default_prob = 0;
1047 }
1048
1049 if (default_edge)
1050 default_edge->probability = default_prob;
1051
1052 /* We have altered the probability of the default edge. So the probabilities
1053 of all other edges need to be adjusted so that it sums up to
1054 REG_BR_PROB_BASE. */
1055 if (base)
1056 {
1057 edge e;
1058 edge_iterator ei;
1059 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
1060 e->probability = GCOV_COMPUTE_SCALE (e->probability, base);
1061 }
1062
1063 if (try_with_tablejump)
1064 {
1065 bool ok = try_tablejump (index_type, index_expr, minval, range,
1066 table_label, default_label, new_default_prob);
1067 gcc_assert (ok);
1068 }
1069 /* Output the table. */
1070 emit_label (table_label);
1071
1072 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1073 emit_jump_table_data (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1074 gen_rtx_LABEL_REF (Pmode,
1075 table_label),
1076 gen_rtvec_v (ncases, labelvec),
1077 const0_rtx, const0_rtx));
1078 else
1079 emit_jump_table_data (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1080 gen_rtvec_v (ncases, labelvec)));
1081
1082 /* Record no drop-through after the table. */
1083 emit_barrier ();
1084 }
1085
1086 /* Reset the aux field of all outgoing edges of basic block BB. */
1087
1088 static inline void
1089 reset_out_edges_aux (basic_block bb)
1090 {
1091 edge e;
1092 edge_iterator ei;
1093 FOR_EACH_EDGE (e, ei, bb->succs)
1094 e->aux = (void *)0;
1095 }
1096
1097 /* Compute the number of case labels that correspond to each outgoing edge of
1098 STMT. Record this information in the aux field of the edge. */
1099
1100 static inline void
1101 compute_cases_per_edge (gswitch *stmt)
1102 {
1103 basic_block bb = gimple_bb (stmt);
1104 reset_out_edges_aux (bb);
1105 int ncases = gimple_switch_num_labels (stmt);
1106 for (int i = ncases - 1; i >= 1; --i)
1107 {
1108 tree elt = gimple_switch_label (stmt, i);
1109 tree lab = CASE_LABEL (elt);
1110 basic_block case_bb = label_to_block_fn (cfun, lab);
1111 edge case_edge = find_edge (bb, case_bb);
1112 case_edge->aux = (void *)((intptr_t)(case_edge->aux) + 1);
1113 }
1114 }
1115
1116 /* Terminate a case (Pascal/Ada) or switch (C) statement
1117 in which ORIG_INDEX is the expression to be tested.
1118 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
1119 type as given in the source before any compiler conversions.
1120 Generate the code to test it and jump to the right place. */
1121
1122 void
1123 expand_case (gswitch *stmt)
1124 {
1125 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
1126 rtx_code_label *default_label = NULL;
1127 unsigned int count, uniq;
1128 int i;
1129 int ncases = gimple_switch_num_labels (stmt);
1130 tree index_expr = gimple_switch_index (stmt);
1131 tree index_type = TREE_TYPE (index_expr);
1132 tree elt;
1133 basic_block bb = gimple_bb (stmt);
1134
1135 /* A list of case labels; it is first built as a list and it may then
1136 be rearranged into a nearly balanced binary tree. */
1137 struct case_node *case_list = 0;
1138
1139 /* A pool for case nodes. */
1140 pool_allocator<case_node> case_node_pool ("struct case_node pool", 100);
1141
1142 /* An ERROR_MARK occurs for various reasons including invalid data type.
1143 ??? Can this still happen, with GIMPLE and all? */
1144 if (index_type == error_mark_node)
1145 return;
1146
1147 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
1148 expressions being INTEGER_CST. */
1149 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
1150
1151
1152 do_pending_stack_adjust ();
1153
1154 /* Find the default case target label. */
1155 default_label = jump_target_rtx
1156 (CASE_LABEL (gimple_switch_default_label (stmt)));
1157 edge default_edge = EDGE_SUCC (bb, 0);
1158 int default_prob = default_edge->probability;
1159
1160 /* Get upper and lower bounds of case values. */
1161 elt = gimple_switch_label (stmt, 1);
1162 minval = fold_convert (index_type, CASE_LOW (elt));
1163 elt = gimple_switch_label (stmt, ncases - 1);
1164 if (CASE_HIGH (elt))
1165 maxval = fold_convert (index_type, CASE_HIGH (elt));
1166 else
1167 maxval = fold_convert (index_type, CASE_LOW (elt));
1168
1169 /* Compute span of values. */
1170 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
1171
1172 /* Listify the labels queue and gather some numbers to decide
1173 how to expand this switch(). */
1174 uniq = 0;
1175 count = 0;
1176 hash_set<tree> seen_labels;
1177 compute_cases_per_edge (stmt);
1178
1179 for (i = ncases - 1; i >= 1; --i)
1180 {
1181 elt = gimple_switch_label (stmt, i);
1182 tree low = CASE_LOW (elt);
1183 gcc_assert (low);
1184 tree high = CASE_HIGH (elt);
1185 gcc_assert (! high || tree_int_cst_lt (low, high));
1186 tree lab = CASE_LABEL (elt);
1187
1188 /* Count the elements.
1189 A range counts double, since it requires two compares. */
1190 count++;
1191 if (high)
1192 count++;
1193
1194 /* If we have not seen this label yet, then increase the
1195 number of unique case node targets seen. */
1196 if (!seen_labels.add (lab))
1197 uniq++;
1198
1199 /* The bounds on the case range, LOW and HIGH, have to be converted
1200 to case's index type TYPE. Note that the original type of the
1201 case index in the source code is usually "lost" during
1202 gimplification due to type promotion, but the case labels retain the
1203 original type. Make sure to drop overflow flags. */
1204 low = fold_convert (index_type, low);
1205 if (TREE_OVERFLOW (low))
1206 low = wide_int_to_tree (index_type, low);
1207
1208 /* The canonical from of a case label in GIMPLE is that a simple case
1209 has an empty CASE_HIGH. For the casesi and tablejump expanders,
1210 the back ends want simple cases to have high == low. */
1211 if (! high)
1212 high = low;
1213 high = fold_convert (index_type, high);
1214 if (TREE_OVERFLOW (high))
1215 high = wide_int_to_tree (index_type, high);
1216
1217 basic_block case_bb = label_to_block_fn (cfun, lab);
1218 edge case_edge = find_edge (bb, case_bb);
1219 case_list = add_case_node (
1220 case_list, low, high, lab,
1221 case_edge->probability / (intptr_t)(case_edge->aux),
1222 case_node_pool);
1223 }
1224 reset_out_edges_aux (bb);
1225
1226 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
1227 destination, such as one with a default case only.
1228 It also removes cases that are out of range for the switch
1229 type, so we should never get a zero here. */
1230 gcc_assert (count > 0);
1231
1232 rtx_insn *before_case = get_last_insn ();
1233
1234 /* Decide how to expand this switch.
1235 The two options at this point are a dispatch table (casesi or
1236 tablejump) or a decision tree. */
1237
1238 if (expand_switch_as_decision_tree_p (range, uniq, count))
1239 emit_case_decision_tree (index_expr, index_type,
1240 case_list, default_label,
1241 default_prob);
1242 else
1243 emit_case_dispatch_table (index_expr, index_type,
1244 case_list, default_label,
1245 minval, maxval, range, bb);
1246
1247 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1248
1249 free_temp_slots ();
1250 }
1251
1252 /* Expand the dispatch to a short decrement chain if there are few cases
1253 to dispatch to. Likewise if neither casesi nor tablejump is available,
1254 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
1255 tablejump. The index mode is always the mode of integer_type_node.
1256 Trap if no case matches the index.
1257
1258 DISPATCH_INDEX is the index expression to switch on. It should be a
1259 memory or register operand.
1260
1261 DISPATCH_TABLE is a set of case labels. The set should be sorted in
1262 ascending order, be contiguous, starting with value 0, and contain only
1263 single-valued case labels. */
1264
1265 void
1266 expand_sjlj_dispatch_table (rtx dispatch_index,
1267 vec<tree> dispatch_table)
1268 {
1269 tree index_type = integer_type_node;
1270 machine_mode index_mode = TYPE_MODE (index_type);
1271
1272 int ncases = dispatch_table.length ();
1273
1274 do_pending_stack_adjust ();
1275 rtx_insn *before_case = get_last_insn ();
1276
1277 /* Expand as a decrement-chain if there are 5 or fewer dispatch
1278 labels. This covers more than 98% of the cases in libjava,
1279 and seems to be a reasonable compromise between the "old way"
1280 of expanding as a decision tree or dispatch table vs. the "new
1281 way" with decrement chain or dispatch table. */
1282 if (dispatch_table.length () <= 5
1283 || (!targetm.have_casesi () && !targetm.have_tablejump ())
1284 || !flag_jump_tables)
1285 {
1286 /* Expand the dispatch as a decrement chain:
1287
1288 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
1289
1290 ==>
1291
1292 if (index == 0) do_0; else index--;
1293 if (index == 0) do_1; else index--;
1294 ...
1295 if (index == 0) do_N; else index--;
1296
1297 This is more efficient than a dispatch table on most machines.
1298 The last "index--" is redundant but the code is trivially dead
1299 and will be cleaned up by later passes. */
1300 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
1301 rtx zero = CONST0_RTX (index_mode);
1302 for (int i = 0; i < ncases; i++)
1303 {
1304 tree elt = dispatch_table[i];
1305 rtx_code_label *lab = jump_target_rtx (CASE_LABEL (elt));
1306 do_jump_if_equal (index_mode, index, zero, lab, 0, -1);
1307 force_expand_binop (index_mode, sub_optab,
1308 index, CONST1_RTX (index_mode),
1309 index, 0, OPTAB_DIRECT);
1310 }
1311 }
1312 else
1313 {
1314 /* Similar to expand_case, but much simpler. */
1315 struct case_node *case_list = 0;
1316 pool_allocator<case_node> case_node_pool ("struct sjlj_case pool",
1317 ncases);
1318 tree index_expr = make_tree (index_type, dispatch_index);
1319 tree minval = build_int_cst (index_type, 0);
1320 tree maxval = CASE_LOW (dispatch_table.last ());
1321 tree range = maxval;
1322 rtx_code_label *default_label = gen_label_rtx ();
1323
1324 for (int i = ncases - 1; i >= 0; --i)
1325 {
1326 tree elt = dispatch_table[i];
1327 tree low = CASE_LOW (elt);
1328 tree lab = CASE_LABEL (elt);
1329 case_list = add_case_node (case_list, low, low, lab, 0, case_node_pool);
1330 }
1331
1332 emit_case_dispatch_table (index_expr, index_type,
1333 case_list, default_label,
1334 minval, maxval, range,
1335 BLOCK_FOR_INSN (before_case));
1336 emit_label (default_label);
1337 }
1338
1339 /* Dispatching something not handled? Trap! */
1340 expand_builtin_trap ();
1341
1342 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1343
1344 free_temp_slots ();
1345 }
1346
1347 \f
1348 /* Take an ordered list of case nodes
1349 and transform them into a near optimal binary tree,
1350 on the assumption that any target code selection value is as
1351 likely as any other.
1352
1353 The transformation is performed by splitting the ordered
1354 list into two equal sections plus a pivot. The parts are
1355 then attached to the pivot as left and right branches. Each
1356 branch is then transformed recursively. */
1357
1358 static void
1359 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
1360 {
1361 case_node_ptr np;
1362
1363 np = *head;
1364 if (np)
1365 {
1366 int i = 0;
1367 int ranges = 0;
1368 case_node_ptr *npp;
1369 case_node_ptr left;
1370
1371 /* Count the number of entries on branch. Also count the ranges. */
1372
1373 while (np)
1374 {
1375 if (!tree_int_cst_equal (np->low, np->high))
1376 ranges++;
1377
1378 i++;
1379 np = np->right;
1380 }
1381
1382 if (i > 2)
1383 {
1384 /* Split this list if it is long enough for that to help. */
1385 npp = head;
1386 left = *npp;
1387
1388 /* If there are just three nodes, split at the middle one. */
1389 if (i == 3)
1390 npp = &(*npp)->right;
1391 else
1392 {
1393 /* Find the place in the list that bisects the list's total cost,
1394 where ranges count as 2.
1395 Here I gets half the total cost. */
1396 i = (i + ranges + 1) / 2;
1397 while (1)
1398 {
1399 /* Skip nodes while their cost does not reach that amount. */
1400 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
1401 i--;
1402 i--;
1403 if (i <= 0)
1404 break;
1405 npp = &(*npp)->right;
1406 }
1407 }
1408 *head = np = *npp;
1409 *npp = 0;
1410 np->parent = parent;
1411 np->left = left;
1412
1413 /* Optimize each of the two split parts. */
1414 balance_case_nodes (&np->left, np);
1415 balance_case_nodes (&np->right, np);
1416 np->subtree_prob = np->prob;
1417 np->subtree_prob += np->left->subtree_prob;
1418 np->subtree_prob += np->right->subtree_prob;
1419 }
1420 else
1421 {
1422 /* Else leave this branch as one level,
1423 but fill in `parent' fields. */
1424 np = *head;
1425 np->parent = parent;
1426 np->subtree_prob = np->prob;
1427 for (; np->right; np = np->right)
1428 {
1429 np->right->parent = np;
1430 (*head)->subtree_prob += np->right->subtree_prob;
1431 }
1432 }
1433 }
1434 }
1435 \f
1436 /* Search the parent sections of the case node tree
1437 to see if a test for the lower bound of NODE would be redundant.
1438 INDEX_TYPE is the type of the index expression.
1439
1440 The instructions to generate the case decision tree are
1441 output in the same order as nodes are processed so it is
1442 known that if a parent node checks the range of the current
1443 node minus one that the current node is bounded at its lower
1444 span. Thus the test would be redundant. */
1445
1446 static int
1447 node_has_low_bound (case_node_ptr node, tree index_type)
1448 {
1449 tree low_minus_one;
1450 case_node_ptr pnode;
1451
1452 /* If the lower bound of this node is the lowest value in the index type,
1453 we need not test it. */
1454
1455 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
1456 return 1;
1457
1458 /* If this node has a left branch, the value at the left must be less
1459 than that at this node, so it cannot be bounded at the bottom and
1460 we need not bother testing any further. */
1461
1462 if (node->left)
1463 return 0;
1464
1465 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
1466 node->low,
1467 build_int_cst (TREE_TYPE (node->low), 1));
1468
1469 /* If the subtraction above overflowed, we can't verify anything.
1470 Otherwise, look for a parent that tests our value - 1. */
1471
1472 if (! tree_int_cst_lt (low_minus_one, node->low))
1473 return 0;
1474
1475 for (pnode = node->parent; pnode; pnode = pnode->parent)
1476 if (tree_int_cst_equal (low_minus_one, pnode->high))
1477 return 1;
1478
1479 return 0;
1480 }
1481
1482 /* Search the parent sections of the case node tree
1483 to see if a test for the upper bound of NODE would be redundant.
1484 INDEX_TYPE is the type of the index expression.
1485
1486 The instructions to generate the case decision tree are
1487 output in the same order as nodes are processed so it is
1488 known that if a parent node checks the range of the current
1489 node plus one that the current node is bounded at its upper
1490 span. Thus the test would be redundant. */
1491
1492 static int
1493 node_has_high_bound (case_node_ptr node, tree index_type)
1494 {
1495 tree high_plus_one;
1496 case_node_ptr pnode;
1497
1498 /* If there is no upper bound, obviously no test is needed. */
1499
1500 if (TYPE_MAX_VALUE (index_type) == NULL)
1501 return 1;
1502
1503 /* If the upper bound of this node is the highest value in the type
1504 of the index expression, we need not test against it. */
1505
1506 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
1507 return 1;
1508
1509 /* If this node has a right branch, the value at the right must be greater
1510 than that at this node, so it cannot be bounded at the top and
1511 we need not bother testing any further. */
1512
1513 if (node->right)
1514 return 0;
1515
1516 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
1517 node->high,
1518 build_int_cst (TREE_TYPE (node->high), 1));
1519
1520 /* If the addition above overflowed, we can't verify anything.
1521 Otherwise, look for a parent that tests our value + 1. */
1522
1523 if (! tree_int_cst_lt (node->high, high_plus_one))
1524 return 0;
1525
1526 for (pnode = node->parent; pnode; pnode = pnode->parent)
1527 if (tree_int_cst_equal (high_plus_one, pnode->low))
1528 return 1;
1529
1530 return 0;
1531 }
1532
1533 /* Search the parent sections of the
1534 case node tree to see if both tests for the upper and lower
1535 bounds of NODE would be redundant. */
1536
1537 static int
1538 node_is_bounded (case_node_ptr node, tree index_type)
1539 {
1540 return (node_has_low_bound (node, index_type)
1541 && node_has_high_bound (node, index_type));
1542 }
1543 \f
1544
1545 /* Emit step-by-step code to select a case for the value of INDEX.
1546 The thus generated decision tree follows the form of the
1547 case-node binary tree NODE, whose nodes represent test conditions.
1548 INDEX_TYPE is the type of the index of the switch.
1549
1550 Care is taken to prune redundant tests from the decision tree
1551 by detecting any boundary conditions already checked by
1552 emitted rtx. (See node_has_high_bound, node_has_low_bound
1553 and node_is_bounded, above.)
1554
1555 Where the test conditions can be shown to be redundant we emit
1556 an unconditional jump to the target code. As a further
1557 optimization, the subordinates of a tree node are examined to
1558 check for bounded nodes. In this case conditional and/or
1559 unconditional jumps as a result of the boundary check for the
1560 current node are arranged to target the subordinates associated
1561 code for out of bound conditions on the current node.
1562
1563 We can assume that when control reaches the code generated here,
1564 the index value has already been compared with the parents
1565 of this node, and determined to be on the same side of each parent
1566 as this node is. Thus, if this node tests for the value 51,
1567 and a parent tested for 52, we don't need to consider
1568 the possibility of a value greater than 51. If another parent
1569 tests for the value 50, then this node need not test anything. */
1570
1571 static void
1572 emit_case_nodes (rtx index, case_node_ptr node, rtx_code_label *default_label,
1573 int default_prob, tree index_type)
1574 {
1575 /* If INDEX has an unsigned type, we must make unsigned branches. */
1576 int unsignedp = TYPE_UNSIGNED (index_type);
1577 int probability;
1578 int prob = node->prob, subtree_prob = node->subtree_prob;
1579 machine_mode mode = GET_MODE (index);
1580 machine_mode imode = TYPE_MODE (index_type);
1581
1582 /* Handle indices detected as constant during RTL expansion. */
1583 if (mode == VOIDmode)
1584 mode = imode;
1585
1586 /* See if our parents have already tested everything for us.
1587 If they have, emit an unconditional jump for this node. */
1588 if (node_is_bounded (node, index_type))
1589 emit_jump (label_rtx (node->code_label));
1590
1591 else if (tree_int_cst_equal (node->low, node->high))
1592 {
1593 probability = conditional_probability (prob, subtree_prob + default_prob);
1594 /* Node is single valued. First see if the index expression matches
1595 this node and then check our children, if any. */
1596 do_jump_if_equal (mode, index,
1597 convert_modes (mode, imode,
1598 expand_normal (node->low),
1599 unsignedp),
1600 jump_target_rtx (node->code_label),
1601 unsignedp, probability);
1602 /* Since this case is taken at this point, reduce its weight from
1603 subtree_weight. */
1604 subtree_prob -= prob;
1605 if (node->right != 0 && node->left != 0)
1606 {
1607 /* This node has children on both sides.
1608 Dispatch to one side or the other
1609 by comparing the index value with this node's value.
1610 If one subtree is bounded, check that one first,
1611 so we can avoid real branches in the tree. */
1612
1613 if (node_is_bounded (node->right, index_type))
1614 {
1615 probability = conditional_probability (
1616 node->right->prob,
1617 subtree_prob + default_prob);
1618 emit_cmp_and_jump_insns (index,
1619 convert_modes
1620 (mode, imode,
1621 expand_normal (node->high),
1622 unsignedp),
1623 GT, NULL_RTX, mode, unsignedp,
1624 label_rtx (node->right->code_label),
1625 probability);
1626 emit_case_nodes (index, node->left, default_label, default_prob,
1627 index_type);
1628 }
1629
1630 else if (node_is_bounded (node->left, index_type))
1631 {
1632 probability = conditional_probability (
1633 node->left->prob,
1634 subtree_prob + default_prob);
1635 emit_cmp_and_jump_insns (index,
1636 convert_modes
1637 (mode, imode,
1638 expand_normal (node->high),
1639 unsignedp),
1640 LT, NULL_RTX, mode, unsignedp,
1641 label_rtx (node->left->code_label),
1642 probability);
1643 emit_case_nodes (index, node->right, default_label, default_prob,
1644 index_type);
1645 }
1646
1647 /* If both children are single-valued cases with no
1648 children, finish up all the work. This way, we can save
1649 one ordered comparison. */
1650 else if (tree_int_cst_equal (node->right->low, node->right->high)
1651 && node->right->left == 0
1652 && node->right->right == 0
1653 && tree_int_cst_equal (node->left->low, node->left->high)
1654 && node->left->left == 0
1655 && node->left->right == 0)
1656 {
1657 /* Neither node is bounded. First distinguish the two sides;
1658 then emit the code for one side at a time. */
1659
1660 /* See if the value matches what the right hand side
1661 wants. */
1662 probability = conditional_probability (
1663 node->right->prob,
1664 subtree_prob + default_prob);
1665 do_jump_if_equal (mode, index,
1666 convert_modes (mode, imode,
1667 expand_normal (node->right->low),
1668 unsignedp),
1669 jump_target_rtx (node->right->code_label),
1670 unsignedp, probability);
1671
1672 /* See if the value matches what the left hand side
1673 wants. */
1674 probability = conditional_probability (
1675 node->left->prob,
1676 subtree_prob + default_prob);
1677 do_jump_if_equal (mode, index,
1678 convert_modes (mode, imode,
1679 expand_normal (node->left->low),
1680 unsignedp),
1681 jump_target_rtx (node->left->code_label),
1682 unsignedp, probability);
1683 }
1684
1685 else
1686 {
1687 /* Neither node is bounded. First distinguish the two sides;
1688 then emit the code for one side at a time. */
1689
1690 tree test_label
1691 = build_decl (curr_insn_location (),
1692 LABEL_DECL, NULL_TREE, void_type_node);
1693
1694 /* The default label could be reached either through the right
1695 subtree or the left subtree. Divide the probability
1696 equally. */
1697 probability = conditional_probability (
1698 node->right->subtree_prob + default_prob/2,
1699 subtree_prob + default_prob);
1700 /* See if the value is on the right. */
1701 emit_cmp_and_jump_insns (index,
1702 convert_modes
1703 (mode, imode,
1704 expand_normal (node->high),
1705 unsignedp),
1706 GT, NULL_RTX, mode, unsignedp,
1707 label_rtx (test_label),
1708 probability);
1709 default_prob /= 2;
1710
1711 /* Value must be on the left.
1712 Handle the left-hand subtree. */
1713 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1714 /* If left-hand subtree does nothing,
1715 go to default. */
1716 if (default_label)
1717 emit_jump (default_label);
1718
1719 /* Code branches here for the right-hand subtree. */
1720 expand_label (test_label);
1721 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1722 }
1723 }
1724
1725 else if (node->right != 0 && node->left == 0)
1726 {
1727 /* Here we have a right child but no left so we issue a conditional
1728 branch to default and process the right child.
1729
1730 Omit the conditional branch to default if the right child
1731 does not have any children and is single valued; it would
1732 cost too much space to save so little time. */
1733
1734 if (node->right->right || node->right->left
1735 || !tree_int_cst_equal (node->right->low, node->right->high))
1736 {
1737 if (!node_has_low_bound (node, index_type))
1738 {
1739 probability = conditional_probability (
1740 default_prob/2,
1741 subtree_prob + default_prob);
1742 emit_cmp_and_jump_insns (index,
1743 convert_modes
1744 (mode, imode,
1745 expand_normal (node->high),
1746 unsignedp),
1747 LT, NULL_RTX, mode, unsignedp,
1748 default_label,
1749 probability);
1750 default_prob /= 2;
1751 }
1752
1753 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1754 }
1755 else
1756 {
1757 probability = conditional_probability (
1758 node->right->subtree_prob,
1759 subtree_prob + default_prob);
1760 /* We cannot process node->right normally
1761 since we haven't ruled out the numbers less than
1762 this node's value. So handle node->right explicitly. */
1763 do_jump_if_equal (mode, index,
1764 convert_modes
1765 (mode, imode,
1766 expand_normal (node->right->low),
1767 unsignedp),
1768 jump_target_rtx (node->right->code_label),
1769 unsignedp, probability);
1770 }
1771 }
1772
1773 else if (node->right == 0 && node->left != 0)
1774 {
1775 /* Just one subtree, on the left. */
1776 if (node->left->left || node->left->right
1777 || !tree_int_cst_equal (node->left->low, node->left->high))
1778 {
1779 if (!node_has_high_bound (node, index_type))
1780 {
1781 probability = conditional_probability (
1782 default_prob/2,
1783 subtree_prob + default_prob);
1784 emit_cmp_and_jump_insns (index,
1785 convert_modes
1786 (mode, imode,
1787 expand_normal (node->high),
1788 unsignedp),
1789 GT, NULL_RTX, mode, unsignedp,
1790 default_label,
1791 probability);
1792 default_prob /= 2;
1793 }
1794
1795 emit_case_nodes (index, node->left, default_label,
1796 default_prob, index_type);
1797 }
1798 else
1799 {
1800 probability = conditional_probability (
1801 node->left->subtree_prob,
1802 subtree_prob + default_prob);
1803 /* We cannot process node->left normally
1804 since we haven't ruled out the numbers less than
1805 this node's value. So handle node->left explicitly. */
1806 do_jump_if_equal (mode, index,
1807 convert_modes
1808 (mode, imode,
1809 expand_normal (node->left->low),
1810 unsignedp),
1811 jump_target_rtx (node->left->code_label),
1812 unsignedp, probability);
1813 }
1814 }
1815 }
1816 else
1817 {
1818 /* Node is a range. These cases are very similar to those for a single
1819 value, except that we do not start by testing whether this node
1820 is the one to branch to. */
1821
1822 if (node->right != 0 && node->left != 0)
1823 {
1824 /* Node has subtrees on both sides.
1825 If the right-hand subtree is bounded,
1826 test for it first, since we can go straight there.
1827 Otherwise, we need to make a branch in the control structure,
1828 then handle the two subtrees. */
1829 tree test_label = 0;
1830
1831 if (node_is_bounded (node->right, index_type))
1832 {
1833 /* Right hand node is fully bounded so we can eliminate any
1834 testing and branch directly to the target code. */
1835 probability = conditional_probability (
1836 node->right->subtree_prob,
1837 subtree_prob + default_prob);
1838 emit_cmp_and_jump_insns (index,
1839 convert_modes
1840 (mode, imode,
1841 expand_normal (node->high),
1842 unsignedp),
1843 GT, NULL_RTX, mode, unsignedp,
1844 label_rtx (node->right->code_label),
1845 probability);
1846 }
1847 else
1848 {
1849 /* Right hand node requires testing.
1850 Branch to a label where we will handle it later. */
1851
1852 test_label = build_decl (curr_insn_location (),
1853 LABEL_DECL, NULL_TREE, void_type_node);
1854 probability = conditional_probability (
1855 node->right->subtree_prob + default_prob/2,
1856 subtree_prob + default_prob);
1857 emit_cmp_and_jump_insns (index,
1858 convert_modes
1859 (mode, imode,
1860 expand_normal (node->high),
1861 unsignedp),
1862 GT, NULL_RTX, mode, unsignedp,
1863 label_rtx (test_label),
1864 probability);
1865 default_prob /= 2;
1866 }
1867
1868 /* Value belongs to this node or to the left-hand subtree. */
1869
1870 probability = conditional_probability (
1871 prob,
1872 subtree_prob + default_prob);
1873 emit_cmp_and_jump_insns (index,
1874 convert_modes
1875 (mode, imode,
1876 expand_normal (node->low),
1877 unsignedp),
1878 GE, NULL_RTX, mode, unsignedp,
1879 label_rtx (node->code_label),
1880 probability);
1881
1882 /* Handle the left-hand subtree. */
1883 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1884
1885 /* If right node had to be handled later, do that now. */
1886
1887 if (test_label)
1888 {
1889 /* If the left-hand subtree fell through,
1890 don't let it fall into the right-hand subtree. */
1891 if (default_label)
1892 emit_jump (default_label);
1893
1894 expand_label (test_label);
1895 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1896 }
1897 }
1898
1899 else if (node->right != 0 && node->left == 0)
1900 {
1901 /* Deal with values to the left of this node,
1902 if they are possible. */
1903 if (!node_has_low_bound (node, index_type))
1904 {
1905 probability = conditional_probability (
1906 default_prob/2,
1907 subtree_prob + default_prob);
1908 emit_cmp_and_jump_insns (index,
1909 convert_modes
1910 (mode, imode,
1911 expand_normal (node->low),
1912 unsignedp),
1913 LT, NULL_RTX, mode, unsignedp,
1914 default_label,
1915 probability);
1916 default_prob /= 2;
1917 }
1918
1919 /* Value belongs to this node or to the right-hand subtree. */
1920
1921 probability = conditional_probability (
1922 prob,
1923 subtree_prob + default_prob);
1924 emit_cmp_and_jump_insns (index,
1925 convert_modes
1926 (mode, imode,
1927 expand_normal (node->high),
1928 unsignedp),
1929 LE, NULL_RTX, mode, unsignedp,
1930 label_rtx (node->code_label),
1931 probability);
1932
1933 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1934 }
1935
1936 else if (node->right == 0 && node->left != 0)
1937 {
1938 /* Deal with values to the right of this node,
1939 if they are possible. */
1940 if (!node_has_high_bound (node, index_type))
1941 {
1942 probability = conditional_probability (
1943 default_prob/2,
1944 subtree_prob + default_prob);
1945 emit_cmp_and_jump_insns (index,
1946 convert_modes
1947 (mode, imode,
1948 expand_normal (node->high),
1949 unsignedp),
1950 GT, NULL_RTX, mode, unsignedp,
1951 default_label,
1952 probability);
1953 default_prob /= 2;
1954 }
1955
1956 /* Value belongs to this node or to the left-hand subtree. */
1957
1958 probability = conditional_probability (
1959 prob,
1960 subtree_prob + default_prob);
1961 emit_cmp_and_jump_insns (index,
1962 convert_modes
1963 (mode, imode,
1964 expand_normal (node->low),
1965 unsignedp),
1966 GE, NULL_RTX, mode, unsignedp,
1967 label_rtx (node->code_label),
1968 probability);
1969
1970 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1971 }
1972
1973 else
1974 {
1975 /* Node has no children so we check low and high bounds to remove
1976 redundant tests. Only one of the bounds can exist,
1977 since otherwise this node is bounded--a case tested already. */
1978 int high_bound = node_has_high_bound (node, index_type);
1979 int low_bound = node_has_low_bound (node, index_type);
1980
1981 if (!high_bound && low_bound)
1982 {
1983 probability = conditional_probability (
1984 default_prob,
1985 subtree_prob + default_prob);
1986 emit_cmp_and_jump_insns (index,
1987 convert_modes
1988 (mode, imode,
1989 expand_normal (node->high),
1990 unsignedp),
1991 GT, NULL_RTX, mode, unsignedp,
1992 default_label,
1993 probability);
1994 }
1995
1996 else if (!low_bound && high_bound)
1997 {
1998 probability = conditional_probability (
1999 default_prob,
2000 subtree_prob + default_prob);
2001 emit_cmp_and_jump_insns (index,
2002 convert_modes
2003 (mode, imode,
2004 expand_normal (node->low),
2005 unsignedp),
2006 LT, NULL_RTX, mode, unsignedp,
2007 default_label,
2008 probability);
2009 }
2010 else if (!low_bound && !high_bound)
2011 {
2012 /* Widen LOW and HIGH to the same width as INDEX. */
2013 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2014 tree low = build1 (CONVERT_EXPR, type, node->low);
2015 tree high = build1 (CONVERT_EXPR, type, node->high);
2016 rtx low_rtx, new_index, new_bound;
2017
2018 /* Instead of doing two branches, emit one unsigned branch for
2019 (index-low) > (high-low). */
2020 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2021 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2022 NULL_RTX, unsignedp,
2023 OPTAB_WIDEN);
2024 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2025 high, low),
2026 NULL_RTX, mode, EXPAND_NORMAL);
2027
2028 probability = conditional_probability (
2029 default_prob,
2030 subtree_prob + default_prob);
2031 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2032 mode, 1, default_label, probability);
2033 }
2034
2035 emit_jump (jump_target_rtx (node->code_label));
2036 }
2037 }
2038 }