2012-09-15 Tom de Vries <tom@codesourcery.com>
[official-gcc.git] / gcc / stmt.c
blobb64b0807433168912623876ef7092b620505011c
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 */
99 typedef struct case_node case_node;
100 typedef struct case_node *case_node_ptr;
103 static int n_occurrences (int, const char *);
104 static bool tree_conflicts_with_clobbers_p (tree, HARD_REG_SET *);
105 static void expand_nl_goto_receiver (void);
106 static bool check_operand_nalternatives (tree, tree);
107 static bool check_unique_operand_names (tree, tree, tree);
108 static char *resolve_operand_name_1 (char *, tree, tree, tree);
109 static void expand_null_return_1 (void);
110 static void expand_value_return (rtx);
111 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
112 static int node_has_low_bound (case_node_ptr, tree);
113 static int node_has_high_bound (case_node_ptr, tree);
114 static int node_is_bounded (case_node_ptr, tree);
115 static void emit_case_nodes (rtx, case_node_ptr, rtx, tree);
117 /* Return the rtx-label that corresponds to a LABEL_DECL,
118 creating it if necessary. */
121 label_rtx (tree label)
123 gcc_assert (TREE_CODE (label) == LABEL_DECL);
125 if (!DECL_RTL_SET_P (label))
127 rtx r = gen_label_rtx ();
128 SET_DECL_RTL (label, r);
129 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
130 LABEL_PRESERVE_P (r) = 1;
133 return DECL_RTL (label);
136 /* As above, but also put it on the forced-reference list of the
137 function that contains it. */
139 force_label_rtx (tree label)
141 rtx ref = label_rtx (label);
142 tree function = decl_function_context (label);
144 gcc_assert (function);
146 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, ref, forced_labels);
147 return ref;
150 /* Add an unconditional jump to LABEL as the next sequential instruction. */
152 void
153 emit_jump (rtx label)
155 do_pending_stack_adjust ();
156 emit_jump_insn (gen_jump (label));
157 emit_barrier ();
160 /* Emit code to jump to the address
161 specified by the pointer expression EXP. */
163 void
164 expand_computed_goto (tree exp)
166 rtx x = expand_normal (exp);
168 x = convert_memory_address (Pmode, x);
170 do_pending_stack_adjust ();
171 emit_indirect_jump (x);
174 /* Handle goto statements and the labels that they can go to. */
176 /* Specify the location in the RTL code of a label LABEL,
177 which is a LABEL_DECL tree node.
179 This is used for the kind of label that the user can jump to with a
180 goto statement, and for alternatives of a switch or case statement.
181 RTL labels generated for loops and conditionals don't go through here;
182 they are generated directly at the RTL level, by other functions below.
184 Note that this has nothing to do with defining label *names*.
185 Languages vary in how they do that and what that even means. */
187 void
188 expand_label (tree label)
190 rtx label_r = label_rtx (label);
192 do_pending_stack_adjust ();
193 emit_label (label_r);
194 if (DECL_NAME (label))
195 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
197 if (DECL_NONLOCAL (label))
199 expand_nl_goto_receiver ();
200 nonlocal_goto_handler_labels
201 = gen_rtx_EXPR_LIST (VOIDmode, label_r,
202 nonlocal_goto_handler_labels);
205 if (FORCED_LABEL (label))
206 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, label_r, forced_labels);
208 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
209 maybe_set_first_label_num (label_r);
212 /* Generate RTL code for a `goto' statement with target label LABEL.
213 LABEL should be a LABEL_DECL tree node that was or will later be
214 defined with `expand_label'. */
216 void
217 expand_goto (tree label)
219 #ifdef ENABLE_CHECKING
220 /* Check for a nonlocal goto to a containing function. Should have
221 gotten translated to __builtin_nonlocal_goto. */
222 tree context = decl_function_context (label);
223 gcc_assert (!context || context == current_function_decl);
224 #endif
226 emit_jump (label_rtx (label));
229 /* Return the number of times character C occurs in string S. */
230 static int
231 n_occurrences (int c, const char *s)
233 int n = 0;
234 while (*s)
235 n += (*s++ == c);
236 return n;
239 /* Generate RTL for an asm statement (explicit assembler code).
240 STRING is a STRING_CST node containing the assembler code text,
241 or an ADDR_EXPR containing a STRING_CST. VOL nonzero means the
242 insn is volatile; don't optimize it. */
244 static void
245 expand_asm_loc (tree string, int vol, location_t locus)
247 rtx body;
249 if (TREE_CODE (string) == ADDR_EXPR)
250 string = TREE_OPERAND (string, 0);
252 body = gen_rtx_ASM_INPUT_loc (VOIDmode,
253 ggc_strdup (TREE_STRING_POINTER (string)),
254 locus);
256 MEM_VOLATILE_P (body) = vol;
258 emit_insn (body);
261 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
262 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
263 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
264 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
265 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
266 constraint allows the use of a register operand. And, *IS_INOUT
267 will be true if the operand is read-write, i.e., if it is used as
268 an input as well as an output. If *CONSTRAINT_P is not in
269 canonical form, it will be made canonical. (Note that `+' will be
270 replaced with `=' as part of this process.)
272 Returns TRUE if all went well; FALSE if an error occurred. */
274 bool
275 parse_output_constraint (const char **constraint_p, int operand_num,
276 int ninputs, int noutputs, bool *allows_mem,
277 bool *allows_reg, bool *is_inout)
279 const char *constraint = *constraint_p;
280 const char *p;
282 /* Assume the constraint doesn't allow the use of either a register
283 or memory. */
284 *allows_mem = false;
285 *allows_reg = false;
287 /* Allow the `=' or `+' to not be at the beginning of the string,
288 since it wasn't explicitly documented that way, and there is a
289 large body of code that puts it last. Swap the character to
290 the front, so as not to uglify any place else. */
291 p = strchr (constraint, '=');
292 if (!p)
293 p = strchr (constraint, '+');
295 /* If the string doesn't contain an `=', issue an error
296 message. */
297 if (!p)
299 error ("output operand constraint lacks %<=%>");
300 return false;
303 /* If the constraint begins with `+', then the operand is both read
304 from and written to. */
305 *is_inout = (*p == '+');
307 /* Canonicalize the output constraint so that it begins with `='. */
308 if (p != constraint || *is_inout)
310 char *buf;
311 size_t c_len = strlen (constraint);
313 if (p != constraint)
314 warning (0, "output constraint %qc for operand %d "
315 "is not at the beginning",
316 *p, operand_num);
318 /* Make a copy of the constraint. */
319 buf = XALLOCAVEC (char, c_len + 1);
320 strcpy (buf, constraint);
321 /* Swap the first character and the `=' or `+'. */
322 buf[p - constraint] = buf[0];
323 /* Make sure the first character is an `='. (Until we do this,
324 it might be a `+'.) */
325 buf[0] = '=';
326 /* Replace the constraint with the canonicalized string. */
327 *constraint_p = ggc_alloc_string (buf, c_len);
328 constraint = *constraint_p;
331 /* Loop through the constraint string. */
332 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
333 switch (*p)
335 case '+':
336 case '=':
337 error ("operand constraint contains incorrectly positioned "
338 "%<+%> or %<=%>");
339 return false;
341 case '%':
342 if (operand_num + 1 == ninputs + noutputs)
344 error ("%<%%%> constraint used with last operand");
345 return false;
347 break;
349 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
350 *allows_mem = true;
351 break;
353 case '?': case '!': case '*': case '&': case '#':
354 case 'E': case 'F': case 'G': case 'H':
355 case 's': case 'i': case 'n':
356 case 'I': case 'J': case 'K': case 'L': case 'M':
357 case 'N': case 'O': case 'P': case ',':
358 break;
360 case '0': case '1': case '2': case '3': case '4':
361 case '5': case '6': case '7': case '8': case '9':
362 case '[':
363 error ("matching constraint not valid in output operand");
364 return false;
366 case '<': case '>':
367 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
368 excepting those that expand_call created. So match memory
369 and hope. */
370 *allows_mem = true;
371 break;
373 case 'g': case 'X':
374 *allows_reg = true;
375 *allows_mem = true;
376 break;
378 case 'p': case 'r':
379 *allows_reg = true;
380 break;
382 default:
383 if (!ISALPHA (*p))
384 break;
385 if (REG_CLASS_FROM_CONSTRAINT (*p, p) != NO_REGS)
386 *allows_reg = true;
387 #ifdef EXTRA_CONSTRAINT_STR
388 else if (EXTRA_ADDRESS_CONSTRAINT (*p, p))
389 *allows_reg = true;
390 else if (EXTRA_MEMORY_CONSTRAINT (*p, p))
391 *allows_mem = true;
392 else
394 /* Otherwise we can't assume anything about the nature of
395 the constraint except that it isn't purely registers.
396 Treat it like "g" and hope for the best. */
397 *allows_reg = true;
398 *allows_mem = true;
400 #endif
401 break;
404 return true;
407 /* Similar, but for input constraints. */
409 bool
410 parse_input_constraint (const char **constraint_p, int input_num,
411 int ninputs, int noutputs, int ninout,
412 const char * const * constraints,
413 bool *allows_mem, bool *allows_reg)
415 const char *constraint = *constraint_p;
416 const char *orig_constraint = constraint;
417 size_t c_len = strlen (constraint);
418 size_t j;
419 bool saw_match = false;
421 /* Assume the constraint doesn't allow the use of either
422 a register or memory. */
423 *allows_mem = false;
424 *allows_reg = false;
426 /* Make sure constraint has neither `=', `+', nor '&'. */
428 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
429 switch (constraint[j])
431 case '+': case '=': case '&':
432 if (constraint == orig_constraint)
434 error ("input operand constraint contains %qc", constraint[j]);
435 return false;
437 break;
439 case '%':
440 if (constraint == orig_constraint
441 && input_num + 1 == ninputs - ninout)
443 error ("%<%%%> constraint used with last operand");
444 return false;
446 break;
448 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
449 *allows_mem = true;
450 break;
452 case '<': case '>':
453 case '?': case '!': case '*': case '#':
454 case 'E': case 'F': case 'G': case 'H':
455 case 's': case 'i': case 'n':
456 case 'I': case 'J': case 'K': case 'L': case 'M':
457 case 'N': case 'O': case 'P': case ',':
458 break;
460 /* Whether or not a numeric constraint allows a register is
461 decided by the matching constraint, and so there is no need
462 to do anything special with them. We must handle them in
463 the default case, so that we don't unnecessarily force
464 operands to memory. */
465 case '0': case '1': case '2': case '3': case '4':
466 case '5': case '6': case '7': case '8': case '9':
468 char *end;
469 unsigned long match;
471 saw_match = true;
473 match = strtoul (constraint + j, &end, 10);
474 if (match >= (unsigned long) noutputs)
476 error ("matching constraint references invalid operand number");
477 return false;
480 /* Try and find the real constraint for this dup. Only do this
481 if the matching constraint is the only alternative. */
482 if (*end == '\0'
483 && (j == 0 || (j == 1 && constraint[0] == '%')))
485 constraint = constraints[match];
486 *constraint_p = constraint;
487 c_len = strlen (constraint);
488 j = 0;
489 /* ??? At the end of the loop, we will skip the first part of
490 the matched constraint. This assumes not only that the
491 other constraint is an output constraint, but also that
492 the '=' or '+' come first. */
493 break;
495 else
496 j = end - constraint;
497 /* Anticipate increment at end of loop. */
498 j--;
500 /* Fall through. */
502 case 'p': case 'r':
503 *allows_reg = true;
504 break;
506 case 'g': case 'X':
507 *allows_reg = true;
508 *allows_mem = true;
509 break;
511 default:
512 if (! ISALPHA (constraint[j]))
514 error ("invalid punctuation %qc in constraint", constraint[j]);
515 return false;
517 if (REG_CLASS_FROM_CONSTRAINT (constraint[j], constraint + j)
518 != NO_REGS)
519 *allows_reg = true;
520 #ifdef EXTRA_CONSTRAINT_STR
521 else if (EXTRA_ADDRESS_CONSTRAINT (constraint[j], constraint + j))
522 *allows_reg = true;
523 else if (EXTRA_MEMORY_CONSTRAINT (constraint[j], constraint + j))
524 *allows_mem = true;
525 else
527 /* Otherwise we can't assume anything about the nature of
528 the constraint except that it isn't purely registers.
529 Treat it like "g" and hope for the best. */
530 *allows_reg = true;
531 *allows_mem = true;
533 #endif
534 break;
537 if (saw_match && !*allows_reg)
538 warning (0, "matching constraint does not allow a register");
540 return true;
543 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
544 can be an asm-declared register. Called via walk_tree. */
546 static tree
547 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
548 void *data)
550 tree decl = *declp;
551 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
553 if (TREE_CODE (decl) == VAR_DECL)
555 if (DECL_HARD_REGISTER (decl)
556 && REG_P (DECL_RTL (decl))
557 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
559 rtx reg = DECL_RTL (decl);
561 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
562 return decl;
564 walk_subtrees = 0;
566 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
567 walk_subtrees = 0;
568 return NULL_TREE;
571 /* If there is an overlap between *REGS and DECL, return the first overlap
572 found. */
573 tree
574 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
576 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
579 /* Check for overlap between registers marked in CLOBBERED_REGS and
580 anything inappropriate in T. Emit error and return the register
581 variable definition for error, NULL_TREE for ok. */
583 static bool
584 tree_conflicts_with_clobbers_p (tree t, HARD_REG_SET *clobbered_regs)
586 /* Conflicts between asm-declared register variables and the clobber
587 list are not allowed. */
588 tree overlap = tree_overlaps_hard_reg_set (t, clobbered_regs);
590 if (overlap)
592 error ("asm-specifier for variable %qE conflicts with asm clobber list",
593 DECL_NAME (overlap));
595 /* Reset registerness to stop multiple errors emitted for a single
596 variable. */
597 DECL_REGISTER (overlap) = 0;
598 return true;
601 return false;
604 /* Generate RTL for an asm statement with arguments.
605 STRING is the instruction template.
606 OUTPUTS is a list of output arguments (lvalues); INPUTS a list of inputs.
607 Each output or input has an expression in the TREE_VALUE and
608 a tree list in TREE_PURPOSE which in turn contains a constraint
609 name in TREE_VALUE (or NULL_TREE) and a constraint string
610 in TREE_PURPOSE.
611 CLOBBERS is a list of STRING_CST nodes each naming a hard register
612 that is clobbered by this insn.
614 Not all kinds of lvalue that may appear in OUTPUTS can be stored directly.
615 Some elements of OUTPUTS may be replaced with trees representing temporary
616 values. The caller should copy those temporary values to the originally
617 specified lvalues.
619 VOL nonzero means the insn is volatile; don't optimize it. */
621 static void
622 expand_asm_operands (tree string, tree outputs, tree inputs,
623 tree clobbers, tree labels, int vol, location_t locus)
625 rtvec argvec, constraintvec, labelvec;
626 rtx body;
627 int ninputs = list_length (inputs);
628 int noutputs = list_length (outputs);
629 int nlabels = list_length (labels);
630 int ninout;
631 int nclobbers;
632 HARD_REG_SET clobbered_regs;
633 int clobber_conflict_found = 0;
634 tree tail;
635 tree t;
636 int i;
637 /* Vector of RTX's of evaluated output operands. */
638 rtx *output_rtx = XALLOCAVEC (rtx, noutputs);
639 int *inout_opnum = XALLOCAVEC (int, noutputs);
640 rtx *real_output_rtx = XALLOCAVEC (rtx, noutputs);
641 enum machine_mode *inout_mode = XALLOCAVEC (enum machine_mode, noutputs);
642 const char **constraints = XALLOCAVEC (const char *, noutputs + ninputs);
643 int old_generating_concat_p = generating_concat_p;
645 /* An ASM with no outputs needs to be treated as volatile, for now. */
646 if (noutputs == 0)
647 vol = 1;
649 if (! check_operand_nalternatives (outputs, inputs))
650 return;
652 string = resolve_asm_operand_names (string, outputs, inputs, labels);
654 /* Collect constraints. */
655 i = 0;
656 for (t = outputs; t ; t = TREE_CHAIN (t), i++)
657 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
658 for (t = inputs; t ; t = TREE_CHAIN (t), i++)
659 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
661 /* Sometimes we wish to automatically clobber registers across an asm.
662 Case in point is when the i386 backend moved from cc0 to a hard reg --
663 maintaining source-level compatibility means automatically clobbering
664 the flags register. */
665 clobbers = targetm.md_asm_clobbers (outputs, inputs, clobbers);
667 /* Count the number of meaningful clobbered registers, ignoring what
668 we would ignore later. */
669 nclobbers = 0;
670 CLEAR_HARD_REG_SET (clobbered_regs);
671 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
673 const char *regname;
674 int nregs;
676 if (TREE_VALUE (tail) == error_mark_node)
677 return;
678 regname = TREE_STRING_POINTER (TREE_VALUE (tail));
680 i = decode_reg_name_and_count (regname, &nregs);
681 if (i == -4)
682 ++nclobbers;
683 else if (i == -2)
684 error ("unknown register name %qs in %<asm%>", regname);
686 /* Mark clobbered registers. */
687 if (i >= 0)
689 int reg;
691 for (reg = i; reg < i + nregs; reg++)
693 ++nclobbers;
695 /* Clobbering the PIC register is an error. */
696 if (reg == (int) PIC_OFFSET_TABLE_REGNUM)
698 error ("PIC register clobbered by %qs in %<asm%>", regname);
699 return;
702 SET_HARD_REG_BIT (clobbered_regs, reg);
707 /* First pass over inputs and outputs checks validity and sets
708 mark_addressable if needed. */
710 ninout = 0;
711 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
713 tree val = TREE_VALUE (tail);
714 tree type = TREE_TYPE (val);
715 const char *constraint;
716 bool is_inout;
717 bool allows_reg;
718 bool allows_mem;
720 /* If there's an erroneous arg, emit no insn. */
721 if (type == error_mark_node)
722 return;
724 /* Try to parse the output constraint. If that fails, there's
725 no point in going further. */
726 constraint = constraints[i];
727 if (!parse_output_constraint (&constraint, i, ninputs, noutputs,
728 &allows_mem, &allows_reg, &is_inout))
729 return;
731 if (! allows_reg
732 && (allows_mem
733 || is_inout
734 || (DECL_P (val)
735 && REG_P (DECL_RTL (val))
736 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type))))
737 mark_addressable (val);
739 if (is_inout)
740 ninout++;
743 ninputs += ninout;
744 if (ninputs + noutputs > MAX_RECOG_OPERANDS)
746 error ("more than %d operands in %<asm%>", MAX_RECOG_OPERANDS);
747 return;
750 for (i = 0, tail = inputs; tail; i++, tail = TREE_CHAIN (tail))
752 bool allows_reg, allows_mem;
753 const char *constraint;
755 /* If there's an erroneous arg, emit no insn, because the ASM_INPUT
756 would get VOIDmode and that could cause a crash in reload. */
757 if (TREE_TYPE (TREE_VALUE (tail)) == error_mark_node)
758 return;
760 constraint = constraints[i + noutputs];
761 if (! parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
762 constraints, &allows_mem, &allows_reg))
763 return;
765 if (! allows_reg && allows_mem)
766 mark_addressable (TREE_VALUE (tail));
769 /* Second pass evaluates arguments. */
771 /* Make sure stack is consistent for asm goto. */
772 if (nlabels > 0)
773 do_pending_stack_adjust ();
775 ninout = 0;
776 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
778 tree val = TREE_VALUE (tail);
779 tree type = TREE_TYPE (val);
780 bool is_inout;
781 bool allows_reg;
782 bool allows_mem;
783 rtx op;
784 bool ok;
786 ok = parse_output_constraint (&constraints[i], i, ninputs,
787 noutputs, &allows_mem, &allows_reg,
788 &is_inout);
789 gcc_assert (ok);
791 /* If an output operand is not a decl or indirect ref and our constraint
792 allows a register, make a temporary to act as an intermediate.
793 Make the asm insn write into that, then our caller will copy it to
794 the real output operand. Likewise for promoted variables. */
796 generating_concat_p = 0;
798 real_output_rtx[i] = NULL_RTX;
799 if ((TREE_CODE (val) == INDIRECT_REF
800 && allows_mem)
801 || (DECL_P (val)
802 && (allows_mem || REG_P (DECL_RTL (val)))
803 && ! (REG_P (DECL_RTL (val))
804 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type)))
805 || ! allows_reg
806 || is_inout)
808 op = expand_expr (val, NULL_RTX, VOIDmode, EXPAND_WRITE);
809 if (MEM_P (op))
810 op = validize_mem (op);
812 if (! allows_reg && !MEM_P (op))
813 error ("output number %d not directly addressable", i);
814 if ((! allows_mem && MEM_P (op))
815 || GET_CODE (op) == CONCAT)
817 real_output_rtx[i] = op;
818 op = gen_reg_rtx (GET_MODE (op));
819 if (is_inout)
820 emit_move_insn (op, real_output_rtx[i]);
823 else
825 op = assign_temp (type, 0, 1);
826 op = validize_mem (op);
827 if (!MEM_P (op) && TREE_CODE (TREE_VALUE (tail)) == SSA_NAME)
828 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (TREE_VALUE (tail)), op);
829 TREE_VALUE (tail) = make_tree (type, op);
831 output_rtx[i] = op;
833 generating_concat_p = old_generating_concat_p;
835 if (is_inout)
837 inout_mode[ninout] = TYPE_MODE (type);
838 inout_opnum[ninout++] = i;
841 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
842 clobber_conflict_found = 1;
845 /* Make vectors for the expression-rtx, constraint strings,
846 and named operands. */
848 argvec = rtvec_alloc (ninputs);
849 constraintvec = rtvec_alloc (ninputs);
850 labelvec = rtvec_alloc (nlabels);
852 body = gen_rtx_ASM_OPERANDS ((noutputs == 0 ? VOIDmode
853 : GET_MODE (output_rtx[0])),
854 ggc_strdup (TREE_STRING_POINTER (string)),
855 empty_string, 0, argvec, constraintvec,
856 labelvec, locus);
858 MEM_VOLATILE_P (body) = vol;
860 /* Eval the inputs and put them into ARGVEC.
861 Put their constraints into ASM_INPUTs and store in CONSTRAINTS. */
863 for (i = 0, tail = inputs; tail; tail = TREE_CHAIN (tail), ++i)
865 bool allows_reg, allows_mem;
866 const char *constraint;
867 tree val, type;
868 rtx op;
869 bool ok;
871 constraint = constraints[i + noutputs];
872 ok = parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
873 constraints, &allows_mem, &allows_reg);
874 gcc_assert (ok);
876 generating_concat_p = 0;
878 val = TREE_VALUE (tail);
879 type = TREE_TYPE (val);
880 /* EXPAND_INITIALIZER will not generate code for valid initializer
881 constants, but will still generate code for other types of operand.
882 This is the behavior we want for constant constraints. */
883 op = expand_expr (val, NULL_RTX, VOIDmode,
884 allows_reg ? EXPAND_NORMAL
885 : allows_mem ? EXPAND_MEMORY
886 : EXPAND_INITIALIZER);
888 /* Never pass a CONCAT to an ASM. */
889 if (GET_CODE (op) == CONCAT)
890 op = force_reg (GET_MODE (op), op);
891 else if (MEM_P (op))
892 op = validize_mem (op);
894 if (asm_operand_ok (op, constraint, NULL) <= 0)
896 if (allows_reg && TYPE_MODE (type) != BLKmode)
897 op = force_reg (TYPE_MODE (type), op);
898 else if (!allows_mem)
899 warning (0, "asm operand %d probably doesn%'t match constraints",
900 i + noutputs);
901 else if (MEM_P (op))
903 /* We won't recognize either volatile memory or memory
904 with a queued address as available a memory_operand
905 at this point. Ignore it: clearly this *is* a memory. */
907 else
908 gcc_unreachable ();
911 generating_concat_p = old_generating_concat_p;
912 ASM_OPERANDS_INPUT (body, i) = op;
914 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, i)
915 = gen_rtx_ASM_INPUT (TYPE_MODE (type),
916 ggc_strdup (constraints[i + noutputs]));
918 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
919 clobber_conflict_found = 1;
922 /* Protect all the operands from the queue now that they have all been
923 evaluated. */
925 generating_concat_p = 0;
927 /* For in-out operands, copy output rtx to input rtx. */
928 for (i = 0; i < ninout; i++)
930 int j = inout_opnum[i];
931 char buffer[16];
933 ASM_OPERANDS_INPUT (body, ninputs - ninout + i)
934 = output_rtx[j];
936 sprintf (buffer, "%d", j);
937 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, ninputs - ninout + i)
938 = gen_rtx_ASM_INPUT (inout_mode[i], ggc_strdup (buffer));
941 /* Copy labels to the vector. */
942 for (i = 0, tail = labels; i < nlabels; ++i, tail = TREE_CHAIN (tail))
943 ASM_OPERANDS_LABEL (body, i)
944 = gen_rtx_LABEL_REF (Pmode, label_rtx (TREE_VALUE (tail)));
946 generating_concat_p = old_generating_concat_p;
948 /* Now, for each output, construct an rtx
949 (set OUTPUT (asm_operands INSN OUTPUTCONSTRAINT OUTPUTNUMBER
950 ARGVEC CONSTRAINTS OPNAMES))
951 If there is more than one, put them inside a PARALLEL. */
953 if (nlabels > 0 && nclobbers == 0)
955 gcc_assert (noutputs == 0);
956 emit_jump_insn (body);
958 else if (noutputs == 0 && nclobbers == 0)
960 /* No output operands: put in a raw ASM_OPERANDS rtx. */
961 emit_insn (body);
963 else if (noutputs == 1 && nclobbers == 0)
965 ASM_OPERANDS_OUTPUT_CONSTRAINT (body) = ggc_strdup (constraints[0]);
966 emit_insn (gen_rtx_SET (VOIDmode, output_rtx[0], body));
968 else
970 rtx obody = body;
971 int num = noutputs;
973 if (num == 0)
974 num = 1;
976 body = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num + nclobbers));
978 /* For each output operand, store a SET. */
979 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
981 XVECEXP (body, 0, i)
982 = gen_rtx_SET (VOIDmode,
983 output_rtx[i],
984 gen_rtx_ASM_OPERANDS
985 (GET_MODE (output_rtx[i]),
986 ggc_strdup (TREE_STRING_POINTER (string)),
987 ggc_strdup (constraints[i]),
988 i, argvec, constraintvec, labelvec, locus));
990 MEM_VOLATILE_P (SET_SRC (XVECEXP (body, 0, i))) = vol;
993 /* If there are no outputs (but there are some clobbers)
994 store the bare ASM_OPERANDS into the PARALLEL. */
996 if (i == 0)
997 XVECEXP (body, 0, i++) = obody;
999 /* Store (clobber REG) for each clobbered register specified. */
1001 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
1003 const char *regname = TREE_STRING_POINTER (TREE_VALUE (tail));
1004 int reg, nregs;
1005 int j = decode_reg_name_and_count (regname, &nregs);
1006 rtx clobbered_reg;
1008 if (j < 0)
1010 if (j == -3) /* `cc', which is not a register */
1011 continue;
1013 if (j == -4) /* `memory', don't cache memory across asm */
1015 XVECEXP (body, 0, i++)
1016 = gen_rtx_CLOBBER (VOIDmode,
1017 gen_rtx_MEM
1018 (BLKmode,
1019 gen_rtx_SCRATCH (VOIDmode)));
1020 continue;
1023 /* Ignore unknown register, error already signaled. */
1024 continue;
1027 for (reg = j; reg < j + nregs; reg++)
1029 /* Use QImode since that's guaranteed to clobber just
1030 * one reg. */
1031 clobbered_reg = gen_rtx_REG (QImode, reg);
1033 /* Do sanity check for overlap between clobbers and
1034 respectively input and outputs that hasn't been
1035 handled. Such overlap should have been detected and
1036 reported above. */
1037 if (!clobber_conflict_found)
1039 int opno;
1041 /* We test the old body (obody) contents to avoid
1042 tripping over the under-construction body. */
1043 for (opno = 0; opno < noutputs; opno++)
1044 if (reg_overlap_mentioned_p (clobbered_reg,
1045 output_rtx[opno]))
1046 internal_error
1047 ("asm clobber conflict with output operand");
1049 for (opno = 0; opno < ninputs - ninout; opno++)
1050 if (reg_overlap_mentioned_p (clobbered_reg,
1051 ASM_OPERANDS_INPUT (obody,
1052 opno)))
1053 internal_error
1054 ("asm clobber conflict with input operand");
1057 XVECEXP (body, 0, i++)
1058 = gen_rtx_CLOBBER (VOIDmode, clobbered_reg);
1062 if (nlabels > 0)
1063 emit_jump_insn (body);
1064 else
1065 emit_insn (body);
1068 /* For any outputs that needed reloading into registers, spill them
1069 back to where they belong. */
1070 for (i = 0; i < noutputs; ++i)
1071 if (real_output_rtx[i])
1072 emit_move_insn (real_output_rtx[i], output_rtx[i]);
1074 crtl->has_asm_statement = 1;
1075 free_temp_slots ();
1078 void
1079 expand_asm_stmt (gimple stmt)
1081 int noutputs;
1082 tree outputs, tail, t;
1083 tree *o;
1084 size_t i, n;
1085 const char *s;
1086 tree str, out, in, cl, labels;
1087 location_t locus = gimple_location (stmt);
1089 /* Meh... convert the gimple asm operands into real tree lists.
1090 Eventually we should make all routines work on the vectors instead
1091 of relying on TREE_CHAIN. */
1092 out = NULL_TREE;
1093 n = gimple_asm_noutputs (stmt);
1094 if (n > 0)
1096 t = out = gimple_asm_output_op (stmt, 0);
1097 for (i = 1; i < n; i++)
1098 t = TREE_CHAIN (t) = gimple_asm_output_op (stmt, i);
1101 in = NULL_TREE;
1102 n = gimple_asm_ninputs (stmt);
1103 if (n > 0)
1105 t = in = gimple_asm_input_op (stmt, 0);
1106 for (i = 1; i < n; i++)
1107 t = TREE_CHAIN (t) = gimple_asm_input_op (stmt, i);
1110 cl = NULL_TREE;
1111 n = gimple_asm_nclobbers (stmt);
1112 if (n > 0)
1114 t = cl = gimple_asm_clobber_op (stmt, 0);
1115 for (i = 1; i < n; i++)
1116 t = TREE_CHAIN (t) = gimple_asm_clobber_op (stmt, i);
1119 labels = NULL_TREE;
1120 n = gimple_asm_nlabels (stmt);
1121 if (n > 0)
1123 t = labels = gimple_asm_label_op (stmt, 0);
1124 for (i = 1; i < n; i++)
1125 t = TREE_CHAIN (t) = gimple_asm_label_op (stmt, i);
1128 s = gimple_asm_string (stmt);
1129 str = build_string (strlen (s), s);
1131 if (gimple_asm_input_p (stmt))
1133 expand_asm_loc (str, gimple_asm_volatile_p (stmt), locus);
1134 return;
1137 outputs = out;
1138 noutputs = gimple_asm_noutputs (stmt);
1139 /* o[I] is the place that output number I should be written. */
1140 o = (tree *) alloca (noutputs * sizeof (tree));
1142 /* Record the contents of OUTPUTS before it is modified. */
1143 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1144 o[i] = TREE_VALUE (tail);
1146 /* Generate the ASM_OPERANDS insn; store into the TREE_VALUEs of
1147 OUTPUTS some trees for where the values were actually stored. */
1148 expand_asm_operands (str, outputs, in, cl, labels,
1149 gimple_asm_volatile_p (stmt), locus);
1151 /* Copy all the intermediate outputs into the specified outputs. */
1152 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1154 if (o[i] != TREE_VALUE (tail))
1156 expand_assignment (o[i], TREE_VALUE (tail), false);
1157 free_temp_slots ();
1159 /* Restore the original value so that it's correct the next
1160 time we expand this function. */
1161 TREE_VALUE (tail) = o[i];
1166 /* A subroutine of expand_asm_operands. Check that all operands have
1167 the same number of alternatives. Return true if so. */
1169 static bool
1170 check_operand_nalternatives (tree outputs, tree inputs)
1172 if (outputs || inputs)
1174 tree tmp = TREE_PURPOSE (outputs ? outputs : inputs);
1175 int nalternatives
1176 = n_occurrences (',', TREE_STRING_POINTER (TREE_VALUE (tmp)));
1177 tree next = inputs;
1179 if (nalternatives + 1 > MAX_RECOG_ALTERNATIVES)
1181 error ("too many alternatives in %<asm%>");
1182 return false;
1185 tmp = outputs;
1186 while (tmp)
1188 const char *constraint
1189 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tmp)));
1191 if (n_occurrences (',', constraint) != nalternatives)
1193 error ("operand constraints for %<asm%> differ "
1194 "in number of alternatives");
1195 return false;
1198 if (TREE_CHAIN (tmp))
1199 tmp = TREE_CHAIN (tmp);
1200 else
1201 tmp = next, next = 0;
1205 return true;
1208 /* A subroutine of expand_asm_operands. Check that all operand names
1209 are unique. Return true if so. We rely on the fact that these names
1210 are identifiers, and so have been canonicalized by get_identifier,
1211 so all we need are pointer comparisons. */
1213 static bool
1214 check_unique_operand_names (tree outputs, tree inputs, tree labels)
1216 tree i, j, i_name = NULL_TREE;
1218 for (i = outputs; i ; i = TREE_CHAIN (i))
1220 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1221 if (! i_name)
1222 continue;
1224 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1225 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1226 goto failure;
1229 for (i = inputs; i ; i = TREE_CHAIN (i))
1231 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1232 if (! i_name)
1233 continue;
1235 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1236 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1237 goto failure;
1238 for (j = outputs; j ; j = TREE_CHAIN (j))
1239 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1240 goto failure;
1243 for (i = labels; i ; i = TREE_CHAIN (i))
1245 i_name = TREE_PURPOSE (i);
1246 if (! i_name)
1247 continue;
1249 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1250 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
1251 goto failure;
1252 for (j = inputs; j ; j = TREE_CHAIN (j))
1253 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1254 goto failure;
1257 return true;
1259 failure:
1260 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
1261 return false;
1264 /* A subroutine of expand_asm_operands. Resolve the names of the operands
1265 in *POUTPUTS and *PINPUTS to numbers, and replace the name expansions in
1266 STRING and in the constraints to those numbers. */
1268 tree
1269 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
1271 char *buffer;
1272 char *p;
1273 const char *c;
1274 tree t;
1276 check_unique_operand_names (outputs, inputs, labels);
1278 /* Substitute [<name>] in input constraint strings. There should be no
1279 named operands in output constraints. */
1280 for (t = inputs; t ; t = TREE_CHAIN (t))
1282 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1283 if (strchr (c, '[') != NULL)
1285 p = buffer = xstrdup (c);
1286 while ((p = strchr (p, '[')) != NULL)
1287 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
1288 TREE_VALUE (TREE_PURPOSE (t))
1289 = build_string (strlen (buffer), buffer);
1290 free (buffer);
1294 /* Now check for any needed substitutions in the template. */
1295 c = TREE_STRING_POINTER (string);
1296 while ((c = strchr (c, '%')) != NULL)
1298 if (c[1] == '[')
1299 break;
1300 else if (ISALPHA (c[1]) && c[2] == '[')
1301 break;
1302 else
1304 c += 1 + (c[1] == '%');
1305 continue;
1309 if (c)
1311 /* OK, we need to make a copy so we can perform the substitutions.
1312 Assume that we will not need extra space--we get to remove '['
1313 and ']', which means we cannot have a problem until we have more
1314 than 999 operands. */
1315 buffer = xstrdup (TREE_STRING_POINTER (string));
1316 p = buffer + (c - TREE_STRING_POINTER (string));
1318 while ((p = strchr (p, '%')) != NULL)
1320 if (p[1] == '[')
1321 p += 1;
1322 else if (ISALPHA (p[1]) && p[2] == '[')
1323 p += 2;
1324 else
1326 p += 1 + (p[1] == '%');
1327 continue;
1330 p = resolve_operand_name_1 (p, outputs, inputs, labels);
1333 string = build_string (strlen (buffer), buffer);
1334 free (buffer);
1337 return string;
1340 /* A subroutine of resolve_operand_names. P points to the '[' for a
1341 potential named operand of the form [<name>]. In place, replace
1342 the name and brackets with a number. Return a pointer to the
1343 balance of the string after substitution. */
1345 static char *
1346 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
1348 char *q;
1349 int op;
1350 tree t;
1352 /* Collect the operand name. */
1353 q = strchr (++p, ']');
1354 if (!q)
1356 error ("missing close brace for named operand");
1357 return strchr (p, '\0');
1359 *q = '\0';
1361 /* Resolve the name to a number. */
1362 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
1364 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1365 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1366 goto found;
1368 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
1370 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1371 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1372 goto found;
1374 for (t = labels; t ; t = TREE_CHAIN (t), op++)
1376 tree name = TREE_PURPOSE (t);
1377 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1378 goto found;
1381 error ("undefined named operand %qs", identifier_to_locale (p));
1382 op = 0;
1384 found:
1385 /* Replace the name with the number. Unfortunately, not all libraries
1386 get the return value of sprintf correct, so search for the end of the
1387 generated string by hand. */
1388 sprintf (--p, "%d", op);
1389 p = strchr (p, '\0');
1391 /* Verify the no extra buffer space assumption. */
1392 gcc_assert (p <= q);
1394 /* Shift the rest of the buffer down to fill the gap. */
1395 memmove (p, q + 1, strlen (q + 1) + 1);
1397 return p;
1400 /* Generate RTL to return from the current function, with no value.
1401 (That is, we do not do anything about returning any value.) */
1403 void
1404 expand_null_return (void)
1406 /* If this function was declared to return a value, but we
1407 didn't, clobber the return registers so that they are not
1408 propagated live to the rest of the function. */
1409 clobber_return_register ();
1411 expand_null_return_1 ();
1414 /* Generate RTL to return directly from the current function.
1415 (That is, we bypass any return value.) */
1417 void
1418 expand_naked_return (void)
1420 rtx end_label;
1422 clear_pending_stack_adjust ();
1423 do_pending_stack_adjust ();
1425 end_label = naked_return_label;
1426 if (end_label == 0)
1427 end_label = naked_return_label = gen_label_rtx ();
1429 emit_jump (end_label);
1432 /* Generate RTL to return from the current function, with value VAL. */
1434 static void
1435 expand_value_return (rtx val)
1437 /* Copy the value to the return location unless it's already there. */
1439 tree decl = DECL_RESULT (current_function_decl);
1440 rtx return_reg = DECL_RTL (decl);
1441 if (return_reg != val)
1443 tree funtype = TREE_TYPE (current_function_decl);
1444 tree type = TREE_TYPE (decl);
1445 int unsignedp = TYPE_UNSIGNED (type);
1446 enum machine_mode old_mode = DECL_MODE (decl);
1447 enum machine_mode mode;
1448 if (DECL_BY_REFERENCE (decl))
1449 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 2);
1450 else
1451 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 1);
1453 if (mode != old_mode)
1454 val = convert_modes (mode, old_mode, val, unsignedp);
1456 if (GET_CODE (return_reg) == PARALLEL)
1457 emit_group_load (return_reg, val, type, int_size_in_bytes (type));
1458 else
1459 emit_move_insn (return_reg, val);
1462 expand_null_return_1 ();
1465 /* Output a return with no value. */
1467 static void
1468 expand_null_return_1 (void)
1470 clear_pending_stack_adjust ();
1471 do_pending_stack_adjust ();
1472 emit_jump (return_label);
1475 /* Generate RTL to evaluate the expression RETVAL and return it
1476 from the current function. */
1478 void
1479 expand_return (tree retval)
1481 rtx result_rtl;
1482 rtx val = 0;
1483 tree retval_rhs;
1485 /* If function wants no value, give it none. */
1486 if (TREE_CODE (TREE_TYPE (TREE_TYPE (current_function_decl))) == VOID_TYPE)
1488 expand_normal (retval);
1489 expand_null_return ();
1490 return;
1493 if (retval == error_mark_node)
1495 /* Treat this like a return of no value from a function that
1496 returns a value. */
1497 expand_null_return ();
1498 return;
1500 else if ((TREE_CODE (retval) == MODIFY_EXPR
1501 || TREE_CODE (retval) == INIT_EXPR)
1502 && TREE_CODE (TREE_OPERAND (retval, 0)) == RESULT_DECL)
1503 retval_rhs = TREE_OPERAND (retval, 1);
1504 else
1505 retval_rhs = retval;
1507 result_rtl = DECL_RTL (DECL_RESULT (current_function_decl));
1509 /* If we are returning the RESULT_DECL, then the value has already
1510 been stored into it, so we don't have to do anything special. */
1511 if (TREE_CODE (retval_rhs) == RESULT_DECL)
1512 expand_value_return (result_rtl);
1514 /* If the result is an aggregate that is being returned in one (or more)
1515 registers, load the registers here. */
1517 else if (retval_rhs != 0
1518 && TYPE_MODE (TREE_TYPE (retval_rhs)) == BLKmode
1519 && REG_P (result_rtl))
1521 val = copy_blkmode_to_reg (GET_MODE (result_rtl), retval_rhs);
1522 if (val)
1524 /* Use the mode of the result value on the return register. */
1525 PUT_MODE (result_rtl, GET_MODE (val));
1526 expand_value_return (val);
1528 else
1529 expand_null_return ();
1531 else if (retval_rhs != 0
1532 && !VOID_TYPE_P (TREE_TYPE (retval_rhs))
1533 && (REG_P (result_rtl)
1534 || (GET_CODE (result_rtl) == PARALLEL)))
1536 /* Calculate the return value into a temporary (usually a pseudo
1537 reg). */
1538 tree ot = TREE_TYPE (DECL_RESULT (current_function_decl));
1539 tree nt = build_qualified_type (ot, TYPE_QUALS (ot) | TYPE_QUAL_CONST);
1541 val = assign_temp (nt, 0, 1);
1542 val = expand_expr (retval_rhs, val, GET_MODE (val), EXPAND_NORMAL);
1543 val = force_not_mem (val);
1544 /* Return the calculated value. */
1545 expand_value_return (val);
1547 else
1549 /* No hard reg used; calculate value into hard return reg. */
1550 expand_expr (retval, const0_rtx, VOIDmode, EXPAND_NORMAL);
1551 expand_value_return (result_rtl);
1555 /* Emit code to restore vital registers at the beginning of a nonlocal goto
1556 handler. */
1557 static void
1558 expand_nl_goto_receiver (void)
1560 rtx chain;
1562 /* Clobber the FP when we get here, so we have to make sure it's
1563 marked as used by this function. */
1564 emit_use (hard_frame_pointer_rtx);
1566 /* Mark the static chain as clobbered here so life information
1567 doesn't get messed up for it. */
1568 chain = targetm.calls.static_chain (current_function_decl, true);
1569 if (chain && REG_P (chain))
1570 emit_clobber (chain);
1572 #ifdef HAVE_nonlocal_goto
1573 if (! HAVE_nonlocal_goto)
1574 #endif
1575 /* First adjust our frame pointer to its actual value. It was
1576 previously set to the start of the virtual area corresponding to
1577 the stacked variables when we branched here and now needs to be
1578 adjusted to the actual hardware fp value.
1580 Assignments are to virtual registers are converted by
1581 instantiate_virtual_regs into the corresponding assignment
1582 to the underlying register (fp in this case) that makes
1583 the original assignment true.
1584 So the following insn will actually be
1585 decrementing fp by STARTING_FRAME_OFFSET. */
1586 emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
1588 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
1589 if (fixed_regs[ARG_POINTER_REGNUM])
1591 #ifdef ELIMINABLE_REGS
1592 /* If the argument pointer can be eliminated in favor of the
1593 frame pointer, we don't need to restore it. We assume here
1594 that if such an elimination is present, it can always be used.
1595 This is the case on all known machines; if we don't make this
1596 assumption, we do unnecessary saving on many machines. */
1597 static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
1598 size_t i;
1600 for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
1601 if (elim_regs[i].from == ARG_POINTER_REGNUM
1602 && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
1603 break;
1605 if (i == ARRAY_SIZE (elim_regs))
1606 #endif
1608 /* Now restore our arg pointer from the address at which it
1609 was saved in our stack frame. */
1610 emit_move_insn (crtl->args.internal_arg_pointer,
1611 copy_to_reg (get_arg_pointer_save_area ()));
1614 #endif
1616 #ifdef HAVE_nonlocal_goto_receiver
1617 if (HAVE_nonlocal_goto_receiver)
1618 emit_insn (gen_nonlocal_goto_receiver ());
1619 #endif
1621 /* We must not allow the code we just generated to be reordered by
1622 scheduling. Specifically, the update of the frame pointer must
1623 happen immediately, not later. */
1624 emit_insn (gen_blockage ());
1627 /* Emit code to save the current value of stack. */
1629 expand_stack_save (void)
1631 rtx ret = NULL_RTX;
1633 do_pending_stack_adjust ();
1634 emit_stack_save (SAVE_BLOCK, &ret);
1635 return ret;
1638 /* Emit code to restore the current value of stack. */
1639 void
1640 expand_stack_restore (tree var)
1642 rtx prev, sa = expand_normal (var);
1644 sa = convert_memory_address (Pmode, sa);
1646 prev = get_last_insn ();
1647 emit_stack_restore (SAVE_BLOCK, sa);
1648 fixup_args_size_notes (prev, get_last_insn (), 0);
1651 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. */
1652 static void
1653 do_jump_if_equal (enum machine_mode mode, rtx op0, rtx op1, rtx label,
1654 int unsignedp)
1656 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
1657 NULL_RTX, NULL_RTX, label, -1);
1660 /* Do the insertion of a case label into case_list. The labels are
1661 fed to us in descending order from the sorted vector of case labels used
1662 in the tree part of the middle end. So the list we construct is
1663 sorted in ascending order. */
1665 static struct case_node *
1666 add_case_node (struct case_node *head, tree low, tree high,
1667 tree label, alloc_pool case_node_pool)
1669 struct case_node *r;
1671 gcc_checking_assert (low);
1672 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
1674 /* Add this label to the chain. */
1675 r = (struct case_node *) pool_alloc (case_node_pool);
1676 r->low = low;
1677 r->high = high;
1678 r->code_label = label;
1679 r->parent = r->left = NULL;
1680 r->right = head;
1681 return r;
1684 /* Dump ROOT, a list or tree of case nodes, to file. */
1686 static void
1687 dump_case_nodes (FILE *f, struct case_node *root,
1688 int indent_step, int indent_level)
1690 HOST_WIDE_INT low, high;
1692 if (root == 0)
1693 return;
1694 indent_level++;
1696 dump_case_nodes (f, root->left, indent_step, indent_level);
1698 low = tree_low_cst (root->low, 0);
1699 high = tree_low_cst (root->high, 0);
1701 fputs (";; ", f);
1702 if (high == low)
1703 fprintf(f, "%*s" HOST_WIDE_INT_PRINT_DEC,
1704 indent_step * indent_level, "", low);
1705 else
1706 fprintf(f, "%*s" HOST_WIDE_INT_PRINT_DEC " ... " HOST_WIDE_INT_PRINT_DEC,
1707 indent_step * indent_level, "", low, high);
1708 fputs ("\n", f);
1710 dump_case_nodes (f, root->right, indent_step, indent_level);
1713 #ifndef HAVE_casesi
1714 #define HAVE_casesi 0
1715 #endif
1717 #ifndef HAVE_tablejump
1718 #define HAVE_tablejump 0
1719 #endif
1721 /* Return the smallest number of different values for which it is best to use a
1722 jump-table instead of a tree of conditional branches. */
1724 static unsigned int
1725 case_values_threshold (void)
1727 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
1729 if (threshold == 0)
1730 threshold = targetm.case_values_threshold ();
1732 return threshold;
1735 /* Return true if a switch should be expanded as a decision tree.
1736 RANGE is the difference between highest and lowest case.
1737 UNIQ is number of unique case node targets, not counting the default case.
1738 COUNT is the number of comparisons needed, not counting the default case. */
1740 static bool
1741 expand_switch_as_decision_tree_p (tree range,
1742 unsigned int uniq ATTRIBUTE_UNUSED,
1743 unsigned int count)
1745 int max_ratio;
1747 /* If neither casesi or tablejump is available, or flag_jump_tables
1748 over-ruled us, we really have no choice. */
1749 if (!HAVE_casesi && !HAVE_tablejump)
1750 return true;
1751 if (!flag_jump_tables)
1752 return true;
1754 /* If the switch is relatively small such that the cost of one
1755 indirect jump on the target are higher than the cost of a
1756 decision tree, go with the decision tree.
1758 If range of values is much bigger than number of values,
1759 or if it is too large to represent in a HOST_WIDE_INT,
1760 make a sequence of conditional branches instead of a dispatch.
1762 The definition of "much bigger" depends on whether we are
1763 optimizing for size or for speed. If the former, the maximum
1764 ratio range/count = 3, because this was found to be the optimal
1765 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
1766 10 is much older, and was probably selected after an extensive
1767 benchmarking investigation on numerous platforms. Or maybe it
1768 just made sense to someone at some point in the history of GCC,
1769 who knows... */
1770 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
1771 if (count < case_values_threshold ()
1772 || ! host_integerp (range, /*pos=*/1)
1773 || compare_tree_int (range, max_ratio * count) > 0)
1774 return true;
1776 return false;
1779 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1780 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1782 We generate a binary decision tree to select the appropriate target
1783 code. This is done as follows:
1785 If the index is a short or char that we do not have
1786 an insn to handle comparisons directly, convert it to
1787 a full integer now, rather than letting each comparison
1788 generate the conversion.
1790 Load the index into a register.
1792 The list of cases is rearranged into a binary tree,
1793 nearly optimal assuming equal probability for each case.
1795 The tree is transformed into RTL, eliminating redundant
1796 test conditions at the same time.
1798 If program flow could reach the end of the decision tree
1799 an unconditional jump to the default code is emitted.
1801 The above process is unaware of the CFG. The caller has to fix up
1802 the CFG itself. This is done in cfgexpand.c. */
1804 static void
1805 emit_case_decision_tree (tree index_expr, tree index_type,
1806 struct case_node *case_list, rtx default_label)
1808 rtx index = expand_normal (index_expr);
1810 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
1811 && ! have_insn_for (COMPARE, GET_MODE (index)))
1813 int unsignedp = TYPE_UNSIGNED (index_type);
1814 enum machine_mode wider_mode;
1815 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
1816 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
1817 if (have_insn_for (COMPARE, wider_mode))
1819 index = convert_to_mode (wider_mode, index, unsignedp);
1820 break;
1824 do_pending_stack_adjust ();
1826 if (MEM_P (index))
1828 index = copy_to_reg (index);
1829 if (TREE_CODE (index_expr) == SSA_NAME)
1830 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
1833 balance_case_nodes (&case_list, NULL);
1835 if (dump_file && (dump_flags & TDF_DETAILS))
1837 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1838 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1839 dump_case_nodes (dump_file, case_list, indent_step, 0);
1842 emit_case_nodes (index, case_list, default_label, index_type);
1843 if (default_label)
1844 emit_jump (default_label);
1847 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
1848 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1849 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
1850 labels in CASE_LIST.
1852 First, a jump insn is emitted. First we try "casesi". If that
1853 fails, try "tablejump". A target *must* have one of them (or both).
1855 Then, a table with the target labels is emitted.
1857 The process is unaware of the CFG. The caller has to fix up
1858 the CFG itself. This is done in cfgexpand.c. */
1860 static void
1861 emit_case_dispatch_table (tree index_expr, tree index_type,
1862 struct case_node *case_list, rtx default_label,
1863 tree minval, tree maxval, tree range)
1865 int i, ncases;
1866 struct case_node *n;
1867 rtx *labelvec;
1868 rtx fallback_label = label_rtx (case_list->code_label);
1869 rtx table_label = gen_label_rtx ();
1871 if (! try_casesi (index_type, index_expr, minval, range,
1872 table_label, default_label, fallback_label))
1874 bool ok;
1876 /* Index jumptables from zero for suitable values of minval to avoid
1877 a subtraction. For the rationale see:
1878 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
1879 if (optimize_insn_for_speed_p ()
1880 && compare_tree_int (minval, 0) > 0
1881 && compare_tree_int (minval, 3) < 0)
1883 minval = build_int_cst (index_type, 0);
1884 range = maxval;
1887 ok = try_tablejump (index_type, index_expr, minval, range,
1888 table_label, default_label);
1889 gcc_assert (ok);
1892 /* Get table of labels to jump to, in order of case index. */
1894 ncases = tree_low_cst (range, 0) + 1;
1895 labelvec = XALLOCAVEC (rtx, ncases);
1896 memset (labelvec, 0, ncases * sizeof (rtx));
1898 for (n = case_list; n; n = n->right)
1900 /* Compute the low and high bounds relative to the minimum
1901 value since that should fit in a HOST_WIDE_INT while the
1902 actual values may not. */
1903 HOST_WIDE_INT i_low
1904 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1905 n->low, minval), 1);
1906 HOST_WIDE_INT i_high
1907 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1908 n->high, minval), 1);
1909 HOST_WIDE_INT i;
1911 for (i = i_low; i <= i_high; i ++)
1912 labelvec[i]
1913 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1916 /* Fill in the gaps with the default. We may have gaps at
1917 the beginning if we tried to avoid the minval subtraction,
1918 so substitute some label even if the default label was
1919 deemed unreachable. */
1920 if (!default_label)
1921 default_label = fallback_label;
1922 for (i = 0; i < ncases; i++)
1923 if (labelvec[i] == 0)
1924 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1926 /* Output the table. */
1927 emit_label (table_label);
1929 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1930 emit_jump_insn (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1931 gen_rtx_LABEL_REF (Pmode, table_label),
1932 gen_rtvec_v (ncases, labelvec),
1933 const0_rtx, const0_rtx));
1934 else
1935 emit_jump_insn (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1936 gen_rtvec_v (ncases, labelvec)));
1938 /* Record no drop-through after the table. */
1939 emit_barrier ();
1942 /* Terminate a case (Pascal/Ada) or switch (C) statement
1943 in which ORIG_INDEX is the expression to be tested.
1944 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
1945 type as given in the source before any compiler conversions.
1946 Generate the code to test it and jump to the right place. */
1948 void
1949 expand_case (gimple stmt)
1951 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
1952 rtx default_label = NULL_RTX;
1953 unsigned int count, uniq;
1954 int i;
1955 int ncases = gimple_switch_num_labels (stmt);
1956 tree index_expr = gimple_switch_index (stmt);
1957 tree index_type = TREE_TYPE (index_expr);
1958 tree elt;
1960 /* A list of case labels; it is first built as a list and it may then
1961 be rearranged into a nearly balanced binary tree. */
1962 struct case_node *case_list = 0;
1964 /* A pool for case nodes. */
1965 alloc_pool case_node_pool;
1967 /* An ERROR_MARK occurs for various reasons including invalid data type.
1968 ??? Can this still happen, with GIMPLE and all? */
1969 if (index_type == error_mark_node)
1970 return;
1972 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
1973 expressions being INTEGER_CST. */
1974 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
1976 case_node_pool = create_alloc_pool ("struct case_node pool",
1977 sizeof (struct case_node),
1978 100);
1980 do_pending_stack_adjust ();
1982 /* Find the default case target label. */
1983 default_label = label_rtx (CASE_LABEL (gimple_switch_default_label (stmt)));
1985 /* Get upper and lower bounds of case values. */
1986 elt = gimple_switch_label (stmt, 1);
1987 minval = fold_convert (index_type, CASE_LOW (elt));
1988 elt = gimple_switch_label (stmt, ncases - 1);
1989 if (CASE_HIGH (elt))
1990 maxval = fold_convert (index_type, CASE_HIGH (elt));
1991 else
1992 maxval = fold_convert (index_type, CASE_LOW (elt));
1994 /* Compute span of values. */
1995 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
1997 /* Listify the labels queue and gather some numbers to decide
1998 how to expand this switch(). */
1999 uniq = 0;
2000 count = 0;
2001 struct pointer_set_t *seen_labels = pointer_set_create ();
2002 for (i = gimple_switch_num_labels (stmt) - 1; i >= 1; --i)
2004 elt = gimple_switch_label (stmt, i);
2005 tree low = CASE_LOW (elt);
2006 gcc_assert (low);
2007 tree high = CASE_HIGH (elt);
2008 gcc_assert (! high || tree_int_cst_lt (low, high));
2009 tree lab = CASE_LABEL (elt);
2011 /* Count the elements.
2012 A range counts double, since it requires two compares. */
2013 count++;
2014 if (high)
2015 count++;
2017 /* If we have not seen this label yet, then increase the
2018 number of unique case node targets seen. */
2019 if (!pointer_set_insert (seen_labels, lab))
2020 uniq++;
2022 /* The bounds on the case range, LOW and HIGH, have to be converted
2023 to case's index type TYPE. Note that the original type of the
2024 case index in the source code is usually "lost" during
2025 gimplification due to type promotion, but the case labels retain the
2026 original type. Make sure to drop overflow flags. */
2027 low = fold_convert (index_type, low);
2028 if (TREE_OVERFLOW (low))
2029 low = build_int_cst_wide (index_type,
2030 TREE_INT_CST_LOW (low),
2031 TREE_INT_CST_HIGH (low));
2033 /* The canonical from of a case label in GIMPLE is that a simple case
2034 has an empty CASE_HIGH. For the casesi and tablejump expanders,
2035 the back ends want simple cases to have high == low. */
2036 if (! high)
2037 high = low;
2038 high = fold_convert (index_type, high);
2039 if (TREE_OVERFLOW (high))
2040 high = build_int_cst_wide (index_type,
2041 TREE_INT_CST_LOW (high),
2042 TREE_INT_CST_HIGH (high));
2044 case_list = add_case_node (case_list, low, high, lab,
2045 case_node_pool);
2047 pointer_set_destroy (seen_labels);
2049 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
2050 destination, such as one with a default case only.
2051 It also removes cases that are out of range for the switch
2052 type, so we should never get a zero here. */
2053 gcc_assert (count > 0);
2055 rtx before_case = get_last_insn ();
2057 /* Decide how to expand this switch.
2058 The two options at this point are a dispatch table (casesi or
2059 tablejump) or a decision tree. */
2061 if (expand_switch_as_decision_tree_p (range, uniq, count))
2062 emit_case_decision_tree (index_expr, index_type,
2063 case_list, default_label);
2064 else
2065 emit_case_dispatch_table (index_expr, index_type,
2066 case_list, default_label,
2067 minval, maxval, range);
2069 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2071 free_temp_slots ();
2072 free_alloc_pool (case_node_pool);
2075 /* Expand the dispatch to a short decrement chain if there are few cases
2076 to dispatch to. Likewise if neither casesi nor tablejump is available,
2077 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
2078 tablejump. The index mode is always the mode of integer_type_node.
2079 Trap if no case matches the index.
2081 DISPATCH_INDEX is the index expression to switch on. It should be a
2082 memory or register operand.
2084 DISPATCH_TABLE is a set of case labels. The set should be sorted in
2085 ascending order, be contiguous, starting with value 0, and contain only
2086 single-valued case labels. */
2088 void
2089 expand_sjlj_dispatch_table (rtx dispatch_index,
2090 VEC(tree,heap) *dispatch_table)
2092 tree index_type = integer_type_node;
2093 enum machine_mode index_mode = TYPE_MODE (index_type);
2095 int ncases = VEC_length (tree, dispatch_table);
2097 do_pending_stack_adjust ();
2098 rtx before_case = get_last_insn ();
2100 /* Expand as a decrement-chain if there are 5 or fewer dispatch
2101 labels. This covers more than 98% of the cases in libjava,
2102 and seems to be a reasonable compromise between the "old way"
2103 of expanding as a decision tree or dispatch table vs. the "new
2104 way" with decrement chain or dispatch table. */
2105 if (VEC_length (tree, dispatch_table) <= 5
2106 || (!HAVE_casesi && !HAVE_tablejump)
2107 || !flag_jump_tables)
2109 /* Expand the dispatch as a decrement chain:
2111 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
2115 if (index == 0) do_0; else index--;
2116 if (index == 0) do_1; else index--;
2118 if (index == 0) do_N; else index--;
2120 This is more efficient than a dispatch table on most machines.
2121 The last "index--" is redundant but the code is trivially dead
2122 and will be cleaned up by later passes. */
2123 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
2124 rtx zero = CONST0_RTX (index_mode);
2125 for (int i = 0; i < ncases; i++)
2127 tree elt = VEC_index (tree, dispatch_table, i);
2128 rtx lab = label_rtx (CASE_LABEL (elt));
2129 do_jump_if_equal (index_mode, index, zero, lab, 0);
2130 force_expand_binop (index_mode, sub_optab,
2131 index, CONST1_RTX (index_mode),
2132 index, 0, OPTAB_DIRECT);
2135 else
2137 /* Similar to expand_case, but much simpler. */
2138 struct case_node *case_list = 0;
2139 alloc_pool case_node_pool = create_alloc_pool ("struct sjlj_case pool",
2140 sizeof (struct case_node),
2141 ncases);
2142 tree index_expr = make_tree (index_type, dispatch_index);
2143 tree minval = build_int_cst (index_type, 0);
2144 tree maxval = CASE_LOW (VEC_last (tree, dispatch_table));
2145 tree range = maxval;
2146 rtx default_label = gen_label_rtx ();
2148 for (int i = ncases - 1; i > 0; --i)
2150 tree elt = VEC_index (tree, dispatch_table, i);
2151 tree low = CASE_LOW (elt);
2152 tree lab = CASE_LABEL (elt);
2153 case_list = add_case_node (case_list, low, low, lab, case_node_pool);
2156 emit_case_dispatch_table (index_expr, index_type,
2157 case_list, default_label,
2158 minval, maxval, range);
2159 emit_label (default_label);
2160 free_alloc_pool (case_node_pool);
2163 /* Dispatching something not handled? Trap! */
2164 expand_builtin_trap ();
2166 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2168 free_temp_slots ();
2172 /* Take an ordered list of case nodes
2173 and transform them into a near optimal binary tree,
2174 on the assumption that any target code selection value is as
2175 likely as any other.
2177 The transformation is performed by splitting the ordered
2178 list into two equal sections plus a pivot. The parts are
2179 then attached to the pivot as left and right branches. Each
2180 branch is then transformed recursively. */
2182 static void
2183 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
2185 case_node_ptr np;
2187 np = *head;
2188 if (np)
2190 int i = 0;
2191 int ranges = 0;
2192 case_node_ptr *npp;
2193 case_node_ptr left;
2195 /* Count the number of entries on branch. Also count the ranges. */
2197 while (np)
2199 if (!tree_int_cst_equal (np->low, np->high))
2200 ranges++;
2202 i++;
2203 np = np->right;
2206 if (i > 2)
2208 /* Split this list if it is long enough for that to help. */
2209 npp = head;
2210 left = *npp;
2212 /* If there are just three nodes, split at the middle one. */
2213 if (i == 3)
2214 npp = &(*npp)->right;
2215 else
2217 /* Find the place in the list that bisects the list's total cost,
2218 where ranges count as 2.
2219 Here I gets half the total cost. */
2220 i = (i + ranges + 1) / 2;
2221 while (1)
2223 /* Skip nodes while their cost does not reach that amount. */
2224 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
2225 i--;
2226 i--;
2227 if (i <= 0)
2228 break;
2229 npp = &(*npp)->right;
2232 *head = np = *npp;
2233 *npp = 0;
2234 np->parent = parent;
2235 np->left = left;
2237 /* Optimize each of the two split parts. */
2238 balance_case_nodes (&np->left, np);
2239 balance_case_nodes (&np->right, np);
2241 else
2243 /* Else leave this branch as one level,
2244 but fill in `parent' fields. */
2245 np = *head;
2246 np->parent = parent;
2247 for (; np->right; np = np->right)
2248 np->right->parent = np;
2253 /* Search the parent sections of the case node tree
2254 to see if a test for the lower bound of NODE would be redundant.
2255 INDEX_TYPE is the type of the index expression.
2257 The instructions to generate the case decision tree are
2258 output in the same order as nodes are processed so it is
2259 known that if a parent node checks the range of the current
2260 node minus one that the current node is bounded at its lower
2261 span. Thus the test would be redundant. */
2263 static int
2264 node_has_low_bound (case_node_ptr node, tree index_type)
2266 tree low_minus_one;
2267 case_node_ptr pnode;
2269 /* If the lower bound of this node is the lowest value in the index type,
2270 we need not test it. */
2272 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
2273 return 1;
2275 /* If this node has a left branch, the value at the left must be less
2276 than that at this node, so it cannot be bounded at the bottom and
2277 we need not bother testing any further. */
2279 if (node->left)
2280 return 0;
2282 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
2283 node->low,
2284 build_int_cst (TREE_TYPE (node->low), 1));
2286 /* If the subtraction above overflowed, we can't verify anything.
2287 Otherwise, look for a parent that tests our value - 1. */
2289 if (! tree_int_cst_lt (low_minus_one, node->low))
2290 return 0;
2292 for (pnode = node->parent; pnode; pnode = pnode->parent)
2293 if (tree_int_cst_equal (low_minus_one, pnode->high))
2294 return 1;
2296 return 0;
2299 /* Search the parent sections of the case node tree
2300 to see if a test for the upper bound of NODE would be redundant.
2301 INDEX_TYPE is the type of the index expression.
2303 The instructions to generate the case decision tree are
2304 output in the same order as nodes are processed so it is
2305 known that if a parent node checks the range of the current
2306 node plus one that the current node is bounded at its upper
2307 span. Thus the test would be redundant. */
2309 static int
2310 node_has_high_bound (case_node_ptr node, tree index_type)
2312 tree high_plus_one;
2313 case_node_ptr pnode;
2315 /* If there is no upper bound, obviously no test is needed. */
2317 if (TYPE_MAX_VALUE (index_type) == NULL)
2318 return 1;
2320 /* If the upper bound of this node is the highest value in the type
2321 of the index expression, we need not test against it. */
2323 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
2324 return 1;
2326 /* If this node has a right branch, the value at the right must be greater
2327 than that at this node, so it cannot be bounded at the top and
2328 we need not bother testing any further. */
2330 if (node->right)
2331 return 0;
2333 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
2334 node->high,
2335 build_int_cst (TREE_TYPE (node->high), 1));
2337 /* If the addition above overflowed, we can't verify anything.
2338 Otherwise, look for a parent that tests our value + 1. */
2340 if (! tree_int_cst_lt (node->high, high_plus_one))
2341 return 0;
2343 for (pnode = node->parent; pnode; pnode = pnode->parent)
2344 if (tree_int_cst_equal (high_plus_one, pnode->low))
2345 return 1;
2347 return 0;
2350 /* Search the parent sections of the
2351 case node tree to see if both tests for the upper and lower
2352 bounds of NODE would be redundant. */
2354 static int
2355 node_is_bounded (case_node_ptr node, tree index_type)
2357 return (node_has_low_bound (node, index_type)
2358 && node_has_high_bound (node, index_type));
2361 /* Emit step-by-step code to select a case for the value of INDEX.
2362 The thus generated decision tree follows the form of the
2363 case-node binary tree NODE, whose nodes represent test conditions.
2364 INDEX_TYPE is the type of the index of the switch.
2366 Care is taken to prune redundant tests from the decision tree
2367 by detecting any boundary conditions already checked by
2368 emitted rtx. (See node_has_high_bound, node_has_low_bound
2369 and node_is_bounded, above.)
2371 Where the test conditions can be shown to be redundant we emit
2372 an unconditional jump to the target code. As a further
2373 optimization, the subordinates of a tree node are examined to
2374 check for bounded nodes. In this case conditional and/or
2375 unconditional jumps as a result of the boundary check for the
2376 current node are arranged to target the subordinates associated
2377 code for out of bound conditions on the current node.
2379 We can assume that when control reaches the code generated here,
2380 the index value has already been compared with the parents
2381 of this node, and determined to be on the same side of each parent
2382 as this node is. Thus, if this node tests for the value 51,
2383 and a parent tested for 52, we don't need to consider
2384 the possibility of a value greater than 51. If another parent
2385 tests for the value 50, then this node need not test anything. */
2387 static void
2388 emit_case_nodes (rtx index, case_node_ptr node, rtx default_label,
2389 tree index_type)
2391 /* If INDEX has an unsigned type, we must make unsigned branches. */
2392 int unsignedp = TYPE_UNSIGNED (index_type);
2393 enum machine_mode mode = GET_MODE (index);
2394 enum machine_mode imode = TYPE_MODE (index_type);
2396 /* Handle indices detected as constant during RTL expansion. */
2397 if (mode == VOIDmode)
2398 mode = imode;
2400 /* See if our parents have already tested everything for us.
2401 If they have, emit an unconditional jump for this node. */
2402 if (node_is_bounded (node, index_type))
2403 emit_jump (label_rtx (node->code_label));
2405 else if (tree_int_cst_equal (node->low, node->high))
2407 /* Node is single valued. First see if the index expression matches
2408 this node and then check our children, if any. */
2410 do_jump_if_equal (mode, index,
2411 convert_modes (mode, imode,
2412 expand_normal (node->low),
2413 unsignedp),
2414 label_rtx (node->code_label), unsignedp);
2416 if (node->right != 0 && node->left != 0)
2418 /* This node has children on both sides.
2419 Dispatch to one side or the other
2420 by comparing the index value with this node's value.
2421 If one subtree is bounded, check that one first,
2422 so we can avoid real branches in the tree. */
2424 if (node_is_bounded (node->right, index_type))
2426 emit_cmp_and_jump_insns (index,
2427 convert_modes
2428 (mode, imode,
2429 expand_normal (node->high),
2430 unsignedp),
2431 GT, NULL_RTX, mode, unsignedp,
2432 label_rtx (node->right->code_label));
2433 emit_case_nodes (index, node->left, default_label, index_type);
2436 else if (node_is_bounded (node->left, index_type))
2438 emit_cmp_and_jump_insns (index,
2439 convert_modes
2440 (mode, imode,
2441 expand_normal (node->high),
2442 unsignedp),
2443 LT, NULL_RTX, mode, unsignedp,
2444 label_rtx (node->left->code_label));
2445 emit_case_nodes (index, node->right, default_label, index_type);
2448 /* If both children are single-valued cases with no
2449 children, finish up all the work. This way, we can save
2450 one ordered comparison. */
2451 else if (tree_int_cst_equal (node->right->low, node->right->high)
2452 && node->right->left == 0
2453 && node->right->right == 0
2454 && tree_int_cst_equal (node->left->low, node->left->high)
2455 && node->left->left == 0
2456 && node->left->right == 0)
2458 /* Neither node is bounded. First distinguish the two sides;
2459 then emit the code for one side at a time. */
2461 /* See if the value matches what the right hand side
2462 wants. */
2463 do_jump_if_equal (mode, index,
2464 convert_modes (mode, imode,
2465 expand_normal (node->right->low),
2466 unsignedp),
2467 label_rtx (node->right->code_label),
2468 unsignedp);
2470 /* See if the value matches what the left hand side
2471 wants. */
2472 do_jump_if_equal (mode, index,
2473 convert_modes (mode, imode,
2474 expand_normal (node->left->low),
2475 unsignedp),
2476 label_rtx (node->left->code_label),
2477 unsignedp);
2480 else
2482 /* Neither node is bounded. First distinguish the two sides;
2483 then emit the code for one side at a time. */
2485 tree test_label
2486 = build_decl (CURR_INSN_LOCATION,
2487 LABEL_DECL, NULL_TREE, NULL_TREE);
2489 /* See if the value is on the right. */
2490 emit_cmp_and_jump_insns (index,
2491 convert_modes
2492 (mode, imode,
2493 expand_normal (node->high),
2494 unsignedp),
2495 GT, NULL_RTX, mode, unsignedp,
2496 label_rtx (test_label));
2498 /* Value must be on the left.
2499 Handle the left-hand subtree. */
2500 emit_case_nodes (index, node->left, default_label, index_type);
2501 /* If left-hand subtree does nothing,
2502 go to default. */
2503 if (default_label)
2504 emit_jump (default_label);
2506 /* Code branches here for the right-hand subtree. */
2507 expand_label (test_label);
2508 emit_case_nodes (index, node->right, default_label, index_type);
2512 else if (node->right != 0 && node->left == 0)
2514 /* Here we have a right child but no left so we issue a conditional
2515 branch to default and process the right child.
2517 Omit the conditional branch to default if the right child
2518 does not have any children and is single valued; it would
2519 cost too much space to save so little time. */
2521 if (node->right->right || node->right->left
2522 || !tree_int_cst_equal (node->right->low, node->right->high))
2524 if (!node_has_low_bound (node, index_type))
2526 emit_cmp_and_jump_insns (index,
2527 convert_modes
2528 (mode, imode,
2529 expand_normal (node->high),
2530 unsignedp),
2531 LT, NULL_RTX, mode, unsignedp,
2532 default_label);
2535 emit_case_nodes (index, node->right, default_label, index_type);
2537 else
2538 /* We cannot process node->right normally
2539 since we haven't ruled out the numbers less than
2540 this node's value. So handle node->right explicitly. */
2541 do_jump_if_equal (mode, index,
2542 convert_modes
2543 (mode, imode,
2544 expand_normal (node->right->low),
2545 unsignedp),
2546 label_rtx (node->right->code_label), unsignedp);
2549 else if (node->right == 0 && node->left != 0)
2551 /* Just one subtree, on the left. */
2552 if (node->left->left || node->left->right
2553 || !tree_int_cst_equal (node->left->low, node->left->high))
2555 if (!node_has_high_bound (node, index_type))
2557 emit_cmp_and_jump_insns (index,
2558 convert_modes
2559 (mode, imode,
2560 expand_normal (node->high),
2561 unsignedp),
2562 GT, NULL_RTX, mode, unsignedp,
2563 default_label);
2566 emit_case_nodes (index, node->left, default_label, index_type);
2568 else
2569 /* We cannot process node->left normally
2570 since we haven't ruled out the numbers less than
2571 this node's value. So handle node->left explicitly. */
2572 do_jump_if_equal (mode, index,
2573 convert_modes
2574 (mode, imode,
2575 expand_normal (node->left->low),
2576 unsignedp),
2577 label_rtx (node->left->code_label), unsignedp);
2580 else
2582 /* Node is a range. These cases are very similar to those for a single
2583 value, except that we do not start by testing whether this node
2584 is the one to branch to. */
2586 if (node->right != 0 && node->left != 0)
2588 /* Node has subtrees on both sides.
2589 If the right-hand subtree is bounded,
2590 test for it first, since we can go straight there.
2591 Otherwise, we need to make a branch in the control structure,
2592 then handle the two subtrees. */
2593 tree test_label = 0;
2595 if (node_is_bounded (node->right, index_type))
2596 /* Right hand node is fully bounded so we can eliminate any
2597 testing and branch directly to the target code. */
2598 emit_cmp_and_jump_insns (index,
2599 convert_modes
2600 (mode, imode,
2601 expand_normal (node->high),
2602 unsignedp),
2603 GT, NULL_RTX, mode, unsignedp,
2604 label_rtx (node->right->code_label));
2605 else
2607 /* Right hand node requires testing.
2608 Branch to a label where we will handle it later. */
2610 test_label = build_decl (CURR_INSN_LOCATION,
2611 LABEL_DECL, NULL_TREE, NULL_TREE);
2612 emit_cmp_and_jump_insns (index,
2613 convert_modes
2614 (mode, imode,
2615 expand_normal (node->high),
2616 unsignedp),
2617 GT, NULL_RTX, mode, unsignedp,
2618 label_rtx (test_label));
2621 /* Value belongs to this node or to the left-hand subtree. */
2623 emit_cmp_and_jump_insns (index,
2624 convert_modes
2625 (mode, imode,
2626 expand_normal (node->low),
2627 unsignedp),
2628 GE, NULL_RTX, mode, unsignedp,
2629 label_rtx (node->code_label));
2631 /* Handle the left-hand subtree. */
2632 emit_case_nodes (index, node->left, default_label, index_type);
2634 /* If right node had to be handled later, do that now. */
2636 if (test_label)
2638 /* If the left-hand subtree fell through,
2639 don't let it fall into the right-hand subtree. */
2640 if (default_label)
2641 emit_jump (default_label);
2643 expand_label (test_label);
2644 emit_case_nodes (index, node->right, default_label, index_type);
2648 else if (node->right != 0 && node->left == 0)
2650 /* Deal with values to the left of this node,
2651 if they are possible. */
2652 if (!node_has_low_bound (node, index_type))
2654 emit_cmp_and_jump_insns (index,
2655 convert_modes
2656 (mode, imode,
2657 expand_normal (node->low),
2658 unsignedp),
2659 LT, NULL_RTX, mode, unsignedp,
2660 default_label);
2663 /* Value belongs to this node or to the right-hand subtree. */
2665 emit_cmp_and_jump_insns (index,
2666 convert_modes
2667 (mode, imode,
2668 expand_normal (node->high),
2669 unsignedp),
2670 LE, NULL_RTX, mode, unsignedp,
2671 label_rtx (node->code_label));
2673 emit_case_nodes (index, node->right, default_label, index_type);
2676 else if (node->right == 0 && node->left != 0)
2678 /* Deal with values to the right of this node,
2679 if they are possible. */
2680 if (!node_has_high_bound (node, index_type))
2682 emit_cmp_and_jump_insns (index,
2683 convert_modes
2684 (mode, imode,
2685 expand_normal (node->high),
2686 unsignedp),
2687 GT, NULL_RTX, mode, unsignedp,
2688 default_label);
2691 /* Value belongs to this node or to the left-hand subtree. */
2693 emit_cmp_and_jump_insns (index,
2694 convert_modes
2695 (mode, imode,
2696 expand_normal (node->low),
2697 unsignedp),
2698 GE, NULL_RTX, mode, unsignedp,
2699 label_rtx (node->code_label));
2701 emit_case_nodes (index, node->left, default_label, index_type);
2704 else
2706 /* Node has no children so we check low and high bounds to remove
2707 redundant tests. Only one of the bounds can exist,
2708 since otherwise this node is bounded--a case tested already. */
2709 int high_bound = node_has_high_bound (node, index_type);
2710 int low_bound = node_has_low_bound (node, index_type);
2712 if (!high_bound && low_bound)
2714 emit_cmp_and_jump_insns (index,
2715 convert_modes
2716 (mode, imode,
2717 expand_normal (node->high),
2718 unsignedp),
2719 GT, NULL_RTX, mode, unsignedp,
2720 default_label);
2723 else if (!low_bound && high_bound)
2725 emit_cmp_and_jump_insns (index,
2726 convert_modes
2727 (mode, imode,
2728 expand_normal (node->low),
2729 unsignedp),
2730 LT, NULL_RTX, mode, unsignedp,
2731 default_label);
2733 else if (!low_bound && !high_bound)
2735 /* Widen LOW and HIGH to the same width as INDEX. */
2736 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2737 tree low = build1 (CONVERT_EXPR, type, node->low);
2738 tree high = build1 (CONVERT_EXPR, type, node->high);
2739 rtx low_rtx, new_index, new_bound;
2741 /* Instead of doing two branches, emit one unsigned branch for
2742 (index-low) > (high-low). */
2743 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2744 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2745 NULL_RTX, unsignedp,
2746 OPTAB_WIDEN);
2747 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2748 high, low),
2749 NULL_RTX, mode, EXPAND_NORMAL);
2751 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2752 mode, 1, default_label);
2755 emit_jump (label_rtx (node->code_label));