* stmt.c (expand_nl_goto_receiver): Remove almost-copy of
[official-gcc.git] / gcc / stmt.c
blob07e7cc74159541fbdaff55b5eab208491cec7cc8
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010, 2011, 2012 Free Software Foundation, Inc.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* This file handles the generation of rtl code from tree structure
23 above the level of expressions, using subroutines in exp*.c and emit-rtl.c.
24 The functions whose names start with `expand_' are called by the
25 expander to generate RTL instructions for various kinds of constructs. */
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
32 #include "rtl.h"
33 #include "hard-reg-set.h"
34 #include "tree.h"
35 #include "tm_p.h"
36 #include "flags.h"
37 #include "except.h"
38 #include "function.h"
39 #include "insn-config.h"
40 #include "expr.h"
41 #include "libfuncs.h"
42 #include "recog.h"
43 #include "machmode.h"
44 #include "diagnostic-core.h"
45 #include "output.h"
46 #include "ggc.h"
47 #include "langhooks.h"
48 #include "predict.h"
49 #include "optabs.h"
50 #include "target.h"
51 #include "gimple.h"
52 #include "regs.h"
53 #include "alloc-pool.h"
54 #include "pretty-print.h"
55 #include "pointer-set.h"
56 #include "params.h"
57 #include "dumpfile.h"
60 /* Functions and data structures for expanding case statements. */
62 /* Case label structure, used to hold info on labels within case
63 statements. We handle "range" labels; for a single-value label
64 as in C, the high and low limits are the same.
66 We start with a vector of case nodes sorted in ascending order, and
67 the default label as the last element in the vector. Before expanding
68 to RTL, we transform this vector into a list linked via the RIGHT
69 fields in the case_node struct. Nodes with higher case values are
70 later in the list.
72 Switch statements can be output in three forms. A branch table is
73 used if there are more than a few labels and the labels are dense
74 within the range between the smallest and largest case value. If a
75 branch table is used, no further manipulations are done with the case
76 node chain.
78 The alternative to the use of a branch table is to generate a series
79 of compare and jump insns. When that is done, we use the LEFT, RIGHT,
80 and PARENT fields to hold a binary tree. Initially the tree is
81 totally unbalanced, with everything on the right. We balance the tree
82 with nodes on the left having lower case values than the parent
83 and nodes on the right having higher values. We then output the tree
84 in order.
86 For very small, suitable switch statements, we can generate a series
87 of simple bit test and branches instead. */
89 struct case_node
91 struct case_node *left; /* Left son in binary tree */
92 struct case_node *right; /* Right son in binary tree; also node chain */
93 struct case_node *parent; /* Parent of node in binary tree */
94 tree low; /* Lowest index value for this label */
95 tree high; /* Highest index value for this label */
96 tree code_label; /* Label to jump to when node matches */
97 int prob; /* Probability of taking this case. */
98 /* Probability of reaching subtree rooted at this node */
99 int subtree_prob;
102 typedef struct case_node case_node;
103 typedef struct case_node *case_node_ptr;
105 extern basic_block label_to_block_fn (struct function *, tree);
107 static int n_occurrences (int, const char *);
108 static bool tree_conflicts_with_clobbers_p (tree, HARD_REG_SET *);
109 static bool check_operand_nalternatives (tree, tree);
110 static bool check_unique_operand_names (tree, tree, tree);
111 static char *resolve_operand_name_1 (char *, tree, tree, tree);
112 static void expand_null_return_1 (void);
113 static void expand_value_return (rtx);
114 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
115 static int node_has_low_bound (case_node_ptr, tree);
116 static int node_has_high_bound (case_node_ptr, tree);
117 static int node_is_bounded (case_node_ptr, tree);
118 static void emit_case_nodes (rtx, case_node_ptr, rtx, int, tree);
120 /* Return the rtx-label that corresponds to a LABEL_DECL,
121 creating it if necessary. */
124 label_rtx (tree label)
126 gcc_assert (TREE_CODE (label) == LABEL_DECL);
128 if (!DECL_RTL_SET_P (label))
130 rtx r = gen_label_rtx ();
131 SET_DECL_RTL (label, r);
132 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
133 LABEL_PRESERVE_P (r) = 1;
136 return DECL_RTL (label);
139 /* As above, but also put it on the forced-reference list of the
140 function that contains it. */
142 force_label_rtx (tree label)
144 rtx ref = label_rtx (label);
145 tree function = decl_function_context (label);
147 gcc_assert (function);
149 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, ref, forced_labels);
150 return ref;
153 /* Add an unconditional jump to LABEL as the next sequential instruction. */
155 void
156 emit_jump (rtx label)
158 do_pending_stack_adjust ();
159 emit_jump_insn (gen_jump (label));
160 emit_barrier ();
163 /* Emit code to jump to the address
164 specified by the pointer expression EXP. */
166 void
167 expand_computed_goto (tree exp)
169 rtx x = expand_normal (exp);
171 x = convert_memory_address (Pmode, x);
173 do_pending_stack_adjust ();
174 emit_indirect_jump (x);
177 /* Handle goto statements and the labels that they can go to. */
179 /* Specify the location in the RTL code of a label LABEL,
180 which is a LABEL_DECL tree node.
182 This is used for the kind of label that the user can jump to with a
183 goto statement, and for alternatives of a switch or case statement.
184 RTL labels generated for loops and conditionals don't go through here;
185 they are generated directly at the RTL level, by other functions below.
187 Note that this has nothing to do with defining label *names*.
188 Languages vary in how they do that and what that even means. */
190 void
191 expand_label (tree label)
193 rtx label_r = label_rtx (label);
195 do_pending_stack_adjust ();
196 emit_label (label_r);
197 if (DECL_NAME (label))
198 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
200 if (DECL_NONLOCAL (label))
202 expand_builtin_setjmp_receiver (NULL);
203 nonlocal_goto_handler_labels
204 = gen_rtx_EXPR_LIST (VOIDmode, label_r,
205 nonlocal_goto_handler_labels);
208 if (FORCED_LABEL (label))
209 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, label_r, forced_labels);
211 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
212 maybe_set_first_label_num (label_r);
215 /* Generate RTL code for a `goto' statement with target label LABEL.
216 LABEL should be a LABEL_DECL tree node that was or will later be
217 defined with `expand_label'. */
219 void
220 expand_goto (tree label)
222 #ifdef ENABLE_CHECKING
223 /* Check for a nonlocal goto to a containing function. Should have
224 gotten translated to __builtin_nonlocal_goto. */
225 tree context = decl_function_context (label);
226 gcc_assert (!context || context == current_function_decl);
227 #endif
229 emit_jump (label_rtx (label));
232 /* Return the number of times character C occurs in string S. */
233 static int
234 n_occurrences (int c, const char *s)
236 int n = 0;
237 while (*s)
238 n += (*s++ == c);
239 return n;
242 /* Generate RTL for an asm statement (explicit assembler code).
243 STRING is a STRING_CST node containing the assembler code text,
244 or an ADDR_EXPR containing a STRING_CST. VOL nonzero means the
245 insn is volatile; don't optimize it. */
247 static void
248 expand_asm_loc (tree string, int vol, location_t locus)
250 rtx body;
252 if (TREE_CODE (string) == ADDR_EXPR)
253 string = TREE_OPERAND (string, 0);
255 body = gen_rtx_ASM_INPUT_loc (VOIDmode,
256 ggc_strdup (TREE_STRING_POINTER (string)),
257 locus);
259 MEM_VOLATILE_P (body) = vol;
261 emit_insn (body);
264 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
265 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
266 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
267 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
268 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
269 constraint allows the use of a register operand. And, *IS_INOUT
270 will be true if the operand is read-write, i.e., if it is used as
271 an input as well as an output. If *CONSTRAINT_P is not in
272 canonical form, it will be made canonical. (Note that `+' will be
273 replaced with `=' as part of this process.)
275 Returns TRUE if all went well; FALSE if an error occurred. */
277 bool
278 parse_output_constraint (const char **constraint_p, int operand_num,
279 int ninputs, int noutputs, bool *allows_mem,
280 bool *allows_reg, bool *is_inout)
282 const char *constraint = *constraint_p;
283 const char *p;
285 /* Assume the constraint doesn't allow the use of either a register
286 or memory. */
287 *allows_mem = false;
288 *allows_reg = false;
290 /* Allow the `=' or `+' to not be at the beginning of the string,
291 since it wasn't explicitly documented that way, and there is a
292 large body of code that puts it last. Swap the character to
293 the front, so as not to uglify any place else. */
294 p = strchr (constraint, '=');
295 if (!p)
296 p = strchr (constraint, '+');
298 /* If the string doesn't contain an `=', issue an error
299 message. */
300 if (!p)
302 error ("output operand constraint lacks %<=%>");
303 return false;
306 /* If the constraint begins with `+', then the operand is both read
307 from and written to. */
308 *is_inout = (*p == '+');
310 /* Canonicalize the output constraint so that it begins with `='. */
311 if (p != constraint || *is_inout)
313 char *buf;
314 size_t c_len = strlen (constraint);
316 if (p != constraint)
317 warning (0, "output constraint %qc for operand %d "
318 "is not at the beginning",
319 *p, operand_num);
321 /* Make a copy of the constraint. */
322 buf = XALLOCAVEC (char, c_len + 1);
323 strcpy (buf, constraint);
324 /* Swap the first character and the `=' or `+'. */
325 buf[p - constraint] = buf[0];
326 /* Make sure the first character is an `='. (Until we do this,
327 it might be a `+'.) */
328 buf[0] = '=';
329 /* Replace the constraint with the canonicalized string. */
330 *constraint_p = ggc_alloc_string (buf, c_len);
331 constraint = *constraint_p;
334 /* Loop through the constraint string. */
335 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
336 switch (*p)
338 case '+':
339 case '=':
340 error ("operand constraint contains incorrectly positioned "
341 "%<+%> or %<=%>");
342 return false;
344 case '%':
345 if (operand_num + 1 == ninputs + noutputs)
347 error ("%<%%%> constraint used with last operand");
348 return false;
350 break;
352 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
353 *allows_mem = true;
354 break;
356 case '?': case '!': case '*': case '&': case '#':
357 case 'E': case 'F': case 'G': case 'H':
358 case 's': case 'i': case 'n':
359 case 'I': case 'J': case 'K': case 'L': case 'M':
360 case 'N': case 'O': case 'P': case ',':
361 break;
363 case '0': case '1': case '2': case '3': case '4':
364 case '5': case '6': case '7': case '8': case '9':
365 case '[':
366 error ("matching constraint not valid in output operand");
367 return false;
369 case '<': case '>':
370 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
371 excepting those that expand_call created. So match memory
372 and hope. */
373 *allows_mem = true;
374 break;
376 case 'g': case 'X':
377 *allows_reg = true;
378 *allows_mem = true;
379 break;
381 case 'p': case 'r':
382 *allows_reg = true;
383 break;
385 default:
386 if (!ISALPHA (*p))
387 break;
388 if (REG_CLASS_FROM_CONSTRAINT (*p, p) != NO_REGS)
389 *allows_reg = true;
390 #ifdef EXTRA_CONSTRAINT_STR
391 else if (EXTRA_ADDRESS_CONSTRAINT (*p, p))
392 *allows_reg = true;
393 else if (EXTRA_MEMORY_CONSTRAINT (*p, p))
394 *allows_mem = true;
395 else
397 /* Otherwise we can't assume anything about the nature of
398 the constraint except that it isn't purely registers.
399 Treat it like "g" and hope for the best. */
400 *allows_reg = true;
401 *allows_mem = true;
403 #endif
404 break;
407 return true;
410 /* Similar, but for input constraints. */
412 bool
413 parse_input_constraint (const char **constraint_p, int input_num,
414 int ninputs, int noutputs, int ninout,
415 const char * const * constraints,
416 bool *allows_mem, bool *allows_reg)
418 const char *constraint = *constraint_p;
419 const char *orig_constraint = constraint;
420 size_t c_len = strlen (constraint);
421 size_t j;
422 bool saw_match = false;
424 /* Assume the constraint doesn't allow the use of either
425 a register or memory. */
426 *allows_mem = false;
427 *allows_reg = false;
429 /* Make sure constraint has neither `=', `+', nor '&'. */
431 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
432 switch (constraint[j])
434 case '+': case '=': case '&':
435 if (constraint == orig_constraint)
437 error ("input operand constraint contains %qc", constraint[j]);
438 return false;
440 break;
442 case '%':
443 if (constraint == orig_constraint
444 && input_num + 1 == ninputs - ninout)
446 error ("%<%%%> constraint used with last operand");
447 return false;
449 break;
451 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
452 *allows_mem = true;
453 break;
455 case '<': case '>':
456 case '?': case '!': case '*': case '#':
457 case 'E': case 'F': case 'G': case 'H':
458 case 's': case 'i': case 'n':
459 case 'I': case 'J': case 'K': case 'L': case 'M':
460 case 'N': case 'O': case 'P': case ',':
461 break;
463 /* Whether or not a numeric constraint allows a register is
464 decided by the matching constraint, and so there is no need
465 to do anything special with them. We must handle them in
466 the default case, so that we don't unnecessarily force
467 operands to memory. */
468 case '0': case '1': case '2': case '3': case '4':
469 case '5': case '6': case '7': case '8': case '9':
471 char *end;
472 unsigned long match;
474 saw_match = true;
476 match = strtoul (constraint + j, &end, 10);
477 if (match >= (unsigned long) noutputs)
479 error ("matching constraint references invalid operand number");
480 return false;
483 /* Try and find the real constraint for this dup. Only do this
484 if the matching constraint is the only alternative. */
485 if (*end == '\0'
486 && (j == 0 || (j == 1 && constraint[0] == '%')))
488 constraint = constraints[match];
489 *constraint_p = constraint;
490 c_len = strlen (constraint);
491 j = 0;
492 /* ??? At the end of the loop, we will skip the first part of
493 the matched constraint. This assumes not only that the
494 other constraint is an output constraint, but also that
495 the '=' or '+' come first. */
496 break;
498 else
499 j = end - constraint;
500 /* Anticipate increment at end of loop. */
501 j--;
503 /* Fall through. */
505 case 'p': case 'r':
506 *allows_reg = true;
507 break;
509 case 'g': case 'X':
510 *allows_reg = true;
511 *allows_mem = true;
512 break;
514 default:
515 if (! ISALPHA (constraint[j]))
517 error ("invalid punctuation %qc in constraint", constraint[j]);
518 return false;
520 if (REG_CLASS_FROM_CONSTRAINT (constraint[j], constraint + j)
521 != NO_REGS)
522 *allows_reg = true;
523 #ifdef EXTRA_CONSTRAINT_STR
524 else if (EXTRA_ADDRESS_CONSTRAINT (constraint[j], constraint + j))
525 *allows_reg = true;
526 else if (EXTRA_MEMORY_CONSTRAINT (constraint[j], constraint + j))
527 *allows_mem = true;
528 else
530 /* Otherwise we can't assume anything about the nature of
531 the constraint except that it isn't purely registers.
532 Treat it like "g" and hope for the best. */
533 *allows_reg = true;
534 *allows_mem = true;
536 #endif
537 break;
540 if (saw_match && !*allows_reg)
541 warning (0, "matching constraint does not allow a register");
543 return true;
546 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
547 can be an asm-declared register. Called via walk_tree. */
549 static tree
550 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
551 void *data)
553 tree decl = *declp;
554 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
556 if (TREE_CODE (decl) == VAR_DECL)
558 if (DECL_HARD_REGISTER (decl)
559 && REG_P (DECL_RTL (decl))
560 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
562 rtx reg = DECL_RTL (decl);
564 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
565 return decl;
567 walk_subtrees = 0;
569 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
570 walk_subtrees = 0;
571 return NULL_TREE;
574 /* If there is an overlap between *REGS and DECL, return the first overlap
575 found. */
576 tree
577 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
579 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
582 /* Check for overlap between registers marked in CLOBBERED_REGS and
583 anything inappropriate in T. Emit error and return the register
584 variable definition for error, NULL_TREE for ok. */
586 static bool
587 tree_conflicts_with_clobbers_p (tree t, HARD_REG_SET *clobbered_regs)
589 /* Conflicts between asm-declared register variables and the clobber
590 list are not allowed. */
591 tree overlap = tree_overlaps_hard_reg_set (t, clobbered_regs);
593 if (overlap)
595 error ("asm-specifier for variable %qE conflicts with asm clobber list",
596 DECL_NAME (overlap));
598 /* Reset registerness to stop multiple errors emitted for a single
599 variable. */
600 DECL_REGISTER (overlap) = 0;
601 return true;
604 return false;
607 /* Generate RTL for an asm statement with arguments.
608 STRING is the instruction template.
609 OUTPUTS is a list of output arguments (lvalues); INPUTS a list of inputs.
610 Each output or input has an expression in the TREE_VALUE and
611 a tree list in TREE_PURPOSE which in turn contains a constraint
612 name in TREE_VALUE (or NULL_TREE) and a constraint string
613 in TREE_PURPOSE.
614 CLOBBERS is a list of STRING_CST nodes each naming a hard register
615 that is clobbered by this insn.
617 Not all kinds of lvalue that may appear in OUTPUTS can be stored directly.
618 Some elements of OUTPUTS may be replaced with trees representing temporary
619 values. The caller should copy those temporary values to the originally
620 specified lvalues.
622 VOL nonzero means the insn is volatile; don't optimize it. */
624 static void
625 expand_asm_operands (tree string, tree outputs, tree inputs,
626 tree clobbers, tree labels, int vol, location_t locus)
628 rtvec argvec, constraintvec, labelvec;
629 rtx body;
630 int ninputs = list_length (inputs);
631 int noutputs = list_length (outputs);
632 int nlabels = list_length (labels);
633 int ninout;
634 int nclobbers;
635 HARD_REG_SET clobbered_regs;
636 int clobber_conflict_found = 0;
637 tree tail;
638 tree t;
639 int i;
640 /* Vector of RTX's of evaluated output operands. */
641 rtx *output_rtx = XALLOCAVEC (rtx, noutputs);
642 int *inout_opnum = XALLOCAVEC (int, noutputs);
643 rtx *real_output_rtx = XALLOCAVEC (rtx, noutputs);
644 enum machine_mode *inout_mode = XALLOCAVEC (enum machine_mode, noutputs);
645 const char **constraints = XALLOCAVEC (const char *, noutputs + ninputs);
646 int old_generating_concat_p = generating_concat_p;
648 /* An ASM with no outputs needs to be treated as volatile, for now. */
649 if (noutputs == 0)
650 vol = 1;
652 if (! check_operand_nalternatives (outputs, inputs))
653 return;
655 string = resolve_asm_operand_names (string, outputs, inputs, labels);
657 /* Collect constraints. */
658 i = 0;
659 for (t = outputs; t ; t = TREE_CHAIN (t), i++)
660 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
661 for (t = inputs; t ; t = TREE_CHAIN (t), i++)
662 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
664 /* Sometimes we wish to automatically clobber registers across an asm.
665 Case in point is when the i386 backend moved from cc0 to a hard reg --
666 maintaining source-level compatibility means automatically clobbering
667 the flags register. */
668 clobbers = targetm.md_asm_clobbers (outputs, inputs, clobbers);
670 /* Count the number of meaningful clobbered registers, ignoring what
671 we would ignore later. */
672 nclobbers = 0;
673 CLEAR_HARD_REG_SET (clobbered_regs);
674 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
676 const char *regname;
677 int nregs;
679 if (TREE_VALUE (tail) == error_mark_node)
680 return;
681 regname = TREE_STRING_POINTER (TREE_VALUE (tail));
683 i = decode_reg_name_and_count (regname, &nregs);
684 if (i == -4)
685 ++nclobbers;
686 else if (i == -2)
687 error ("unknown register name %qs in %<asm%>", regname);
689 /* Mark clobbered registers. */
690 if (i >= 0)
692 int reg;
694 for (reg = i; reg < i + nregs; reg++)
696 ++nclobbers;
698 /* Clobbering the PIC register is an error. */
699 if (reg == (int) PIC_OFFSET_TABLE_REGNUM)
701 error ("PIC register clobbered by %qs in %<asm%>", regname);
702 return;
705 SET_HARD_REG_BIT (clobbered_regs, reg);
710 /* First pass over inputs and outputs checks validity and sets
711 mark_addressable if needed. */
713 ninout = 0;
714 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
716 tree val = TREE_VALUE (tail);
717 tree type = TREE_TYPE (val);
718 const char *constraint;
719 bool is_inout;
720 bool allows_reg;
721 bool allows_mem;
723 /* If there's an erroneous arg, emit no insn. */
724 if (type == error_mark_node)
725 return;
727 /* Try to parse the output constraint. If that fails, there's
728 no point in going further. */
729 constraint = constraints[i];
730 if (!parse_output_constraint (&constraint, i, ninputs, noutputs,
731 &allows_mem, &allows_reg, &is_inout))
732 return;
734 if (! allows_reg
735 && (allows_mem
736 || is_inout
737 || (DECL_P (val)
738 && REG_P (DECL_RTL (val))
739 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type))))
740 mark_addressable (val);
742 if (is_inout)
743 ninout++;
746 ninputs += ninout;
747 if (ninputs + noutputs > MAX_RECOG_OPERANDS)
749 error ("more than %d operands in %<asm%>", MAX_RECOG_OPERANDS);
750 return;
753 for (i = 0, tail = inputs; tail; i++, tail = TREE_CHAIN (tail))
755 bool allows_reg, allows_mem;
756 const char *constraint;
758 /* If there's an erroneous arg, emit no insn, because the ASM_INPUT
759 would get VOIDmode and that could cause a crash in reload. */
760 if (TREE_TYPE (TREE_VALUE (tail)) == error_mark_node)
761 return;
763 constraint = constraints[i + noutputs];
764 if (! parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
765 constraints, &allows_mem, &allows_reg))
766 return;
768 if (! allows_reg && allows_mem)
769 mark_addressable (TREE_VALUE (tail));
772 /* Second pass evaluates arguments. */
774 /* Make sure stack is consistent for asm goto. */
775 if (nlabels > 0)
776 do_pending_stack_adjust ();
778 ninout = 0;
779 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
781 tree val = TREE_VALUE (tail);
782 tree type = TREE_TYPE (val);
783 bool is_inout;
784 bool allows_reg;
785 bool allows_mem;
786 rtx op;
787 bool ok;
789 ok = parse_output_constraint (&constraints[i], i, ninputs,
790 noutputs, &allows_mem, &allows_reg,
791 &is_inout);
792 gcc_assert (ok);
794 /* If an output operand is not a decl or indirect ref and our constraint
795 allows a register, make a temporary to act as an intermediate.
796 Make the asm insn write into that, then our caller will copy it to
797 the real output operand. Likewise for promoted variables. */
799 generating_concat_p = 0;
801 real_output_rtx[i] = NULL_RTX;
802 if ((TREE_CODE (val) == INDIRECT_REF
803 && allows_mem)
804 || (DECL_P (val)
805 && (allows_mem || REG_P (DECL_RTL (val)))
806 && ! (REG_P (DECL_RTL (val))
807 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type)))
808 || ! allows_reg
809 || is_inout)
811 op = expand_expr (val, NULL_RTX, VOIDmode, EXPAND_WRITE);
812 if (MEM_P (op))
813 op = validize_mem (op);
815 if (! allows_reg && !MEM_P (op))
816 error ("output number %d not directly addressable", i);
817 if ((! allows_mem && MEM_P (op))
818 || GET_CODE (op) == CONCAT)
820 real_output_rtx[i] = op;
821 op = gen_reg_rtx (GET_MODE (op));
822 if (is_inout)
823 emit_move_insn (op, real_output_rtx[i]);
826 else
828 op = assign_temp (type, 0, 1);
829 op = validize_mem (op);
830 if (!MEM_P (op) && TREE_CODE (TREE_VALUE (tail)) == SSA_NAME)
831 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (TREE_VALUE (tail)), op);
832 TREE_VALUE (tail) = make_tree (type, op);
834 output_rtx[i] = op;
836 generating_concat_p = old_generating_concat_p;
838 if (is_inout)
840 inout_mode[ninout] = TYPE_MODE (type);
841 inout_opnum[ninout++] = i;
844 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
845 clobber_conflict_found = 1;
848 /* Make vectors for the expression-rtx, constraint strings,
849 and named operands. */
851 argvec = rtvec_alloc (ninputs);
852 constraintvec = rtvec_alloc (ninputs);
853 labelvec = rtvec_alloc (nlabels);
855 body = gen_rtx_ASM_OPERANDS ((noutputs == 0 ? VOIDmode
856 : GET_MODE (output_rtx[0])),
857 ggc_strdup (TREE_STRING_POINTER (string)),
858 empty_string, 0, argvec, constraintvec,
859 labelvec, locus);
861 MEM_VOLATILE_P (body) = vol;
863 /* Eval the inputs and put them into ARGVEC.
864 Put their constraints into ASM_INPUTs and store in CONSTRAINTS. */
866 for (i = 0, tail = inputs; tail; tail = TREE_CHAIN (tail), ++i)
868 bool allows_reg, allows_mem;
869 const char *constraint;
870 tree val, type;
871 rtx op;
872 bool ok;
874 constraint = constraints[i + noutputs];
875 ok = parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
876 constraints, &allows_mem, &allows_reg);
877 gcc_assert (ok);
879 generating_concat_p = 0;
881 val = TREE_VALUE (tail);
882 type = TREE_TYPE (val);
883 /* EXPAND_INITIALIZER will not generate code for valid initializer
884 constants, but will still generate code for other types of operand.
885 This is the behavior we want for constant constraints. */
886 op = expand_expr (val, NULL_RTX, VOIDmode,
887 allows_reg ? EXPAND_NORMAL
888 : allows_mem ? EXPAND_MEMORY
889 : EXPAND_INITIALIZER);
891 /* Never pass a CONCAT to an ASM. */
892 if (GET_CODE (op) == CONCAT)
893 op = force_reg (GET_MODE (op), op);
894 else if (MEM_P (op))
895 op = validize_mem (op);
897 if (asm_operand_ok (op, constraint, NULL) <= 0)
899 if (allows_reg && TYPE_MODE (type) != BLKmode)
900 op = force_reg (TYPE_MODE (type), op);
901 else if (!allows_mem)
902 warning (0, "asm operand %d probably doesn%'t match constraints",
903 i + noutputs);
904 else if (MEM_P (op))
906 /* We won't recognize either volatile memory or memory
907 with a queued address as available a memory_operand
908 at this point. Ignore it: clearly this *is* a memory. */
910 else
911 gcc_unreachable ();
914 generating_concat_p = old_generating_concat_p;
915 ASM_OPERANDS_INPUT (body, i) = op;
917 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, i)
918 = gen_rtx_ASM_INPUT (TYPE_MODE (type),
919 ggc_strdup (constraints[i + noutputs]));
921 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
922 clobber_conflict_found = 1;
925 /* Protect all the operands from the queue now that they have all been
926 evaluated. */
928 generating_concat_p = 0;
930 /* For in-out operands, copy output rtx to input rtx. */
931 for (i = 0; i < ninout; i++)
933 int j = inout_opnum[i];
934 char buffer[16];
936 ASM_OPERANDS_INPUT (body, ninputs - ninout + i)
937 = output_rtx[j];
939 sprintf (buffer, "%d", j);
940 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, ninputs - ninout + i)
941 = gen_rtx_ASM_INPUT (inout_mode[i], ggc_strdup (buffer));
944 /* Copy labels to the vector. */
945 for (i = 0, tail = labels; i < nlabels; ++i, tail = TREE_CHAIN (tail))
946 ASM_OPERANDS_LABEL (body, i)
947 = gen_rtx_LABEL_REF (Pmode, label_rtx (TREE_VALUE (tail)));
949 generating_concat_p = old_generating_concat_p;
951 /* Now, for each output, construct an rtx
952 (set OUTPUT (asm_operands INSN OUTPUTCONSTRAINT OUTPUTNUMBER
953 ARGVEC CONSTRAINTS OPNAMES))
954 If there is more than one, put them inside a PARALLEL. */
956 if (nlabels > 0 && nclobbers == 0)
958 gcc_assert (noutputs == 0);
959 emit_jump_insn (body);
961 else if (noutputs == 0 && nclobbers == 0)
963 /* No output operands: put in a raw ASM_OPERANDS rtx. */
964 emit_insn (body);
966 else if (noutputs == 1 && nclobbers == 0)
968 ASM_OPERANDS_OUTPUT_CONSTRAINT (body) = ggc_strdup (constraints[0]);
969 emit_insn (gen_rtx_SET (VOIDmode, output_rtx[0], body));
971 else
973 rtx obody = body;
974 int num = noutputs;
976 if (num == 0)
977 num = 1;
979 body = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num + nclobbers));
981 /* For each output operand, store a SET. */
982 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
984 XVECEXP (body, 0, i)
985 = gen_rtx_SET (VOIDmode,
986 output_rtx[i],
987 gen_rtx_ASM_OPERANDS
988 (GET_MODE (output_rtx[i]),
989 ggc_strdup (TREE_STRING_POINTER (string)),
990 ggc_strdup (constraints[i]),
991 i, argvec, constraintvec, labelvec, locus));
993 MEM_VOLATILE_P (SET_SRC (XVECEXP (body, 0, i))) = vol;
996 /* If there are no outputs (but there are some clobbers)
997 store the bare ASM_OPERANDS into the PARALLEL. */
999 if (i == 0)
1000 XVECEXP (body, 0, i++) = obody;
1002 /* Store (clobber REG) for each clobbered register specified. */
1004 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
1006 const char *regname = TREE_STRING_POINTER (TREE_VALUE (tail));
1007 int reg, nregs;
1008 int j = decode_reg_name_and_count (regname, &nregs);
1009 rtx clobbered_reg;
1011 if (j < 0)
1013 if (j == -3) /* `cc', which is not a register */
1014 continue;
1016 if (j == -4) /* `memory', don't cache memory across asm */
1018 XVECEXP (body, 0, i++)
1019 = gen_rtx_CLOBBER (VOIDmode,
1020 gen_rtx_MEM
1021 (BLKmode,
1022 gen_rtx_SCRATCH (VOIDmode)));
1023 continue;
1026 /* Ignore unknown register, error already signaled. */
1027 continue;
1030 for (reg = j; reg < j + nregs; reg++)
1032 /* Use QImode since that's guaranteed to clobber just
1033 * one reg. */
1034 clobbered_reg = gen_rtx_REG (QImode, reg);
1036 /* Do sanity check for overlap between clobbers and
1037 respectively input and outputs that hasn't been
1038 handled. Such overlap should have been detected and
1039 reported above. */
1040 if (!clobber_conflict_found)
1042 int opno;
1044 /* We test the old body (obody) contents to avoid
1045 tripping over the under-construction body. */
1046 for (opno = 0; opno < noutputs; opno++)
1047 if (reg_overlap_mentioned_p (clobbered_reg,
1048 output_rtx[opno]))
1049 internal_error
1050 ("asm clobber conflict with output operand");
1052 for (opno = 0; opno < ninputs - ninout; opno++)
1053 if (reg_overlap_mentioned_p (clobbered_reg,
1054 ASM_OPERANDS_INPUT (obody,
1055 opno)))
1056 internal_error
1057 ("asm clobber conflict with input operand");
1060 XVECEXP (body, 0, i++)
1061 = gen_rtx_CLOBBER (VOIDmode, clobbered_reg);
1065 if (nlabels > 0)
1066 emit_jump_insn (body);
1067 else
1068 emit_insn (body);
1071 /* For any outputs that needed reloading into registers, spill them
1072 back to where they belong. */
1073 for (i = 0; i < noutputs; ++i)
1074 if (real_output_rtx[i])
1075 emit_move_insn (real_output_rtx[i], output_rtx[i]);
1077 crtl->has_asm_statement = 1;
1078 free_temp_slots ();
1081 void
1082 expand_asm_stmt (gimple stmt)
1084 int noutputs;
1085 tree outputs, tail, t;
1086 tree *o;
1087 size_t i, n;
1088 const char *s;
1089 tree str, out, in, cl, labels;
1090 location_t locus = gimple_location (stmt);
1092 /* Meh... convert the gimple asm operands into real tree lists.
1093 Eventually we should make all routines work on the vectors instead
1094 of relying on TREE_CHAIN. */
1095 out = NULL_TREE;
1096 n = gimple_asm_noutputs (stmt);
1097 if (n > 0)
1099 t = out = gimple_asm_output_op (stmt, 0);
1100 for (i = 1; i < n; i++)
1101 t = TREE_CHAIN (t) = gimple_asm_output_op (stmt, i);
1104 in = NULL_TREE;
1105 n = gimple_asm_ninputs (stmt);
1106 if (n > 0)
1108 t = in = gimple_asm_input_op (stmt, 0);
1109 for (i = 1; i < n; i++)
1110 t = TREE_CHAIN (t) = gimple_asm_input_op (stmt, i);
1113 cl = NULL_TREE;
1114 n = gimple_asm_nclobbers (stmt);
1115 if (n > 0)
1117 t = cl = gimple_asm_clobber_op (stmt, 0);
1118 for (i = 1; i < n; i++)
1119 t = TREE_CHAIN (t) = gimple_asm_clobber_op (stmt, i);
1122 labels = NULL_TREE;
1123 n = gimple_asm_nlabels (stmt);
1124 if (n > 0)
1126 t = labels = gimple_asm_label_op (stmt, 0);
1127 for (i = 1; i < n; i++)
1128 t = TREE_CHAIN (t) = gimple_asm_label_op (stmt, i);
1131 s = gimple_asm_string (stmt);
1132 str = build_string (strlen (s), s);
1134 if (gimple_asm_input_p (stmt))
1136 expand_asm_loc (str, gimple_asm_volatile_p (stmt), locus);
1137 return;
1140 outputs = out;
1141 noutputs = gimple_asm_noutputs (stmt);
1142 /* o[I] is the place that output number I should be written. */
1143 o = (tree *) alloca (noutputs * sizeof (tree));
1145 /* Record the contents of OUTPUTS before it is modified. */
1146 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1147 o[i] = TREE_VALUE (tail);
1149 /* Generate the ASM_OPERANDS insn; store into the TREE_VALUEs of
1150 OUTPUTS some trees for where the values were actually stored. */
1151 expand_asm_operands (str, outputs, in, cl, labels,
1152 gimple_asm_volatile_p (stmt), locus);
1154 /* Copy all the intermediate outputs into the specified outputs. */
1155 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1157 if (o[i] != TREE_VALUE (tail))
1159 expand_assignment (o[i], TREE_VALUE (tail), false);
1160 free_temp_slots ();
1162 /* Restore the original value so that it's correct the next
1163 time we expand this function. */
1164 TREE_VALUE (tail) = o[i];
1169 /* A subroutine of expand_asm_operands. Check that all operands have
1170 the same number of alternatives. Return true if so. */
1172 static bool
1173 check_operand_nalternatives (tree outputs, tree inputs)
1175 if (outputs || inputs)
1177 tree tmp = TREE_PURPOSE (outputs ? outputs : inputs);
1178 int nalternatives
1179 = n_occurrences (',', TREE_STRING_POINTER (TREE_VALUE (tmp)));
1180 tree next = inputs;
1182 if (nalternatives + 1 > MAX_RECOG_ALTERNATIVES)
1184 error ("too many alternatives in %<asm%>");
1185 return false;
1188 tmp = outputs;
1189 while (tmp)
1191 const char *constraint
1192 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tmp)));
1194 if (n_occurrences (',', constraint) != nalternatives)
1196 error ("operand constraints for %<asm%> differ "
1197 "in number of alternatives");
1198 return false;
1201 if (TREE_CHAIN (tmp))
1202 tmp = TREE_CHAIN (tmp);
1203 else
1204 tmp = next, next = 0;
1208 return true;
1211 /* A subroutine of expand_asm_operands. Check that all operand names
1212 are unique. Return true if so. We rely on the fact that these names
1213 are identifiers, and so have been canonicalized by get_identifier,
1214 so all we need are pointer comparisons. */
1216 static bool
1217 check_unique_operand_names (tree outputs, tree inputs, tree labels)
1219 tree i, j, i_name = NULL_TREE;
1221 for (i = outputs; i ; i = TREE_CHAIN (i))
1223 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1224 if (! i_name)
1225 continue;
1227 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1228 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1229 goto failure;
1232 for (i = inputs; i ; i = TREE_CHAIN (i))
1234 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1235 if (! i_name)
1236 continue;
1238 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1239 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1240 goto failure;
1241 for (j = outputs; j ; j = TREE_CHAIN (j))
1242 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1243 goto failure;
1246 for (i = labels; i ; i = TREE_CHAIN (i))
1248 i_name = TREE_PURPOSE (i);
1249 if (! i_name)
1250 continue;
1252 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1253 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
1254 goto failure;
1255 for (j = inputs; j ; j = TREE_CHAIN (j))
1256 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1257 goto failure;
1260 return true;
1262 failure:
1263 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
1264 return false;
1267 /* A subroutine of expand_asm_operands. Resolve the names of the operands
1268 in *POUTPUTS and *PINPUTS to numbers, and replace the name expansions in
1269 STRING and in the constraints to those numbers. */
1271 tree
1272 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
1274 char *buffer;
1275 char *p;
1276 const char *c;
1277 tree t;
1279 check_unique_operand_names (outputs, inputs, labels);
1281 /* Substitute [<name>] in input constraint strings. There should be no
1282 named operands in output constraints. */
1283 for (t = inputs; t ; t = TREE_CHAIN (t))
1285 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1286 if (strchr (c, '[') != NULL)
1288 p = buffer = xstrdup (c);
1289 while ((p = strchr (p, '[')) != NULL)
1290 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
1291 TREE_VALUE (TREE_PURPOSE (t))
1292 = build_string (strlen (buffer), buffer);
1293 free (buffer);
1297 /* Now check for any needed substitutions in the template. */
1298 c = TREE_STRING_POINTER (string);
1299 while ((c = strchr (c, '%')) != NULL)
1301 if (c[1] == '[')
1302 break;
1303 else if (ISALPHA (c[1]) && c[2] == '[')
1304 break;
1305 else
1307 c += 1 + (c[1] == '%');
1308 continue;
1312 if (c)
1314 /* OK, we need to make a copy so we can perform the substitutions.
1315 Assume that we will not need extra space--we get to remove '['
1316 and ']', which means we cannot have a problem until we have more
1317 than 999 operands. */
1318 buffer = xstrdup (TREE_STRING_POINTER (string));
1319 p = buffer + (c - TREE_STRING_POINTER (string));
1321 while ((p = strchr (p, '%')) != NULL)
1323 if (p[1] == '[')
1324 p += 1;
1325 else if (ISALPHA (p[1]) && p[2] == '[')
1326 p += 2;
1327 else
1329 p += 1 + (p[1] == '%');
1330 continue;
1333 p = resolve_operand_name_1 (p, outputs, inputs, labels);
1336 string = build_string (strlen (buffer), buffer);
1337 free (buffer);
1340 return string;
1343 /* A subroutine of resolve_operand_names. P points to the '[' for a
1344 potential named operand of the form [<name>]. In place, replace
1345 the name and brackets with a number. Return a pointer to the
1346 balance of the string after substitution. */
1348 static char *
1349 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
1351 char *q;
1352 int op;
1353 tree t;
1355 /* Collect the operand name. */
1356 q = strchr (++p, ']');
1357 if (!q)
1359 error ("missing close brace for named operand");
1360 return strchr (p, '\0');
1362 *q = '\0';
1364 /* Resolve the name to a number. */
1365 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
1367 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1368 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1369 goto found;
1371 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
1373 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1374 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1375 goto found;
1377 for (t = labels; t ; t = TREE_CHAIN (t), op++)
1379 tree name = TREE_PURPOSE (t);
1380 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1381 goto found;
1384 error ("undefined named operand %qs", identifier_to_locale (p));
1385 op = 0;
1387 found:
1388 /* Replace the name with the number. Unfortunately, not all libraries
1389 get the return value of sprintf correct, so search for the end of the
1390 generated string by hand. */
1391 sprintf (--p, "%d", op);
1392 p = strchr (p, '\0');
1394 /* Verify the no extra buffer space assumption. */
1395 gcc_assert (p <= q);
1397 /* Shift the rest of the buffer down to fill the gap. */
1398 memmove (p, q + 1, strlen (q + 1) + 1);
1400 return p;
1403 /* Generate RTL to return from the current function, with no value.
1404 (That is, we do not do anything about returning any value.) */
1406 void
1407 expand_null_return (void)
1409 /* If this function was declared to return a value, but we
1410 didn't, clobber the return registers so that they are not
1411 propagated live to the rest of the function. */
1412 clobber_return_register ();
1414 expand_null_return_1 ();
1417 /* Generate RTL to return directly from the current function.
1418 (That is, we bypass any return value.) */
1420 void
1421 expand_naked_return (void)
1423 rtx end_label;
1425 clear_pending_stack_adjust ();
1426 do_pending_stack_adjust ();
1428 end_label = naked_return_label;
1429 if (end_label == 0)
1430 end_label = naked_return_label = gen_label_rtx ();
1432 emit_jump (end_label);
1435 /* Generate RTL to return from the current function, with value VAL. */
1437 static void
1438 expand_value_return (rtx val)
1440 /* Copy the value to the return location unless it's already there. */
1442 tree decl = DECL_RESULT (current_function_decl);
1443 rtx return_reg = DECL_RTL (decl);
1444 if (return_reg != val)
1446 tree funtype = TREE_TYPE (current_function_decl);
1447 tree type = TREE_TYPE (decl);
1448 int unsignedp = TYPE_UNSIGNED (type);
1449 enum machine_mode old_mode = DECL_MODE (decl);
1450 enum machine_mode mode;
1451 if (DECL_BY_REFERENCE (decl))
1452 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 2);
1453 else
1454 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 1);
1456 if (mode != old_mode)
1457 val = convert_modes (mode, old_mode, val, unsignedp);
1459 if (GET_CODE (return_reg) == PARALLEL)
1460 emit_group_load (return_reg, val, type, int_size_in_bytes (type));
1461 else
1462 emit_move_insn (return_reg, val);
1465 expand_null_return_1 ();
1468 /* Output a return with no value. */
1470 static void
1471 expand_null_return_1 (void)
1473 clear_pending_stack_adjust ();
1474 do_pending_stack_adjust ();
1475 emit_jump (return_label);
1478 /* Generate RTL to evaluate the expression RETVAL and return it
1479 from the current function. */
1481 void
1482 expand_return (tree retval)
1484 rtx result_rtl;
1485 rtx val = 0;
1486 tree retval_rhs;
1488 /* If function wants no value, give it none. */
1489 if (TREE_CODE (TREE_TYPE (TREE_TYPE (current_function_decl))) == VOID_TYPE)
1491 expand_normal (retval);
1492 expand_null_return ();
1493 return;
1496 if (retval == error_mark_node)
1498 /* Treat this like a return of no value from a function that
1499 returns a value. */
1500 expand_null_return ();
1501 return;
1503 else if ((TREE_CODE (retval) == MODIFY_EXPR
1504 || TREE_CODE (retval) == INIT_EXPR)
1505 && TREE_CODE (TREE_OPERAND (retval, 0)) == RESULT_DECL)
1506 retval_rhs = TREE_OPERAND (retval, 1);
1507 else
1508 retval_rhs = retval;
1510 result_rtl = DECL_RTL (DECL_RESULT (current_function_decl));
1512 /* If we are returning the RESULT_DECL, then the value has already
1513 been stored into it, so we don't have to do anything special. */
1514 if (TREE_CODE (retval_rhs) == RESULT_DECL)
1515 expand_value_return (result_rtl);
1517 /* If the result is an aggregate that is being returned in one (or more)
1518 registers, load the registers here. */
1520 else if (retval_rhs != 0
1521 && TYPE_MODE (TREE_TYPE (retval_rhs)) == BLKmode
1522 && REG_P (result_rtl))
1524 val = copy_blkmode_to_reg (GET_MODE (result_rtl), retval_rhs);
1525 if (val)
1527 /* Use the mode of the result value on the return register. */
1528 PUT_MODE (result_rtl, GET_MODE (val));
1529 expand_value_return (val);
1531 else
1532 expand_null_return ();
1534 else if (retval_rhs != 0
1535 && !VOID_TYPE_P (TREE_TYPE (retval_rhs))
1536 && (REG_P (result_rtl)
1537 || (GET_CODE (result_rtl) == PARALLEL)))
1539 /* Calculate the return value into a temporary (usually a pseudo
1540 reg). */
1541 tree ot = TREE_TYPE (DECL_RESULT (current_function_decl));
1542 tree nt = build_qualified_type (ot, TYPE_QUALS (ot) | TYPE_QUAL_CONST);
1544 val = assign_temp (nt, 0, 1);
1545 val = expand_expr (retval_rhs, val, GET_MODE (val), EXPAND_NORMAL);
1546 val = force_not_mem (val);
1547 /* Return the calculated value. */
1548 expand_value_return (val);
1550 else
1552 /* No hard reg used; calculate value into hard return reg. */
1553 expand_expr (retval, const0_rtx, VOIDmode, EXPAND_NORMAL);
1554 expand_value_return (result_rtl);
1559 /* Emit code to save the current value of stack. */
1561 expand_stack_save (void)
1563 rtx ret = NULL_RTX;
1565 do_pending_stack_adjust ();
1566 emit_stack_save (SAVE_BLOCK, &ret);
1567 return ret;
1570 /* Emit code to restore the current value of stack. */
1571 void
1572 expand_stack_restore (tree var)
1574 rtx prev, sa = expand_normal (var);
1576 sa = convert_memory_address (Pmode, sa);
1578 prev = get_last_insn ();
1579 emit_stack_restore (SAVE_BLOCK, sa);
1580 fixup_args_size_notes (prev, get_last_insn (), 0);
1583 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
1584 is the probability of jumping to LABEL. */
1585 static void
1586 do_jump_if_equal (enum machine_mode mode, rtx op0, rtx op1, rtx label,
1587 int unsignedp, int prob)
1589 gcc_assert (prob <= REG_BR_PROB_BASE);
1590 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
1591 NULL_RTX, NULL_RTX, label, prob);
1594 /* Do the insertion of a case label into case_list. The labels are
1595 fed to us in descending order from the sorted vector of case labels used
1596 in the tree part of the middle end. So the list we construct is
1597 sorted in ascending order.
1599 LABEL is the case label to be inserted. LOW and HIGH are the bounds
1600 against which the index is compared to jump to LABEL and PROB is the
1601 estimated probability LABEL is reached from the switch statement. */
1603 static struct case_node *
1604 add_case_node (struct case_node *head, tree low, tree high,
1605 tree label, int prob, alloc_pool case_node_pool)
1607 struct case_node *r;
1609 gcc_checking_assert (low);
1610 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
1612 /* Add this label to the chain. */
1613 r = (struct case_node *) pool_alloc (case_node_pool);
1614 r->low = low;
1615 r->high = high;
1616 r->code_label = label;
1617 r->parent = r->left = NULL;
1618 r->prob = prob;
1619 r->subtree_prob = prob;
1620 r->right = head;
1621 return r;
1624 /* Dump ROOT, a list or tree of case nodes, to file. */
1626 static void
1627 dump_case_nodes (FILE *f, struct case_node *root,
1628 int indent_step, int indent_level)
1630 HOST_WIDE_INT low, high;
1632 if (root == 0)
1633 return;
1634 indent_level++;
1636 dump_case_nodes (f, root->left, indent_step, indent_level);
1638 low = tree_low_cst (root->low, 0);
1639 high = tree_low_cst (root->high, 0);
1641 fputs (";; ", f);
1642 if (high == low)
1643 fprintf(f, "%*s" HOST_WIDE_INT_PRINT_DEC,
1644 indent_step * indent_level, "", low);
1645 else
1646 fprintf(f, "%*s" HOST_WIDE_INT_PRINT_DEC " ... " HOST_WIDE_INT_PRINT_DEC,
1647 indent_step * indent_level, "", low, high);
1648 fputs ("\n", f);
1650 dump_case_nodes (f, root->right, indent_step, indent_level);
1653 #ifndef HAVE_casesi
1654 #define HAVE_casesi 0
1655 #endif
1657 #ifndef HAVE_tablejump
1658 #define HAVE_tablejump 0
1659 #endif
1661 /* Return the smallest number of different values for which it is best to use a
1662 jump-table instead of a tree of conditional branches. */
1664 static unsigned int
1665 case_values_threshold (void)
1667 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
1669 if (threshold == 0)
1670 threshold = targetm.case_values_threshold ();
1672 return threshold;
1675 /* Return true if a switch should be expanded as a decision tree.
1676 RANGE is the difference between highest and lowest case.
1677 UNIQ is number of unique case node targets, not counting the default case.
1678 COUNT is the number of comparisons needed, not counting the default case. */
1680 static bool
1681 expand_switch_as_decision_tree_p (tree range,
1682 unsigned int uniq ATTRIBUTE_UNUSED,
1683 unsigned int count)
1685 int max_ratio;
1687 /* If neither casesi or tablejump is available, or flag_jump_tables
1688 over-ruled us, we really have no choice. */
1689 if (!HAVE_casesi && !HAVE_tablejump)
1690 return true;
1691 if (!flag_jump_tables)
1692 return true;
1694 /* If the switch is relatively small such that the cost of one
1695 indirect jump on the target are higher than the cost of a
1696 decision tree, go with the decision tree.
1698 If range of values is much bigger than number of values,
1699 or if it is too large to represent in a HOST_WIDE_INT,
1700 make a sequence of conditional branches instead of a dispatch.
1702 The definition of "much bigger" depends on whether we are
1703 optimizing for size or for speed. If the former, the maximum
1704 ratio range/count = 3, because this was found to be the optimal
1705 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
1706 10 is much older, and was probably selected after an extensive
1707 benchmarking investigation on numerous platforms. Or maybe it
1708 just made sense to someone at some point in the history of GCC,
1709 who knows... */
1710 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
1711 if (count < case_values_threshold ()
1712 || ! host_integerp (range, /*pos=*/1)
1713 || compare_tree_int (range, max_ratio * count) > 0)
1714 return true;
1716 return false;
1719 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1720 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1721 DEFAULT_PROB is the estimated probability that it jumps to
1722 DEFAULT_LABEL.
1724 We generate a binary decision tree to select the appropriate target
1725 code. This is done as follows:
1727 If the index is a short or char that we do not have
1728 an insn to handle comparisons directly, convert it to
1729 a full integer now, rather than letting each comparison
1730 generate the conversion.
1732 Load the index into a register.
1734 The list of cases is rearranged into a binary tree,
1735 nearly optimal assuming equal probability for each case.
1737 The tree is transformed into RTL, eliminating redundant
1738 test conditions at the same time.
1740 If program flow could reach the end of the decision tree
1741 an unconditional jump to the default code is emitted.
1743 The above process is unaware of the CFG. The caller has to fix up
1744 the CFG itself. This is done in cfgexpand.c. */
1746 static void
1747 emit_case_decision_tree (tree index_expr, tree index_type,
1748 struct case_node *case_list, rtx default_label,
1749 int default_prob)
1751 rtx index = expand_normal (index_expr);
1753 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
1754 && ! have_insn_for (COMPARE, GET_MODE (index)))
1756 int unsignedp = TYPE_UNSIGNED (index_type);
1757 enum machine_mode wider_mode;
1758 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
1759 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
1760 if (have_insn_for (COMPARE, wider_mode))
1762 index = convert_to_mode (wider_mode, index, unsignedp);
1763 break;
1767 do_pending_stack_adjust ();
1769 if (MEM_P (index))
1771 index = copy_to_reg (index);
1772 if (TREE_CODE (index_expr) == SSA_NAME)
1773 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
1776 balance_case_nodes (&case_list, NULL);
1778 if (dump_file && (dump_flags & TDF_DETAILS))
1780 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1781 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1782 dump_case_nodes (dump_file, case_list, indent_step, 0);
1785 emit_case_nodes (index, case_list, default_label, default_prob, index_type);
1786 if (default_label)
1787 emit_jump (default_label);
1790 /* Return the sum of probabilities of outgoing edges of basic block BB. */
1792 static int
1793 get_outgoing_edge_probs (basic_block bb)
1795 edge e;
1796 edge_iterator ei;
1797 int prob_sum = 0;
1798 FOR_EACH_EDGE(e, ei, bb->succs)
1799 prob_sum += e->probability;
1800 return prob_sum;
1803 /* Computes the conditional probability of jumping to a target if the branch
1804 instruction is executed.
1805 TARGET_PROB is the estimated probability of jumping to a target relative
1806 to some basic block BB.
1807 BASE_PROB is the probability of reaching the branch instruction relative
1808 to the same basic block BB. */
1810 static inline int
1811 conditional_probability (int target_prob, int base_prob)
1813 if (base_prob > 0)
1815 gcc_assert (target_prob >= 0);
1816 gcc_assert (target_prob <= base_prob);
1817 return RDIV (target_prob * REG_BR_PROB_BASE, base_prob);
1819 return -1;
1822 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
1823 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1824 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
1825 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
1827 First, a jump insn is emitted. First we try "casesi". If that
1828 fails, try "tablejump". A target *must* have one of them (or both).
1830 Then, a table with the target labels is emitted.
1832 The process is unaware of the CFG. The caller has to fix up
1833 the CFG itself. This is done in cfgexpand.c. */
1835 static void
1836 emit_case_dispatch_table (tree index_expr, tree index_type,
1837 struct case_node *case_list, rtx default_label,
1838 tree minval, tree maxval, tree range,
1839 basic_block stmt_bb)
1841 int i, ncases;
1842 struct case_node *n;
1843 rtx *labelvec;
1844 rtx fallback_label = label_rtx (case_list->code_label);
1845 rtx table_label = gen_label_rtx ();
1846 bool has_gaps = false;
1847 edge default_edge = EDGE_SUCC(stmt_bb, 0);
1848 int default_prob = default_edge->probability;
1849 int base = get_outgoing_edge_probs (stmt_bb);
1850 bool try_with_tablejump = false;
1852 int new_default_prob = conditional_probability (default_prob,
1853 base);
1855 if (! try_casesi (index_type, index_expr, minval, range,
1856 table_label, default_label, fallback_label,
1857 new_default_prob))
1859 /* Index jumptables from zero for suitable values of minval to avoid
1860 a subtraction. For the rationale see:
1861 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
1862 if (optimize_insn_for_speed_p ()
1863 && compare_tree_int (minval, 0) > 0
1864 && compare_tree_int (minval, 3) < 0)
1866 minval = build_int_cst (index_type, 0);
1867 range = maxval;
1868 has_gaps = true;
1870 try_with_tablejump = true;
1873 /* Get table of labels to jump to, in order of case index. */
1875 ncases = tree_low_cst (range, 0) + 1;
1876 labelvec = XALLOCAVEC (rtx, ncases);
1877 memset (labelvec, 0, ncases * sizeof (rtx));
1879 for (n = case_list; n; n = n->right)
1881 /* Compute the low and high bounds relative to the minimum
1882 value since that should fit in a HOST_WIDE_INT while the
1883 actual values may not. */
1884 HOST_WIDE_INT i_low
1885 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1886 n->low, minval), 1);
1887 HOST_WIDE_INT i_high
1888 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1889 n->high, minval), 1);
1890 HOST_WIDE_INT i;
1892 for (i = i_low; i <= i_high; i ++)
1893 labelvec[i]
1894 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1897 /* Fill in the gaps with the default. We may have gaps at
1898 the beginning if we tried to avoid the minval subtraction,
1899 so substitute some label even if the default label was
1900 deemed unreachable. */
1901 if (!default_label)
1902 default_label = fallback_label;
1903 for (i = 0; i < ncases; i++)
1904 if (labelvec[i] == 0)
1906 has_gaps = true;
1907 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1910 if (has_gaps)
1912 /* There is at least one entry in the jump table that jumps
1913 to default label. The default label can either be reached
1914 through the indirect jump or the direct conditional jump
1915 before that. Split the probability of reaching the
1916 default label among these two jumps. */
1917 new_default_prob = conditional_probability (default_prob/2,
1918 base);
1919 default_prob /= 2;
1920 base -= default_prob;
1922 else
1924 base -= default_prob;
1925 default_prob = 0;
1928 default_edge->probability = default_prob;
1930 /* We have altered the probability of the default edge. So the probabilities
1931 of all other edges need to be adjusted so that it sums up to
1932 REG_BR_PROB_BASE. */
1933 if (base)
1935 edge e;
1936 edge_iterator ei;
1937 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
1938 e->probability = RDIV (e->probability * REG_BR_PROB_BASE, base);
1941 if (try_with_tablejump)
1943 bool ok = try_tablejump (index_type, index_expr, minval, range,
1944 table_label, default_label, new_default_prob);
1945 gcc_assert (ok);
1947 /* Output the table. */
1948 emit_label (table_label);
1950 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1951 emit_jump_insn (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1952 gen_rtx_LABEL_REF (Pmode, table_label),
1953 gen_rtvec_v (ncases, labelvec),
1954 const0_rtx, const0_rtx));
1955 else
1956 emit_jump_insn (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1957 gen_rtvec_v (ncases, labelvec)));
1959 /* Record no drop-through after the table. */
1960 emit_barrier ();
1963 /* Reset the aux field of all outgoing edges of basic block BB. */
1965 static inline void
1966 reset_out_edges_aux (basic_block bb)
1968 edge e;
1969 edge_iterator ei;
1970 FOR_EACH_EDGE(e, ei, bb->succs)
1971 e->aux = (void *)0;
1974 /* Compute the number of case labels that correspond to each outgoing edge of
1975 STMT. Record this information in the aux field of the edge. */
1977 static inline void
1978 compute_cases_per_edge (gimple stmt)
1980 basic_block bb = gimple_bb (stmt);
1981 reset_out_edges_aux (bb);
1982 int ncases = gimple_switch_num_labels (stmt);
1983 for (int i = ncases - 1; i >= 1; --i)
1985 tree elt = gimple_switch_label (stmt, i);
1986 tree lab = CASE_LABEL (elt);
1987 basic_block case_bb = label_to_block_fn (cfun, lab);
1988 edge case_edge = find_edge (bb, case_bb);
1989 case_edge->aux = (void *)((long)(case_edge->aux) + 1);
1993 /* Terminate a case (Pascal/Ada) or switch (C) statement
1994 in which ORIG_INDEX is the expression to be tested.
1995 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
1996 type as given in the source before any compiler conversions.
1997 Generate the code to test it and jump to the right place. */
1999 void
2000 expand_case (gimple stmt)
2002 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
2003 rtx default_label = NULL_RTX;
2004 unsigned int count, uniq;
2005 int i;
2006 int ncases = gimple_switch_num_labels (stmt);
2007 tree index_expr = gimple_switch_index (stmt);
2008 tree index_type = TREE_TYPE (index_expr);
2009 tree elt;
2010 basic_block bb = gimple_bb (stmt);
2012 /* A list of case labels; it is first built as a list and it may then
2013 be rearranged into a nearly balanced binary tree. */
2014 struct case_node *case_list = 0;
2016 /* A pool for case nodes. */
2017 alloc_pool case_node_pool;
2019 /* An ERROR_MARK occurs for various reasons including invalid data type.
2020 ??? Can this still happen, with GIMPLE and all? */
2021 if (index_type == error_mark_node)
2022 return;
2024 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
2025 expressions being INTEGER_CST. */
2026 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
2028 case_node_pool = create_alloc_pool ("struct case_node pool",
2029 sizeof (struct case_node),
2030 100);
2032 do_pending_stack_adjust ();
2034 /* Find the default case target label. */
2035 default_label = label_rtx (CASE_LABEL (gimple_switch_default_label (stmt)));
2036 edge default_edge = EDGE_SUCC(bb, 0);
2037 int default_prob = default_edge->probability;
2039 /* Get upper and lower bounds of case values. */
2040 elt = gimple_switch_label (stmt, 1);
2041 minval = fold_convert (index_type, CASE_LOW (elt));
2042 elt = gimple_switch_label (stmt, ncases - 1);
2043 if (CASE_HIGH (elt))
2044 maxval = fold_convert (index_type, CASE_HIGH (elt));
2045 else
2046 maxval = fold_convert (index_type, CASE_LOW (elt));
2048 /* Compute span of values. */
2049 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
2051 /* Listify the labels queue and gather some numbers to decide
2052 how to expand this switch(). */
2053 uniq = 0;
2054 count = 0;
2055 struct pointer_set_t *seen_labels = pointer_set_create ();
2056 compute_cases_per_edge (stmt);
2058 for (i = ncases - 1; i >= 1; --i)
2060 elt = gimple_switch_label (stmt, i);
2061 tree low = CASE_LOW (elt);
2062 gcc_assert (low);
2063 tree high = CASE_HIGH (elt);
2064 gcc_assert (! high || tree_int_cst_lt (low, high));
2065 tree lab = CASE_LABEL (elt);
2067 /* Count the elements.
2068 A range counts double, since it requires two compares. */
2069 count++;
2070 if (high)
2071 count++;
2073 /* If we have not seen this label yet, then increase the
2074 number of unique case node targets seen. */
2075 if (!pointer_set_insert (seen_labels, lab))
2076 uniq++;
2078 /* The bounds on the case range, LOW and HIGH, have to be converted
2079 to case's index type TYPE. Note that the original type of the
2080 case index in the source code is usually "lost" during
2081 gimplification due to type promotion, but the case labels retain the
2082 original type. Make sure to drop overflow flags. */
2083 low = fold_convert (index_type, low);
2084 if (TREE_OVERFLOW (low))
2085 low = build_int_cst_wide (index_type,
2086 TREE_INT_CST_LOW (low),
2087 TREE_INT_CST_HIGH (low));
2089 /* The canonical from of a case label in GIMPLE is that a simple case
2090 has an empty CASE_HIGH. For the casesi and tablejump expanders,
2091 the back ends want simple cases to have high == low. */
2092 if (! high)
2093 high = low;
2094 high = fold_convert (index_type, high);
2095 if (TREE_OVERFLOW (high))
2096 high = build_int_cst_wide (index_type,
2097 TREE_INT_CST_LOW (high),
2098 TREE_INT_CST_HIGH (high));
2100 basic_block case_bb = label_to_block_fn (cfun, lab);
2101 edge case_edge = find_edge (bb, case_bb);
2102 case_list = add_case_node (
2103 case_list, low, high, lab,
2104 case_edge->probability / (long)(case_edge->aux),
2105 case_node_pool);
2107 pointer_set_destroy (seen_labels);
2108 reset_out_edges_aux (bb);
2110 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
2111 destination, such as one with a default case only.
2112 It also removes cases that are out of range for the switch
2113 type, so we should never get a zero here. */
2114 gcc_assert (count > 0);
2116 rtx before_case = get_last_insn ();
2118 /* Decide how to expand this switch.
2119 The two options at this point are a dispatch table (casesi or
2120 tablejump) or a decision tree. */
2122 if (expand_switch_as_decision_tree_p (range, uniq, count))
2123 emit_case_decision_tree (index_expr, index_type,
2124 case_list, default_label,
2125 default_prob);
2126 else
2127 emit_case_dispatch_table (index_expr, index_type,
2128 case_list, default_label,
2129 minval, maxval, range, bb);
2131 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2133 free_temp_slots ();
2134 free_alloc_pool (case_node_pool);
2137 /* Expand the dispatch to a short decrement chain if there are few cases
2138 to dispatch to. Likewise if neither casesi nor tablejump is available,
2139 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
2140 tablejump. The index mode is always the mode of integer_type_node.
2141 Trap if no case matches the index.
2143 DISPATCH_INDEX is the index expression to switch on. It should be a
2144 memory or register operand.
2146 DISPATCH_TABLE is a set of case labels. The set should be sorted in
2147 ascending order, be contiguous, starting with value 0, and contain only
2148 single-valued case labels. */
2150 void
2151 expand_sjlj_dispatch_table (rtx dispatch_index,
2152 VEC(tree,heap) *dispatch_table)
2154 tree index_type = integer_type_node;
2155 enum machine_mode index_mode = TYPE_MODE (index_type);
2157 int ncases = VEC_length (tree, dispatch_table);
2159 do_pending_stack_adjust ();
2160 rtx before_case = get_last_insn ();
2162 /* Expand as a decrement-chain if there are 5 or fewer dispatch
2163 labels. This covers more than 98% of the cases in libjava,
2164 and seems to be a reasonable compromise between the "old way"
2165 of expanding as a decision tree or dispatch table vs. the "new
2166 way" with decrement chain or dispatch table. */
2167 if (VEC_length (tree, dispatch_table) <= 5
2168 || (!HAVE_casesi && !HAVE_tablejump)
2169 || !flag_jump_tables)
2171 /* Expand the dispatch as a decrement chain:
2173 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
2177 if (index == 0) do_0; else index--;
2178 if (index == 0) do_1; else index--;
2180 if (index == 0) do_N; else index--;
2182 This is more efficient than a dispatch table on most machines.
2183 The last "index--" is redundant but the code is trivially dead
2184 and will be cleaned up by later passes. */
2185 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
2186 rtx zero = CONST0_RTX (index_mode);
2187 for (int i = 0; i < ncases; i++)
2189 tree elt = VEC_index (tree, dispatch_table, i);
2190 rtx lab = label_rtx (CASE_LABEL (elt));
2191 do_jump_if_equal (index_mode, index, zero, lab, 0, -1);
2192 force_expand_binop (index_mode, sub_optab,
2193 index, CONST1_RTX (index_mode),
2194 index, 0, OPTAB_DIRECT);
2197 else
2199 /* Similar to expand_case, but much simpler. */
2200 struct case_node *case_list = 0;
2201 alloc_pool case_node_pool = create_alloc_pool ("struct sjlj_case pool",
2202 sizeof (struct case_node),
2203 ncases);
2204 tree index_expr = make_tree (index_type, dispatch_index);
2205 tree minval = build_int_cst (index_type, 0);
2206 tree maxval = CASE_LOW (VEC_last (tree, dispatch_table));
2207 tree range = maxval;
2208 rtx default_label = gen_label_rtx ();
2210 for (int i = ncases - 1; i > 0; --i)
2212 tree elt = VEC_index (tree, dispatch_table, i);
2213 tree low = CASE_LOW (elt);
2214 tree lab = CASE_LABEL (elt);
2215 case_list = add_case_node (case_list, low, low, lab, 0, case_node_pool);
2218 emit_case_dispatch_table (index_expr, index_type,
2219 case_list, default_label,
2220 minval, maxval, range, NULL);
2221 emit_label (default_label);
2222 free_alloc_pool (case_node_pool);
2225 /* Dispatching something not handled? Trap! */
2226 expand_builtin_trap ();
2228 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2230 free_temp_slots ();
2234 /* Take an ordered list of case nodes
2235 and transform them into a near optimal binary tree,
2236 on the assumption that any target code selection value is as
2237 likely as any other.
2239 The transformation is performed by splitting the ordered
2240 list into two equal sections plus a pivot. The parts are
2241 then attached to the pivot as left and right branches. Each
2242 branch is then transformed recursively. */
2244 static void
2245 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
2247 case_node_ptr np;
2249 np = *head;
2250 if (np)
2252 int i = 0;
2253 int ranges = 0;
2254 case_node_ptr *npp;
2255 case_node_ptr left;
2257 /* Count the number of entries on branch. Also count the ranges. */
2259 while (np)
2261 if (!tree_int_cst_equal (np->low, np->high))
2262 ranges++;
2264 i++;
2265 np = np->right;
2268 if (i > 2)
2270 /* Split this list if it is long enough for that to help. */
2271 npp = head;
2272 left = *npp;
2274 /* If there are just three nodes, split at the middle one. */
2275 if (i == 3)
2276 npp = &(*npp)->right;
2277 else
2279 /* Find the place in the list that bisects the list's total cost,
2280 where ranges count as 2.
2281 Here I gets half the total cost. */
2282 i = (i + ranges + 1) / 2;
2283 while (1)
2285 /* Skip nodes while their cost does not reach that amount. */
2286 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
2287 i--;
2288 i--;
2289 if (i <= 0)
2290 break;
2291 npp = &(*npp)->right;
2294 *head = np = *npp;
2295 *npp = 0;
2296 np->parent = parent;
2297 np->left = left;
2299 /* Optimize each of the two split parts. */
2300 balance_case_nodes (&np->left, np);
2301 balance_case_nodes (&np->right, np);
2302 np->subtree_prob = np->prob;
2303 np->subtree_prob += np->left->subtree_prob;
2304 np->subtree_prob += np->right->subtree_prob;
2306 else
2308 /* Else leave this branch as one level,
2309 but fill in `parent' fields. */
2310 np = *head;
2311 np->parent = parent;
2312 np->subtree_prob = np->prob;
2313 for (; np->right; np = np->right)
2315 np->right->parent = np;
2316 (*head)->subtree_prob += np->right->subtree_prob;
2322 /* Search the parent sections of the case node tree
2323 to see if a test for the lower bound of NODE would be redundant.
2324 INDEX_TYPE is the type of the index expression.
2326 The instructions to generate the case decision tree are
2327 output in the same order as nodes are processed so it is
2328 known that if a parent node checks the range of the current
2329 node minus one that the current node is bounded at its lower
2330 span. Thus the test would be redundant. */
2332 static int
2333 node_has_low_bound (case_node_ptr node, tree index_type)
2335 tree low_minus_one;
2336 case_node_ptr pnode;
2338 /* If the lower bound of this node is the lowest value in the index type,
2339 we need not test it. */
2341 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
2342 return 1;
2344 /* If this node has a left branch, the value at the left must be less
2345 than that at this node, so it cannot be bounded at the bottom and
2346 we need not bother testing any further. */
2348 if (node->left)
2349 return 0;
2351 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
2352 node->low,
2353 build_int_cst (TREE_TYPE (node->low), 1));
2355 /* If the subtraction above overflowed, we can't verify anything.
2356 Otherwise, look for a parent that tests our value - 1. */
2358 if (! tree_int_cst_lt (low_minus_one, node->low))
2359 return 0;
2361 for (pnode = node->parent; pnode; pnode = pnode->parent)
2362 if (tree_int_cst_equal (low_minus_one, pnode->high))
2363 return 1;
2365 return 0;
2368 /* Search the parent sections of the case node tree
2369 to see if a test for the upper bound of NODE would be redundant.
2370 INDEX_TYPE is the type of the index expression.
2372 The instructions to generate the case decision tree are
2373 output in the same order as nodes are processed so it is
2374 known that if a parent node checks the range of the current
2375 node plus one that the current node is bounded at its upper
2376 span. Thus the test would be redundant. */
2378 static int
2379 node_has_high_bound (case_node_ptr node, tree index_type)
2381 tree high_plus_one;
2382 case_node_ptr pnode;
2384 /* If there is no upper bound, obviously no test is needed. */
2386 if (TYPE_MAX_VALUE (index_type) == NULL)
2387 return 1;
2389 /* If the upper bound of this node is the highest value in the type
2390 of the index expression, we need not test against it. */
2392 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
2393 return 1;
2395 /* If this node has a right branch, the value at the right must be greater
2396 than that at this node, so it cannot be bounded at the top and
2397 we need not bother testing any further. */
2399 if (node->right)
2400 return 0;
2402 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
2403 node->high,
2404 build_int_cst (TREE_TYPE (node->high), 1));
2406 /* If the addition above overflowed, we can't verify anything.
2407 Otherwise, look for a parent that tests our value + 1. */
2409 if (! tree_int_cst_lt (node->high, high_plus_one))
2410 return 0;
2412 for (pnode = node->parent; pnode; pnode = pnode->parent)
2413 if (tree_int_cst_equal (high_plus_one, pnode->low))
2414 return 1;
2416 return 0;
2419 /* Search the parent sections of the
2420 case node tree to see if both tests for the upper and lower
2421 bounds of NODE would be redundant. */
2423 static int
2424 node_is_bounded (case_node_ptr node, tree index_type)
2426 return (node_has_low_bound (node, index_type)
2427 && node_has_high_bound (node, index_type));
2431 /* Emit step-by-step code to select a case for the value of INDEX.
2432 The thus generated decision tree follows the form of the
2433 case-node binary tree NODE, whose nodes represent test conditions.
2434 INDEX_TYPE is the type of the index of the switch.
2436 Care is taken to prune redundant tests from the decision tree
2437 by detecting any boundary conditions already checked by
2438 emitted rtx. (See node_has_high_bound, node_has_low_bound
2439 and node_is_bounded, above.)
2441 Where the test conditions can be shown to be redundant we emit
2442 an unconditional jump to the target code. As a further
2443 optimization, the subordinates of a tree node are examined to
2444 check for bounded nodes. In this case conditional and/or
2445 unconditional jumps as a result of the boundary check for the
2446 current node are arranged to target the subordinates associated
2447 code for out of bound conditions on the current node.
2449 We can assume that when control reaches the code generated here,
2450 the index value has already been compared with the parents
2451 of this node, and determined to be on the same side of each parent
2452 as this node is. Thus, if this node tests for the value 51,
2453 and a parent tested for 52, we don't need to consider
2454 the possibility of a value greater than 51. If another parent
2455 tests for the value 50, then this node need not test anything. */
2457 static void
2458 emit_case_nodes (rtx index, case_node_ptr node, rtx default_label,
2459 int default_prob, tree index_type)
2461 /* If INDEX has an unsigned type, we must make unsigned branches. */
2462 int unsignedp = TYPE_UNSIGNED (index_type);
2463 int probability;
2464 int prob = node->prob, subtree_prob = node->subtree_prob;
2465 enum machine_mode mode = GET_MODE (index);
2466 enum machine_mode imode = TYPE_MODE (index_type);
2468 /* Handle indices detected as constant during RTL expansion. */
2469 if (mode == VOIDmode)
2470 mode = imode;
2472 /* See if our parents have already tested everything for us.
2473 If they have, emit an unconditional jump for this node. */
2474 if (node_is_bounded (node, index_type))
2475 emit_jump (label_rtx (node->code_label));
2477 else if (tree_int_cst_equal (node->low, node->high))
2479 probability = conditional_probability (prob, subtree_prob + default_prob);
2480 /* Node is single valued. First see if the index expression matches
2481 this node and then check our children, if any. */
2482 do_jump_if_equal (mode, index,
2483 convert_modes (mode, imode,
2484 expand_normal (node->low),
2485 unsignedp),
2486 label_rtx (node->code_label), unsignedp, probability);
2487 /* Since this case is taken at this point, reduce its weight from
2488 subtree_weight. */
2489 subtree_prob -= prob;
2490 if (node->right != 0 && node->left != 0)
2492 /* This node has children on both sides.
2493 Dispatch to one side or the other
2494 by comparing the index value with this node's value.
2495 If one subtree is bounded, check that one first,
2496 so we can avoid real branches in the tree. */
2498 if (node_is_bounded (node->right, index_type))
2500 probability = conditional_probability (
2501 node->right->prob,
2502 subtree_prob + default_prob);
2503 emit_cmp_and_jump_insns (index,
2504 convert_modes
2505 (mode, imode,
2506 expand_normal (node->high),
2507 unsignedp),
2508 GT, NULL_RTX, mode, unsignedp,
2509 label_rtx (node->right->code_label),
2510 probability);
2511 emit_case_nodes (index, node->left, default_label, default_prob,
2512 index_type);
2515 else if (node_is_bounded (node->left, index_type))
2517 probability = conditional_probability (
2518 node->left->prob,
2519 subtree_prob + default_prob);
2520 emit_cmp_and_jump_insns (index,
2521 convert_modes
2522 (mode, imode,
2523 expand_normal (node->high),
2524 unsignedp),
2525 LT, NULL_RTX, mode, unsignedp,
2526 label_rtx (node->left->code_label),
2527 probability);
2528 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2531 /* If both children are single-valued cases with no
2532 children, finish up all the work. This way, we can save
2533 one ordered comparison. */
2534 else if (tree_int_cst_equal (node->right->low, node->right->high)
2535 && node->right->left == 0
2536 && node->right->right == 0
2537 && tree_int_cst_equal (node->left->low, node->left->high)
2538 && node->left->left == 0
2539 && node->left->right == 0)
2541 /* Neither node is bounded. First distinguish the two sides;
2542 then emit the code for one side at a time. */
2544 /* See if the value matches what the right hand side
2545 wants. */
2546 probability = conditional_probability (
2547 node->right->prob,
2548 subtree_prob + default_prob);
2549 do_jump_if_equal (mode, index,
2550 convert_modes (mode, imode,
2551 expand_normal (node->right->low),
2552 unsignedp),
2553 label_rtx (node->right->code_label),
2554 unsignedp, probability);
2556 /* See if the value matches what the left hand side
2557 wants. */
2558 probability = conditional_probability (
2559 node->left->prob,
2560 subtree_prob + default_prob);
2561 do_jump_if_equal (mode, index,
2562 convert_modes (mode, imode,
2563 expand_normal (node->left->low),
2564 unsignedp),
2565 label_rtx (node->left->code_label),
2566 unsignedp, probability);
2569 else
2571 /* Neither node is bounded. First distinguish the two sides;
2572 then emit the code for one side at a time. */
2574 tree test_label
2575 = build_decl (curr_insn_location (),
2576 LABEL_DECL, NULL_TREE, NULL_TREE);
2578 /* The default label could be reached either through the right
2579 subtree or the left subtree. Divide the probability
2580 equally. */
2581 probability = conditional_probability (
2582 node->right->subtree_prob + default_prob/2,
2583 subtree_prob + default_prob);
2584 /* See if the value is on the right. */
2585 emit_cmp_and_jump_insns (index,
2586 convert_modes
2587 (mode, imode,
2588 expand_normal (node->high),
2589 unsignedp),
2590 GT, NULL_RTX, mode, unsignedp,
2591 label_rtx (test_label),
2592 probability);
2593 default_prob /= 2;
2595 /* Value must be on the left.
2596 Handle the left-hand subtree. */
2597 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2598 /* If left-hand subtree does nothing,
2599 go to default. */
2600 if (default_label)
2601 emit_jump (default_label);
2603 /* Code branches here for the right-hand subtree. */
2604 expand_label (test_label);
2605 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2609 else if (node->right != 0 && node->left == 0)
2611 /* Here we have a right child but no left so we issue a conditional
2612 branch to default and process the right child.
2614 Omit the conditional branch to default if the right child
2615 does not have any children and is single valued; it would
2616 cost too much space to save so little time. */
2618 if (node->right->right || node->right->left
2619 || !tree_int_cst_equal (node->right->low, node->right->high))
2621 if (!node_has_low_bound (node, index_type))
2623 probability = conditional_probability (
2624 default_prob/2,
2625 subtree_prob + default_prob);
2626 emit_cmp_and_jump_insns (index,
2627 convert_modes
2628 (mode, imode,
2629 expand_normal (node->high),
2630 unsignedp),
2631 LT, NULL_RTX, mode, unsignedp,
2632 default_label,
2633 probability);
2634 default_prob /= 2;
2637 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2639 else
2641 probability = conditional_probability (
2642 node->right->subtree_prob,
2643 subtree_prob + default_prob);
2644 /* We cannot process node->right normally
2645 since we haven't ruled out the numbers less than
2646 this node's value. So handle node->right explicitly. */
2647 do_jump_if_equal (mode, index,
2648 convert_modes
2649 (mode, imode,
2650 expand_normal (node->right->low),
2651 unsignedp),
2652 label_rtx (node->right->code_label), unsignedp, probability);
2656 else if (node->right == 0 && node->left != 0)
2658 /* Just one subtree, on the left. */
2659 if (node->left->left || node->left->right
2660 || !tree_int_cst_equal (node->left->low, node->left->high))
2662 if (!node_has_high_bound (node, index_type))
2664 probability = conditional_probability (
2665 default_prob/2,
2666 subtree_prob + default_prob);
2667 emit_cmp_and_jump_insns (index,
2668 convert_modes
2669 (mode, imode,
2670 expand_normal (node->high),
2671 unsignedp),
2672 GT, NULL_RTX, mode, unsignedp,
2673 default_label,
2674 probability);
2675 default_prob /= 2;
2678 emit_case_nodes (index, node->left, default_label,
2679 default_prob, index_type);
2681 else
2683 probability = conditional_probability (
2684 node->left->subtree_prob,
2685 subtree_prob + default_prob);
2686 /* We cannot process node->left normally
2687 since we haven't ruled out the numbers less than
2688 this node's value. So handle node->left explicitly. */
2689 do_jump_if_equal (mode, index,
2690 convert_modes
2691 (mode, imode,
2692 expand_normal (node->left->low),
2693 unsignedp),
2694 label_rtx (node->left->code_label), unsignedp, probability);
2698 else
2700 /* Node is a range. These cases are very similar to those for a single
2701 value, except that we do not start by testing whether this node
2702 is the one to branch to. */
2704 if (node->right != 0 && node->left != 0)
2706 /* Node has subtrees on both sides.
2707 If the right-hand subtree is bounded,
2708 test for it first, since we can go straight there.
2709 Otherwise, we need to make a branch in the control structure,
2710 then handle the two subtrees. */
2711 tree test_label = 0;
2713 if (node_is_bounded (node->right, index_type))
2715 /* Right hand node is fully bounded so we can eliminate any
2716 testing and branch directly to the target code. */
2717 probability = conditional_probability (
2718 node->right->subtree_prob,
2719 subtree_prob + default_prob);
2720 emit_cmp_and_jump_insns (index,
2721 convert_modes
2722 (mode, imode,
2723 expand_normal (node->high),
2724 unsignedp),
2725 GT, NULL_RTX, mode, unsignedp,
2726 label_rtx (node->right->code_label),
2727 probability);
2729 else
2731 /* Right hand node requires testing.
2732 Branch to a label where we will handle it later. */
2734 test_label = build_decl (curr_insn_location (),
2735 LABEL_DECL, NULL_TREE, NULL_TREE);
2736 probability = conditional_probability (
2737 node->right->subtree_prob + default_prob/2,
2738 subtree_prob + default_prob);
2739 emit_cmp_and_jump_insns (index,
2740 convert_modes
2741 (mode, imode,
2742 expand_normal (node->high),
2743 unsignedp),
2744 GT, NULL_RTX, mode, unsignedp,
2745 label_rtx (test_label),
2746 probability);
2747 default_prob /= 2;
2750 /* Value belongs to this node or to the left-hand subtree. */
2752 probability = conditional_probability (
2753 prob,
2754 subtree_prob + default_prob);
2755 emit_cmp_and_jump_insns (index,
2756 convert_modes
2757 (mode, imode,
2758 expand_normal (node->low),
2759 unsignedp),
2760 GE, NULL_RTX, mode, unsignedp,
2761 label_rtx (node->code_label),
2762 probability);
2764 /* Handle the left-hand subtree. */
2765 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2767 /* If right node had to be handled later, do that now. */
2769 if (test_label)
2771 /* If the left-hand subtree fell through,
2772 don't let it fall into the right-hand subtree. */
2773 if (default_label)
2774 emit_jump (default_label);
2776 expand_label (test_label);
2777 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2781 else if (node->right != 0 && node->left == 0)
2783 /* Deal with values to the left of this node,
2784 if they are possible. */
2785 if (!node_has_low_bound (node, index_type))
2787 probability = conditional_probability (
2788 default_prob/2,
2789 subtree_prob + default_prob);
2790 emit_cmp_and_jump_insns (index,
2791 convert_modes
2792 (mode, imode,
2793 expand_normal (node->low),
2794 unsignedp),
2795 LT, NULL_RTX, mode, unsignedp,
2796 default_label,
2797 probability);
2798 default_prob /= 2;
2801 /* Value belongs to this node or to the right-hand subtree. */
2803 probability = conditional_probability (
2804 prob,
2805 subtree_prob + default_prob);
2806 emit_cmp_and_jump_insns (index,
2807 convert_modes
2808 (mode, imode,
2809 expand_normal (node->high),
2810 unsignedp),
2811 LE, NULL_RTX, mode, unsignedp,
2812 label_rtx (node->code_label),
2813 probability);
2815 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2818 else if (node->right == 0 && node->left != 0)
2820 /* Deal with values to the right of this node,
2821 if they are possible. */
2822 if (!node_has_high_bound (node, index_type))
2824 probability = conditional_probability (
2825 default_prob/2,
2826 subtree_prob + default_prob);
2827 emit_cmp_and_jump_insns (index,
2828 convert_modes
2829 (mode, imode,
2830 expand_normal (node->high),
2831 unsignedp),
2832 GT, NULL_RTX, mode, unsignedp,
2833 default_label,
2834 probability);
2835 default_prob /= 2;
2838 /* Value belongs to this node or to the left-hand subtree. */
2840 probability = conditional_probability (
2841 prob,
2842 subtree_prob + default_prob);
2843 emit_cmp_and_jump_insns (index,
2844 convert_modes
2845 (mode, imode,
2846 expand_normal (node->low),
2847 unsignedp),
2848 GE, NULL_RTX, mode, unsignedp,
2849 label_rtx (node->code_label),
2850 probability);
2852 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2855 else
2857 /* Node has no children so we check low and high bounds to remove
2858 redundant tests. Only one of the bounds can exist,
2859 since otherwise this node is bounded--a case tested already. */
2860 int high_bound = node_has_high_bound (node, index_type);
2861 int low_bound = node_has_low_bound (node, index_type);
2863 if (!high_bound && low_bound)
2865 probability = conditional_probability (
2866 default_prob,
2867 subtree_prob + default_prob);
2868 emit_cmp_and_jump_insns (index,
2869 convert_modes
2870 (mode, imode,
2871 expand_normal (node->high),
2872 unsignedp),
2873 GT, NULL_RTX, mode, unsignedp,
2874 default_label,
2875 probability);
2878 else if (!low_bound && high_bound)
2880 probability = conditional_probability (
2881 default_prob,
2882 subtree_prob + default_prob);
2883 emit_cmp_and_jump_insns (index,
2884 convert_modes
2885 (mode, imode,
2886 expand_normal (node->low),
2887 unsignedp),
2888 LT, NULL_RTX, mode, unsignedp,
2889 default_label,
2890 probability);
2892 else if (!low_bound && !high_bound)
2894 /* Widen LOW and HIGH to the same width as INDEX. */
2895 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2896 tree low = build1 (CONVERT_EXPR, type, node->low);
2897 tree high = build1 (CONVERT_EXPR, type, node->high);
2898 rtx low_rtx, new_index, new_bound;
2900 /* Instead of doing two branches, emit one unsigned branch for
2901 (index-low) > (high-low). */
2902 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2903 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2904 NULL_RTX, unsignedp,
2905 OPTAB_WIDEN);
2906 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2907 high, low),
2908 NULL_RTX, mode, EXPAND_NORMAL);
2910 probability = conditional_probability (
2911 default_prob,
2912 subtree_prob + default_prob);
2913 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2914 mode, 1, default_label, probability);
2917 emit_jump (label_rtx (node->code_label));