Debian Codegraph @

gcc/stmt.cc

raw
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987-2025 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.cc.
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 "target.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "cfghooks.h"
34 #include "predict.h"
35 #include "memmodel.h"
36 #include "tm_p.h"
37 #include "optabs.h"
38 #include "regs.h"
39 #include "emit-rtl.h"
40 #include "pretty-print.h"
41 #include "diagnostic-core.h"
42
43 #include "fold-const.h"
44 #include "varasm.h"
45 #include "stor-layout.h"
46 #include "dojump.h"
47 #include "explow.h"
48 #include "stmt.h"
49 #include "expr.h"
50 #include "langhooks.h"
51 #include "cfganal.h"
52 #include "tree-cfg.h"
53 #include "dumpfile.h"
54 #include "builtins.h"
55
56
57 /* Functions and data structures for expanding case statements. */
58
59 /* Case label structure, used to hold info on labels within case
60 statements. We handle "range" labels; for a single-value label
61 as in C, the high and low limits are the same.
62
63 We start with a vector of case nodes sorted in ascending order, and
64 the default label as the last element in the vector.
65
66 Switch statements are expanded in jump table form.
67
68 */
69
70 class simple_case_node
71 {
72 public:
73 simple_case_node (tree low, tree high, tree code_label):
74 m_low (low), m_high (high), m_code_label (code_label)
75 {}
76
77 /* Lowest index value for this label. */
78 tree m_low;
79 /* Highest index value for this label. */
80 tree m_high;
81 /* Label to jump to when node matches. */
82 tree m_code_label;
83 };
84
85 static bool check_unique_operand_names (tree, tree, tree);
86 static char *resolve_operand_name_1 (char *, tree, tree, tree);
87
88 /* Return the rtx-label that corresponds to a LABEL_DECL,
89 creating it if necessary. */
90
91 rtx_insn *
92 label_rtx (tree label)
93 {
94 gcc_assert (TREE_CODE (label) == LABEL_DECL);
95
96 if (!DECL_RTL_SET_P (label))
97 {
98 rtx_code_label *r = gen_label_rtx ();
99 SET_DECL_RTL (label, r);
100 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
101 LABEL_PRESERVE_P (r) = 1;
102 }
103
104 return as_a <rtx_insn *> (DECL_RTL (label));
105 }
106
107 /* As above, but also put it on the forced-reference list of the
108 function that contains it. */
109 rtx_insn *
110 force_label_rtx (tree label)
111 {
112 rtx_insn *ref = label_rtx (label);
113 tree function = decl_function_context (label);
114
115 gcc_assert (function);
116
117 vec_safe_push (forced_labels, ref);
118 return ref;
119 }
120
121 /* As label_rtx, but ensures (in check build), that returned value is
122 an existing label (i.e. rtx with code CODE_LABEL). */
123 rtx_code_label *
124 jump_target_rtx (tree label)
125 {
126 return as_a <rtx_code_label *> (label_rtx (label));
127 }
128
129 /* Add an unconditional jump to LABEL as the next sequential instruction. */
130
131 void
132 emit_jump (rtx label)
133 {
134 do_pending_stack_adjust ();
135 emit_jump_insn (targetm.gen_jump (label));
136 emit_barrier ();
137 }
138
139 /* Handle goto statements and the labels that they can go to. */
140
141 /* Specify the location in the RTL code of a label LABEL,
142 which is a LABEL_DECL tree node.
143
144 This is used for the kind of label that the user can jump to with a
145 goto statement, and for alternatives of a switch or case statement.
146 RTL labels generated for loops and conditionals don't go through here;
147 they are generated directly at the RTL level, by other functions below.
148
149 Note that this has nothing to do with defining label *names*.
150 Languages vary in how they do that and what that even means. */
151
152 void
153 expand_label (tree label)
154 {
155 rtx_code_label *label_r = jump_target_rtx (label);
156
157 do_pending_stack_adjust ();
158 emit_label (label_r);
159 if (DECL_NAME (label))
160 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
161
162 if (DECL_NONLOCAL (label))
163 {
164 expand_builtin_setjmp_receiver (NULL);
165 nonlocal_goto_handler_labels
166 = gen_rtx_INSN_LIST (VOIDmode, label_r,
167 nonlocal_goto_handler_labels);
168 }
169
170 if (FORCED_LABEL (label))
171 vec_safe_push<rtx_insn *> (forced_labels, label_r);
172
173 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
174 maybe_set_first_label_num (label_r);
175 }
176
177 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
178 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
179 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
180 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
181 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
182 constraint allows the use of a register operand. And, *IS_INOUT
183 will be true if the operand is read-write, i.e., if it is used as
184 an input as well as an output. If *CONSTRAINT_P is not in
185 canonical form, it will be made canonical. (Note that `+' will be
186 replaced with `=' as part of this process.)
187
188 Returns TRUE if all went well; FALSE if an error occurred. */
189
190 bool
191 parse_output_constraint (const char **constraint_p, int operand_num,
192 int ninputs, int noutputs, bool *allows_mem,
193 bool *allows_reg, bool *is_inout)
194 {
195 const char *constraint = *constraint_p;
196 const char *p;
197
198 /* Assume the constraint doesn't allow the use of either a register
199 or memory. */
200 *allows_mem = false;
201 *allows_reg = false;
202
203 /* Allow the `=' or `+' to not be at the beginning of the string,
204 since it wasn't explicitly documented that way, and there is a
205 large body of code that puts it last. Swap the character to
206 the front, so as not to uglify any place else. */
207 p = strchr (constraint, '=');
208 if (!p)
209 p = strchr (constraint, '+');
210
211 /* If the string doesn't contain an `=', issue an error
212 message. */
213 if (!p)
214 {
215 error ("output operand constraint lacks %<=%>");
216 return false;
217 }
218
219 /* If the constraint begins with `+', then the operand is both read
220 from and written to. */
221 *is_inout = (*p == '+');
222
223 /* Canonicalize the output constraint so that it begins with `='. */
224 if (p != constraint || *is_inout)
225 {
226 char *buf;
227 size_t c_len = strlen (constraint);
228
229 if (p != constraint)
230 warning (0, "output constraint %qc for operand %d "
231 "is not at the beginning",
232 *p, operand_num);
233
234 /* Make a copy of the constraint. */
235 buf = XALLOCAVEC (char, c_len + 1);
236 strcpy (buf, constraint);
237 /* Swap the first character and the `=' or `+'. */
238 buf[p - constraint] = buf[0];
239 /* Make sure the first character is an `='. (Until we do this,
240 it might be a `+'.) */
241 buf[0] = '=';
242 /* Replace the constraint with the canonicalized string. */
243 *constraint_p = ggc_alloc_string (buf, c_len);
244 constraint = *constraint_p;
245 }
246
247 /* Loop through the constraint string. */
248 for (p = constraint + 1; *p; )
249 {
250 switch (*p)
251 {
252 case '+':
253 case '=':
254 error ("operand constraint contains incorrectly positioned "
255 "%<+%> or %<=%>");
256 return false;
257
258 case '%':
259 if (operand_num + 1 == ninputs + noutputs)
260 {
261 error ("%<%%%> constraint used with last operand");
262 return false;
263 }
264 break;
265
266 case '?': case '!': case '*': case '&': case '#':
267 case '$': case '^':
268 case 'E': case 'F': case 'G': case 'H':
269 case 's': case 'i': case 'n':
270 case 'I': case 'J': case 'K': case 'L': case 'M':
271 case 'N': case 'O': case 'P': case ',': case '-':
272 break;
273
274 case '0': case '1': case '2': case '3': case '4':
275 case '5': case '6': case '7': case '8': case '9':
276 case '[':
277 error ("matching constraint not valid in output operand");
278 return false;
279
280 case ':':
281 error ("%<:%> constraint used for output operand");
282 return false;
283
284 case '<': case '>':
285 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
286 excepting those that expand_call created. So match memory
287 and hope. */
288 *allows_mem = true;
289 break;
290
291 case 'g': case 'X':
292 *allows_reg = true;
293 *allows_mem = true;
294 break;
295
296 default:
297 if (!ISALPHA (*p))
298 break;
299 enum constraint_num cn = lookup_constraint (p);
300 if (reg_class_for_constraint (cn) != NO_REGS
301 || insn_extra_address_constraint (cn))
302 *allows_reg = true;
303 else if (insn_extra_memory_constraint (cn))
304 *allows_mem = true;
305 else
306 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
307 break;
308 }
309
310 for (size_t len = CONSTRAINT_LEN (*p, p); len; len--, p++)
311 if (*p == '\0')
312 break;
313 }
314
315 return true;
316 }
317
318 /* Similar, but for input constraints. */
319
320 bool
321 parse_input_constraint (const char **constraint_p, int input_num,
322 int ninputs, int noutputs, int ninout,
323 const char * const * constraints,
324 bool *allows_mem, bool *allows_reg)
325 {
326 const char *constraint = *constraint_p;
327 const char *orig_constraint = constraint;
328 size_t c_len = strlen (constraint);
329 size_t j;
330 bool saw_match = false;
331 bool at_checked = false;
332
333 /* Assume the constraint doesn't allow the use of either
334 a register or memory. */
335 *allows_mem = false;
336 *allows_reg = false;
337
338 /* Make sure constraint has neither `=', `+', nor '&'. */
339
340 repeat:
341 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
342 switch (constraint[j])
343 {
344 case '+': case '=': case '&':
345 if (constraint == orig_constraint)
346 {
347 error ("input operand constraint contains %qc", constraint[j]);
348 return false;
349 }
350 break;
351
352 case '%':
353 if (constraint == orig_constraint
354 && input_num + 1 == ninputs - ninout)
355 {
356 error ("%<%%%> constraint used with last operand");
357 return false;
358 }
359 break;
360
361 case '<': case '>':
362 case '?': case '!': case '*': case '#':
363 case '$': case '^':
364 case 'E': case 'F': case 'G': case 'H':
365 case 's': case 'i': case 'n':
366 case 'I': case 'J': case 'K': case 'L': case 'M':
367 case 'N': case 'O': case 'P': case ',': case '-':
368 break;
369
370 case ':':
371 /* Verify that if : is used, it is just ":" or say ":,:" but not
372 mixed with other constraints or say ",:,," etc. */
373 if (!at_checked)
374 {
375 for (size_t k = 0; k < c_len; ++k)
376 if (constraint[k] != ((k & 1) ? ',' : ':') || (c_len & 1) == 0)
377 {
378 error ("%<:%> constraint mixed with other constraints");
379 return false;
380 }
381 at_checked = true;
382 }
383 break;
384
385 /* Whether or not a numeric constraint allows a register is
386 decided by the matching constraint, and so there is no need
387 to do anything special with them. We must handle them in
388 the default case, so that we don't unnecessarily force
389 operands to memory. */
390 case '0': case '1': case '2': case '3': case '4':
391 case '5': case '6': case '7': case '8': case '9':
392 {
393 char *end;
394 unsigned long match;
395
396 saw_match = true;
397
398 match = strtoul (constraint + j, &end, 10);
399 if (match >= (unsigned long) noutputs)
400 {
401 error ("matching constraint references invalid operand number");
402 return false;
403 }
404
405 /* Try and find the real constraint for this dup. Only do this
406 if the matching constraint is the only alternative. */
407 if (*end == '\0'
408 && (j == 0 || (j == 1 && constraint[0] == '%')))
409 {
410 constraint = constraints[match];
411 *constraint_p = constraint;
412 c_len = strlen (constraint);
413 goto repeat;
414 }
415 else
416 j = end - constraint;
417 /* Anticipate increment at end of loop. */
418 j--;
419 }
420 /* Fall through. */
421
422 case 'g': case 'X':
423 *allows_reg = true;
424 *allows_mem = true;
425 break;
426
427 default:
428 if (! ISALPHA (constraint[j]))
429 {
430 error ("invalid punctuation %qc in constraint", constraint[j]);
431 return false;
432 }
433 enum constraint_num cn = lookup_constraint (constraint + j);
434 if (reg_class_for_constraint (cn) != NO_REGS
435 || insn_extra_address_constraint (cn))
436 *allows_reg = true;
437 else if (insn_extra_memory_constraint (cn)
438 || insn_extra_special_memory_constraint (cn)
439 || insn_extra_relaxed_memory_constraint (cn))
440 *allows_mem = true;
441 else
442 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
443 break;
444 }
445
446 if (saw_match && !*allows_reg)
447 warning (0, "matching constraint does not allow a register");
448
449 return true;
450 }
451
452 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
453 can be an asm-declared register. Called via walk_tree. */
454
455 static tree
456 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
457 void *data)
458 {
459 tree decl = *declp;
460 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
461
462 if (VAR_P (decl))
463 {
464 if (DECL_HARD_REGISTER (decl)
465 && REG_P (DECL_RTL (decl))
466 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
467 {
468 rtx reg = DECL_RTL (decl);
469
470 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
471 return decl;
472 }
473 walk_subtrees = 0;
474 }
475 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
476 walk_subtrees = 0;
477 return NULL_TREE;
478 }
479
480 /* If there is an overlap between *REGS and DECL, return the first overlap
481 found. */
482 tree
483 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
484 {
485 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
486 }
487
488
489 /* A subroutine of expand_asm_operands. Check that all operand names
490 are unique. Return true if so. We rely on the fact that these names
491 are identifiers, and so have been canonicalized by get_identifier,
492 so all we need are pointer comparisons. */
493
494 static bool
495 check_unique_operand_names (tree outputs, tree inputs, tree labels)
496 {
497 tree i, j, i_name = NULL_TREE;
498
499 for (i = outputs; i ; i = TREE_CHAIN (i))
500 {
501 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
502 if (! i_name)
503 continue;
504
505 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
506 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
507 goto failure;
508 }
509
510 for (i = inputs; i ; i = TREE_CHAIN (i))
511 {
512 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
513 if (! i_name)
514 continue;
515
516 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
517 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
518 goto failure;
519 for (j = outputs; j ; j = TREE_CHAIN (j))
520 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
521 goto failure;
522 }
523
524 for (i = labels; i ; i = TREE_CHAIN (i))
525 {
526 i_name = TREE_PURPOSE (i);
527 if (! i_name)
528 continue;
529
530 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
531 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
532 goto failure;
533 for (j = inputs; j ; j = TREE_CHAIN (j))
534 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
535 goto failure;
536 }
537
538 return true;
539
540 failure:
541 error ("duplicate %<asm%> operand name %qs", TREE_STRING_POINTER (i_name));
542 return false;
543 }
544
545 /* Resolve the names of the operands in *POUTPUTS and *PINPUTS to numbers,
546 and replace the name expansions in STRING and in the constraints to
547 those numbers. This is generally done in the front end while creating
548 the ASM_EXPR generic tree that eventually becomes the GIMPLE_ASM. */
549
550 tree
551 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
552 {
553 char *buffer;
554 char *p;
555 const char *c;
556 tree t;
557
558 check_unique_operand_names (outputs, inputs, labels);
559
560 /* Substitute [<name>] in input constraint strings. There should be no
561 named operands in output constraints. */
562 for (t = inputs; t ; t = TREE_CHAIN (t))
563 {
564 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
565 if (strchr (c, '[') != NULL)
566 {
567 p = buffer = xstrdup (c);
568 while ((p = strchr (p, '[')) != NULL)
569 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
570 TREE_VALUE (TREE_PURPOSE (t))
571 = build_string (strlen (buffer), buffer);
572 free (buffer);
573 }
574 }
575
576 /* Now check for any needed substitutions in the template. */
577 c = TREE_STRING_POINTER (string);
578 while ((c = strchr (c, '%')) != NULL)
579 {
580 if (c[1] == '[')
581 break;
582 else if (ISALPHA (c[1])
583 && (c[2] == '[' || (ISALPHA (c[2]) && c[3] == '[')))
584 break;
585 else
586 {
587 c += 1 + (c[1] == '%');
588 continue;
589 }
590 }
591
592 if (c)
593 {
594 /* OK, we need to make a copy so we can perform the substitutions.
595 Assume that we will not need extra space--we get to remove '['
596 and ']', which means we cannot have a problem until we have more
597 than 999 operands. */
598 buffer = xstrdup (TREE_STRING_POINTER (string));
599 p = buffer + (c - TREE_STRING_POINTER (string));
600
601 while ((p = strchr (p, '%')) != NULL)
602 {
603 if (p[1] == '[')
604 p += 1;
605 else if (ISALPHA (p[1]) && p[2] == '[')
606 p += 2;
607 else if (ISALPHA (p[1]) && ISALPHA (p[2]) && p[3] == '[')
608 p += 3;
609 else
610 {
611 p += 1 + (p[1] == '%');
612 continue;
613 }
614
615 p = resolve_operand_name_1 (p, outputs, inputs, labels);
616 }
617
618 string = build_string (strlen (buffer), buffer);
619 free (buffer);
620 }
621
622 return string;
623 }
624
625 /* A subroutine of resolve_operand_names. P points to the '[' for a
626 potential named operand of the form [<name>]. In place, replace
627 the name and brackets with a number. Return a pointer to the
628 balance of the string after substitution. */
629
630 static char *
631 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
632 {
633 char *q;
634 int op, op_inout;
635 tree t;
636
637 /* Collect the operand name. */
638 q = strchr (++p, ']');
639 if (!q)
640 {
641 error ("missing close brace for named operand");
642 return strchr (p, '\0');
643 }
644 *q = '\0';
645
646 /* Resolve the name to a number. */
647 for (op_inout = op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
648 {
649 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
650 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
651 goto found;
652 tree constraint = TREE_VALUE (TREE_PURPOSE (t));
653 if (constraint && strchr (TREE_STRING_POINTER (constraint), '+') != NULL)
654 op_inout++;
655 }
656 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
657 {
658 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
659 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
660 goto found;
661 }
662 op += op_inout;
663 for (t = labels; t ; t = TREE_CHAIN (t), op++)
664 {
665 tree name = TREE_PURPOSE (t);
666 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
667 goto found;
668 }
669
670 error ("undefined named operand %qs", identifier_to_locale (p));
671 op = 0;
672
673 found:
674 /* Replace the name with the number. Unfortunately, not all libraries
675 get the return value of sprintf correct, so search for the end of the
676 generated string by hand. */
677 sprintf (--p, "%d", op);
678 p = strchr (p, '\0');
679
680 /* Verify the no extra buffer space assumption. */
681 gcc_assert (p <= q);
682
683 /* Shift the rest of the buffer down to fill the gap. */
684 memmove (p, q + 1, strlen (q + 1) + 1);
685
686 return p;
687 }
688
689
690 /* Generate RTL to return directly from the current function.
691 (That is, we bypass any return value.) */
692
693 void
694 expand_naked_return (void)
695 {
696 rtx_code_label *end_label;
697
698 clear_pending_stack_adjust ();
699 do_pending_stack_adjust ();
700
701 end_label = naked_return_label;
702 if (end_label == 0)
703 end_label = naked_return_label = gen_label_rtx ();
704
705 emit_jump (end_label);
706 }
707
708 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
709 is the probability of jumping to LABEL. */
710 static void
711 do_jump_if_equal (machine_mode mode, rtx op0, rtx op1, rtx_code_label *label,
712 int unsignedp, profile_probability prob)
713 {
714 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
715 NULL_RTX, NULL, label, prob);
716 }
717
718 /* Return the sum of probabilities of outgoing edges of basic block BB. */
719
720 static profile_probability
721 get_outgoing_edge_probs (basic_block bb)
722 {
723 edge e;
724 edge_iterator ei;
725 profile_probability prob_sum = profile_probability::never ();
726 if (!bb)
727 return profile_probability::never ();
728 FOR_EACH_EDGE (e, ei, bb->succs)
729 prob_sum += e->probability;
730 return prob_sum;
731 }
732
733 /* Computes the conditional probability of jumping to a target if the branch
734 instruction is executed.
735 TARGET_PROB is the estimated probability of jumping to a target relative
736 to some basic block BB.
737 BASE_PROB is the probability of reaching the branch instruction relative
738 to the same basic block BB. */
739
740 static inline profile_probability
741 conditional_probability (profile_probability target_prob,
742 profile_probability base_prob)
743 {
744 return target_prob / base_prob;
745 }
746
747 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
748 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
749 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
750 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
751
752 First, a jump insn is emitted. First we try "casesi". If that
753 fails, try "tablejump". A target *must* have one of them (or both).
754
755 Then, a table with the target labels is emitted.
756
757 The process is unaware of the CFG. The caller has to fix up
758 the CFG itself. This is done in cfgexpand.cc. */
759
760 static void
761 emit_case_dispatch_table (tree index_expr, tree index_type,
762 auto_vec<simple_case_node> &case_list,
763 rtx default_label,
764 edge default_edge, tree minval, tree maxval,
765 tree range, basic_block stmt_bb)
766 {
767 int i, ncases;
768 auto_vec<rtx> labelvec;
769 rtx_insn *fallback_label = label_rtx (case_list[0].m_code_label);
770 rtx_code_label *table_label = gen_label_rtx ();
771 bool has_gaps = false;
772 profile_probability default_prob = default_edge ? default_edge->probability
773 : profile_probability::never ();
774 profile_probability base = get_outgoing_edge_probs (stmt_bb);
775 bool try_with_tablejump = false;
776
777 profile_probability new_default_prob = conditional_probability (default_prob,
778 base);
779
780 if (! try_casesi (index_type, index_expr, minval, range,
781 table_label, default_label, fallback_label,
782 new_default_prob))
783 {
784 /* Index jumptables from zero for suitable values of minval to avoid
785 a subtraction. For the rationale see:
786 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
787 if (optimize_insn_for_speed_p ()
788 && compare_tree_int (minval, 0) > 0
789 && compare_tree_int (minval, 3) < 0)
790 {
791 minval = build_int_cst (index_type, 0);
792 range = maxval;
793 has_gaps = true;
794 }
795 try_with_tablejump = true;
796 }
797
798 /* Get table of labels to jump to, in order of case index. */
799
800 ncases = tree_to_shwi (range) + 1;
801 labelvec.safe_grow_cleared (ncases);
802
803 for (unsigned j = 0; j < case_list.length (); j++)
804 {
805 simple_case_node *n = &case_list[j];
806 /* Compute the low and high bounds relative to the minimum
807 value since that should fit in a HOST_WIDE_INT while the
808 actual values may not. */
809 HOST_WIDE_INT i_low
810 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
811 n->m_low, minval));
812 HOST_WIDE_INT i_high
813 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
814 n->m_high, minval));
815 HOST_WIDE_INT i;
816
817 for (i = i_low; i <= i_high; i ++)
818 labelvec[i]
819 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->m_code_label));
820 }
821
822 /* The dispatch table may contain gaps, including at the beginning of
823 the table if we tried to avoid the minval subtraction. We fill the
824 dispatch table slots associated with the gaps with the default case label.
825 However, in the event the default case is unreachable, we then use
826 any label from one of the case statements. */
827 rtx gap_label = (default_label) ? default_label : fallback_label;
828
829 for (i = 0; i < ncases; i++)
830 if (labelvec[i] == 0)
831 {
832 has_gaps = true;
833 labelvec[i] = gen_rtx_LABEL_REF (Pmode, gap_label);
834 }
835
836 if (has_gaps && default_label)
837 {
838 /* There is at least one entry in the jump table that jumps
839 to default label. The default label can either be reached
840 through the indirect jump or the direct conditional jump
841 before that. Split the probability of reaching the
842 default label among these two jumps. */
843 new_default_prob = conditional_probability (default_prob / 2, base);
844 default_prob /= 2;
845 base -= default_prob;
846 }
847 else
848 {
849 base -= default_prob;
850 default_prob = profile_probability::never ();
851 }
852
853 if (default_edge)
854 default_edge->probability = default_prob;
855
856 /* We have altered the probability of the default edge. So the probabilities
857 of all other edges need to be adjusted so that it sums up to
858 REG_BR_PROB_BASE. */
859 if (base > profile_probability::never ())
860 {
861 edge e;
862 edge_iterator ei;
863 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
864 e->probability /= base;
865 }
866
867 if (try_with_tablejump)
868 {
869 bool ok = try_tablejump (index_type, index_expr, minval, range,
870 table_label, default_label, new_default_prob);
871 gcc_assert (ok);
872 }
873 /* Output the table. */
874 emit_label (table_label);
875
876 if (CASE_VECTOR_PC_RELATIVE
877 || (flag_pic && targetm.asm_out.generate_pic_addr_diff_vec ()))
878 emit_jump_table_data (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
879 gen_rtx_LABEL_REF (Pmode,
880 table_label),
881 gen_rtvec_v (ncases, labelvec.address ()),
882 const0_rtx, const0_rtx));
883 else
884 emit_jump_table_data (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
885 gen_rtvec_v (ncases, labelvec.address ())));
886
887 /* Record no drop-through after the table. */
888 emit_barrier ();
889 }
890
891 /* Terminate a case Ada or switch (C) statement
892 in which ORIG_INDEX is the expression to be tested.
893 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
894 type as given in the source before any compiler conversions.
895 Generate the code to test it and jump to the right place. */
896
897 void
898 expand_case (gswitch *stmt)
899 {
900 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
901 rtx_code_label *default_label;
902 unsigned int count;
903 int i;
904 int ncases = gimple_switch_num_labels (stmt);
905 tree index_expr = gimple_switch_index (stmt);
906 tree index_type = TREE_TYPE (index_expr);
907 tree elt;
908 basic_block bb = gimple_bb (stmt);
909 gimple *def_stmt;
910
911 auto_vec<simple_case_node> case_list;
912
913 /* An ERROR_MARK occurs for various reasons including invalid data type.
914 ??? Can this still happen, with GIMPLE and all? */
915 if (index_type == error_mark_node)
916 return;
917
918 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
919 expressions being INTEGER_CST. */
920 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
921
922 /* Optimization of switch statements with only one label has already
923 occurred, so we should never see them at this point. */
924 gcc_assert (ncases > 1);
925
926 do_pending_stack_adjust ();
927
928 /* Find the default case target label. */
929 tree default_lab = CASE_LABEL (gimple_switch_default_label (stmt));
930 default_label = jump_target_rtx (default_lab);
931 basic_block default_bb = label_to_block (cfun, default_lab);
932 edge default_edge = find_edge (bb, default_bb);
933
934 /* Get upper and lower bounds of case values. */
935 elt = gimple_switch_label (stmt, 1);
936 minval = fold_convert (index_type, CASE_LOW (elt));
937 elt = gimple_switch_label (stmt, ncases - 1);
938 if (CASE_HIGH (elt))
939 maxval = fold_convert (index_type, CASE_HIGH (elt));
940 else
941 maxval = fold_convert (index_type, CASE_LOW (elt));
942
943 /* Try to narrow the index type if it's larger than a word.
944 That is mainly for -O0 where an equivalent optimization
945 done by forward propagation is not run and is aimed at
946 avoiding a call to a comparison routine of libgcc. */
947 if (TYPE_PRECISION (index_type) > BITS_PER_WORD
948 && TREE_CODE (index_expr) == SSA_NAME
949 && (def_stmt = SSA_NAME_DEF_STMT (index_expr))
950 && is_gimple_assign (def_stmt)
951 && gimple_assign_rhs_code (def_stmt) == NOP_EXPR)
952 {
953 tree inner_index_expr = gimple_assign_rhs1 (def_stmt);
954 tree inner_index_type = TREE_TYPE (inner_index_expr);
955
956 if (INTEGRAL_TYPE_P (inner_index_type)
957 && TYPE_PRECISION (inner_index_type) <= BITS_PER_WORD
958 && int_fits_type_p (minval, inner_index_type)
959 && int_fits_type_p (maxval, inner_index_type))
960 {
961 index_expr = inner_index_expr;
962 index_type = inner_index_type;
963 minval = fold_convert (index_type, minval);
964 maxval = fold_convert (index_type, maxval);
965 }
966 }
967
968 /* Compute span of values. */
969 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
970
971 /* Listify the labels queue and gather some numbers to decide
972 how to expand this switch(). */
973 count = 0;
974
975 for (i = ncases - 1; i >= 1; --i)
976 {
977 elt = gimple_switch_label (stmt, i);
978 tree low = CASE_LOW (elt);
979 gcc_assert (low);
980 tree high = CASE_HIGH (elt);
981 gcc_assert (! high || tree_int_cst_lt (low, high));
982 tree lab = CASE_LABEL (elt);
983
984 /* Count the elements.
985 A range counts double, since it requires two compares. */
986 count++;
987 if (high)
988 count++;
989
990 /* The bounds on the case range, LOW and HIGH, have to be converted
991 to case's index type TYPE. Note that the original type of the
992 case index in the source code is usually "lost" during
993 gimplification due to type promotion, but the case labels retain the
994 original type. Make sure to drop overflow flags. */
995 low = fold_convert (index_type, low);
996 if (TREE_OVERFLOW (low))
997 low = wide_int_to_tree (index_type, wi::to_wide (low));
998
999 /* The canonical from of a case label in GIMPLE is that a simple case
1000 has an empty CASE_HIGH. For the casesi and tablejump expanders,
1001 the back ends want simple cases to have high == low. */
1002 if (! high)
1003 high = low;
1004 high = fold_convert (index_type, high);
1005 if (TREE_OVERFLOW (high))
1006 high = wide_int_to_tree (index_type, wi::to_wide (high));
1007
1008 case_list.safe_push (simple_case_node (low, high, lab));
1009 }
1010
1011 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
1012 destination, such as one with a default case only.
1013 It also removes cases that are out of range for the switch
1014 type, so we should never get a zero here. */
1015 gcc_assert (count > 0);
1016
1017 rtx_insn *before_case = get_last_insn ();
1018
1019 /* If the default case is unreachable, then set default_label to NULL
1020 so that we omit the range check when generating the dispatch table.
1021 We also remove the edge to the unreachable default case. The block
1022 itself will be automatically removed later. */
1023 if (EDGE_COUNT (default_edge->dest->succs) == 0
1024 && gimple_seq_unreachable_p (bb_seq (default_edge->dest)))
1025 {
1026 default_label = NULL;
1027 remove_edge (default_edge);
1028 default_edge = NULL;
1029 }
1030
1031 emit_case_dispatch_table (index_expr, index_type,
1032 case_list, default_label, default_edge,
1033 minval, maxval, range, bb);
1034
1035 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1036
1037 free_temp_slots ();
1038 }
1039
1040 /* Expand the dispatch to a short decrement chain if there are few cases
1041 to dispatch to. Likewise if neither casesi nor tablejump is available,
1042 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
1043 tablejump. The index mode is always the mode of integer_type_node.
1044 Trap if no case matches the index.
1045
1046 DISPATCH_INDEX is the index expression to switch on. It should be a
1047 memory or register operand.
1048
1049 DISPATCH_TABLE is a set of case labels. The set should be sorted in
1050 ascending order, be contiguous, starting with value 0, and contain only
1051 single-valued case labels. */
1052
1053 void
1054 expand_sjlj_dispatch_table (rtx dispatch_index,
1055 vec<tree> dispatch_table)
1056 {
1057 tree index_type = integer_type_node;
1058 machine_mode index_mode = TYPE_MODE (index_type);
1059
1060 int ncases = dispatch_table.length ();
1061
1062 do_pending_stack_adjust ();
1063 rtx_insn *before_case = get_last_insn ();
1064
1065 /* Expand as a decrement-chain if there are 5 or fewer dispatch
1066 labels. This covers more than 98% of the cases in libjava,
1067 and seems to be a reasonable compromise between the "old way"
1068 of expanding as a decision tree or dispatch table vs. the "new
1069 way" with decrement chain or dispatch table. */
1070 if (dispatch_table.length () <= 5
1071 || (!targetm.have_casesi () && !targetm.have_tablejump ())
1072 || !flag_jump_tables)
1073 {
1074 /* Expand the dispatch as a decrement chain:
1075
1076 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
1077
1078 ==>
1079
1080 if (index == 0) do_0; else index--;
1081 if (index == 0) do_1; else index--;
1082 ...
1083 if (index == 0) do_N; else index--;
1084
1085 This is more efficient than a dispatch table on most machines.
1086 The last "index--" is redundant but the code is trivially dead
1087 and will be cleaned up by later passes. */
1088 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
1089 rtx zero = CONST0_RTX (index_mode);
1090 for (int i = 0; i < ncases; i++)
1091 {
1092 tree elt = dispatch_table[i];
1093 rtx_code_label *lab = jump_target_rtx (CASE_LABEL (elt));
1094 do_jump_if_equal (index_mode, index, zero, lab, 0,
1095 profile_probability::uninitialized ());
1096 force_expand_binop (index_mode, sub_optab,
1097 index, CONST1_RTX (index_mode),
1098 index, 0, OPTAB_DIRECT);
1099 }
1100 }
1101 else
1102 {
1103 /* Similar to expand_case, but much simpler. */
1104 auto_vec<simple_case_node> case_list;
1105 tree index_expr = make_tree (index_type, dispatch_index);
1106 tree minval = build_int_cst (index_type, 0);
1107 tree maxval = CASE_LOW (dispatch_table.last ());
1108 tree range = maxval;
1109 rtx_code_label *default_label = gen_label_rtx ();
1110
1111 for (int i = ncases - 1; i >= 0; --i)
1112 {
1113 tree elt = dispatch_table[i];
1114 tree high = CASE_HIGH (elt);
1115 if (high == NULL_TREE)
1116 high = CASE_LOW (elt);
1117 case_list.safe_push (simple_case_node (CASE_LOW (elt), high,
1118 CASE_LABEL (elt)));
1119 }
1120
1121 emit_case_dispatch_table (index_expr, index_type,
1122 case_list, default_label, NULL,
1123 minval, maxval, range,
1124 BLOCK_FOR_INSN (before_case));
1125 emit_label (default_label);
1126 }
1127
1128 /* Dispatching something not handled? Trap! */
1129 expand_builtin_trap ();
1130
1131 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1132
1133 free_temp_slots ();
1134 }
1135
1136