OSDN Git Service

5c8a6e8af9c038e906d47e5d68af6342a93c23c2
[pf3gnuchains/gcc-fork.git] / gcc / stmt.c
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 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
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    It also creates the rtl expressions for parameters and auto variables
25    and has full responsibility for allocating stack slots.
26
27    The functions whose names start with `expand_' are called by the
28    parser to generate RTL instructions for various kinds of constructs.
29
30    Some control and binding constructs require calling several such
31    functions at different times.  For example, a simple if-then
32    is expanded by calling `expand_start_cond' (with the condition-expression
33    as argument) before parsing the then-clause and calling `expand_end_cond'
34    after parsing the then-clause.  */
35
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "tm.h"
40
41 #include "rtl.h"
42 #include "tree.h"
43 #include "tm_p.h"
44 #include "flags.h"
45 #include "except.h"
46 #include "function.h"
47 #include "insn-config.h"
48 #include "expr.h"
49 #include "libfuncs.h"
50 #include "hard-reg-set.h"
51 #include "loop.h"
52 #include "recog.h"
53 #include "machmode.h"
54 #include "toplev.h"
55 #include "output.h"
56 #include "ggc.h"
57 #include "langhooks.h"
58 #include "predict.h"
59 #include "optabs.h"
60 #include "target.h"
61 #include "regs.h"
62 \f
63 /* Functions and data structures for expanding case statements.  */
64
65 /* Case label structure, used to hold info on labels within case
66    statements.  We handle "range" labels; for a single-value label
67    as in C, the high and low limits are the same.
68
69    An AVL tree of case nodes is initially created, and later transformed
70    to a list linked via the RIGHT fields in the nodes.  Nodes with
71    higher case values are later in the list.
72
73    Switch statements can be output in one of two forms.  A branch table
74    is used if there are more than a few labels and the labels are dense
75    within the range between the smallest and largest case value.  If a
76    branch table is used, no further manipulations are done with the case
77    node chain.
78
79    The alternative to the use of a branch table is to generate a series
80    of compare and jump insns.  When that is done, we use the LEFT, RIGHT,
81    and PARENT fields to hold a binary tree.  Initially the tree is
82    totally unbalanced, with everything on the right.  We balance the tree
83    with nodes on the left having lower case values than the parent
84    and nodes on the right having higher values.  We then output the tree
85    in order.  */
86
87 struct case_node GTY(())
88 {
89   struct case_node      *left;  /* Left son in binary tree */
90   struct case_node      *right; /* Right son in binary tree; also node chain */
91   struct case_node      *parent; /* Parent of node in binary tree */
92   tree                  low;    /* Lowest index value for this label */
93   tree                  high;   /* Highest index value for this label */
94   tree                  code_label; /* Label to jump to when node matches */
95   int                   balance;
96 };
97
98 typedef struct case_node case_node;
99 typedef struct case_node *case_node_ptr;
100
101 /* These are used by estimate_case_costs and balance_case_nodes.  */
102
103 /* This must be a signed type, and non-ANSI compilers lack signed char.  */
104 static short cost_table_[129];
105 static int use_cost_table;
106 static int cost_table_initialized;
107
108 /* Special care is needed because we allow -1, but TREE_INT_CST_LOW
109    is unsigned.  */
110 #define COST_TABLE(I)  cost_table_[(unsigned HOST_WIDE_INT) ((I) + 1)]
111 \f
112 /* Stack of control and binding constructs we are currently inside.
113
114    These constructs begin when you call `expand_start_WHATEVER'
115    and end when you call `expand_end_WHATEVER'.  This stack records
116    info about how the construct began that tells the end-function
117    what to do.  It also may provide information about the construct
118    to alter the behavior of other constructs within the body.
119    For example, they may affect the behavior of C `break' and `continue'.
120
121    Each construct gets one `struct nesting' object.
122    All of these objects are chained through the `all' field.
123    `nesting_stack' points to the first object (innermost construct).
124    The position of an entry on `nesting_stack' is in its `depth' field.
125
126    Each type of construct has its own individual stack.
127    For example, loops have `cond_stack'.  Each object points to the
128    next object of the same type through the `next' field.
129
130    Some constructs are visible to `break' exit-statements and others
131    are not.  Which constructs are visible depends on the language.
132    Therefore, the data structure allows each construct to be visible
133    or not, according to the args given when the construct is started.
134    The construct is visible if the `exit_label' field is non-null.
135    In that case, the value should be a CODE_LABEL rtx.  */
136
137 struct nesting GTY(())
138 {
139   struct nesting *all;
140   struct nesting *next;
141   int depth;
142   rtx exit_label;
143   enum nesting_desc {
144     COND_NESTING,
145     BLOCK_NESTING,
146     CASE_NESTING
147   } desc;
148   union nesting_u
149     {
150       /* For conds (if-then and if-then-else statements).  */
151       struct nesting_cond
152         {
153           /* Label for the end of the if construct.
154              There is none if EXITFLAG was not set
155              and no `else' has been seen yet.  */
156           rtx endif_label;
157           /* Label for the end of this alternative.
158              This may be the end of the if or the next else/elseif.  */
159           rtx next_label;
160         } GTY ((tag ("COND_NESTING"))) cond;
161       /* For variable binding contours.  */
162       struct nesting_block
163         {
164           /* Sequence number of this binding contour within the function,
165              in order of entry.  */
166           int block_start_count;
167           /* Nonzero => value to restore stack to on exit.  */
168           rtx stack_level;
169           /* The NOTE that starts this contour.
170              Used by expand_goto to check whether the destination
171              is within each contour or not.  */
172           rtx first_insn;
173           /* Innermost containing binding contour that has a stack level.  */
174           struct nesting *innermost_stack_block;
175           /* List of cleanups to be run on exit from this contour.
176              This is a list of expressions to be evaluated.
177              The TREE_PURPOSE of each link is the ..._DECL node
178              which the cleanup pertains to.  */
179           tree cleanups;
180           /* List of cleanup-lists of blocks containing this block,
181              as they were at the locus where this block appears.
182              There is an element for each containing block,
183              ordered innermost containing block first.
184              The tail of this list can be 0,
185              if all remaining elements would be empty lists.
186              The element's TREE_VALUE is the cleanup-list of that block,
187              which may be null.  */
188           tree outer_cleanups;
189           /* Chain of labels defined inside this binding contour.
190              For contours that have stack levels or cleanups.  */
191           struct label_chain *label_chain;
192           /* Nonzero if this is associated with an EH region.  */
193           int exception_region;
194           /* The saved target_temp_slot_level from our outer block.
195              We may reset target_temp_slot_level to be the level of
196              this block, if that is done, target_temp_slot_level
197              reverts to the saved target_temp_slot_level at the very
198              end of the block.  */
199           int block_target_temp_slot_level;
200           /* True if we are currently emitting insns in an area of
201              output code that is controlled by a conditional
202              expression.  This is used by the cleanup handling code to
203              generate conditional cleanup actions.  */
204           int conditional_code;
205           /* A place to move the start of the exception region for any
206              of the conditional cleanups, must be at the end or after
207              the start of the last unconditional cleanup, and before any
208              conditional branch points.  */
209           rtx last_unconditional_cleanup;
210         } GTY ((tag ("BLOCK_NESTING"))) block;
211       /* For switch (C) or case (Pascal) statements.  */
212       struct nesting_case
213         {
214           /* The insn after which the case dispatch should finally
215              be emitted.  Zero for a dummy.  */
216           rtx start;
217           /* A list of case labels; it is first built as an AVL tree.
218              During expand_end_case, this is converted to a list, and may be
219              rearranged into a nearly balanced binary tree.  */
220           struct case_node *case_list;
221           /* Label to jump to if no case matches.  */
222           tree default_label;
223           /* The expression to be dispatched on.  */
224           tree index_expr;
225           /* Type that INDEX_EXPR should be converted to.  */
226           tree nominal_type;
227           /* Name of this kind of statement, for warnings.  */
228           const char *printname;
229           /* Used to save no_line_numbers till we see the first case label.
230              We set this to -1 when we see the first case label in this
231              case statement.  */
232           int line_number_status;
233         } GTY ((tag ("CASE_NESTING"))) case_stmt;
234     } GTY ((desc ("%1.desc"))) data;
235 };
236
237 /* Allocate and return a new `struct nesting'.  */
238
239 #define ALLOC_NESTING() ggc_alloc (sizeof (struct nesting))
240
241 /* Pop the nesting stack element by element until we pop off
242    the element which is at the top of STACK.
243    Update all the other stacks, popping off elements from them
244    as we pop them from nesting_stack.  */
245
246 #define POPSTACK(STACK)                                 \
247 do { struct nesting *target = STACK;                    \
248      struct nesting *this;                              \
249      do { this = nesting_stack;                         \
250           if (cond_stack == this)                       \
251             cond_stack = cond_stack->next;              \
252           if (block_stack == this)                      \
253             block_stack = block_stack->next;            \
254           if (stack_block_stack == this)                \
255             stack_block_stack = stack_block_stack->next; \
256           if (case_stack == this)                       \
257             case_stack = case_stack->next;              \
258           nesting_depth = nesting_stack->depth - 1;     \
259           nesting_stack = this->all; }                  \
260      while (this != target); } while (0)
261 \f
262 /* In some cases it is impossible to generate code for a forward goto
263    until the label definition is seen.  This happens when it may be necessary
264    for the goto to reset the stack pointer: we don't yet know how to do that.
265    So expand_goto puts an entry on this fixup list.
266    Each time a binding contour that resets the stack is exited,
267    we check each fixup.
268    If the target label has now been defined, we can insert the proper code.  */
269
270 struct goto_fixup GTY(())
271 {
272   /* Points to following fixup.  */
273   struct goto_fixup *next;
274   /* Points to the insn before the jump insn.
275      If more code must be inserted, it goes after this insn.  */
276   rtx before_jump;
277   /* The LABEL_DECL that this jump is jumping to, or 0
278      for break, continue or return.  */
279   tree target;
280   /* The BLOCK for the place where this goto was found.  */
281   tree context;
282   /* The CODE_LABEL rtx that this is jumping to.  */
283   rtx target_rtl;
284   /* Number of binding contours started in current function
285      before the label reference.  */
286   int block_start_count;
287   /* The outermost stack level that should be restored for this jump.
288      Each time a binding contour that resets the stack is exited,
289      if the target label is *not* yet defined, this slot is updated.  */
290   rtx stack_level;
291   /* List of lists of cleanup expressions to be run by this goto.
292      There is one element for each block that this goto is within.
293      The tail of this list can be 0,
294      if all remaining elements would be empty.
295      The TREE_VALUE contains the cleanup list of that block as of the
296      time this goto was seen.
297      The TREE_ADDRESSABLE flag is 1 for a block that has been exited.  */
298   tree cleanup_list_list;
299 };
300
301 /* Within any binding contour that must restore a stack level,
302    all labels are recorded with a chain of these structures.  */
303
304 struct label_chain GTY(())
305 {
306   /* Points to following fixup.  */
307   struct label_chain *next;
308   tree label;
309 };
310
311 struct stmt_status GTY(())
312 {
313   /* Chain of all pending binding contours.  */
314   struct nesting * x_block_stack;
315
316   /* If any new stacks are added here, add them to POPSTACKS too.  */
317
318   /* Chain of all pending binding contours that restore stack levels
319      or have cleanups.  */
320   struct nesting * x_stack_block_stack;
321
322   /* Chain of all pending conditional statements.  */
323   struct nesting * x_cond_stack;
324
325   /* Chain of all pending case or switch statements.  */
326   struct nesting * x_case_stack;
327
328   /* Separate chain including all of the above,
329      chained through the `all' field.  */
330   struct nesting * x_nesting_stack;
331
332   /* Number of entries on nesting_stack now.  */
333   int x_nesting_depth;
334
335   /* Number of binding contours started so far in this function.  */
336   int x_block_start_count;
337
338   /* Each time we expand an expression-statement,
339      record the expr's type and its RTL value here.  */
340   tree x_last_expr_type;
341   rtx x_last_expr_value;
342   rtx x_last_expr_alt_rtl;
343
344   /* Nonzero if within a ({...}) grouping, in which case we must
345      always compute a value for each expr-stmt in case it is the last one.  */
346   int x_expr_stmts_for_value;
347
348   /* Location of last line-number note, whether we actually
349      emitted it or not.  */
350   location_t x_emit_locus;
351
352   struct goto_fixup *x_goto_fixup_chain;
353 };
354
355 #define block_stack (cfun->stmt->x_block_stack)
356 #define stack_block_stack (cfun->stmt->x_stack_block_stack)
357 #define cond_stack (cfun->stmt->x_cond_stack)
358 #define case_stack (cfun->stmt->x_case_stack)
359 #define nesting_stack (cfun->stmt->x_nesting_stack)
360 #define nesting_depth (cfun->stmt->x_nesting_depth)
361 #define current_block_start_count (cfun->stmt->x_block_start_count)
362 #define last_expr_type (cfun->stmt->x_last_expr_type)
363 #define last_expr_value (cfun->stmt->x_last_expr_value)
364 #define last_expr_alt_rtl (cfun->stmt->x_last_expr_alt_rtl)
365 #define expr_stmts_for_value (cfun->stmt->x_expr_stmts_for_value)
366 #define emit_locus (cfun->stmt->x_emit_locus)
367 #define goto_fixup_chain (cfun->stmt->x_goto_fixup_chain)
368
369 /* Nonzero if we are using EH to handle cleanups.  */
370 int using_eh_for_cleanups_p = 0;
371
372 static int n_occurrences (int, const char *);
373 static bool decl_conflicts_with_clobbers_p (tree, const HARD_REG_SET);
374 static void expand_goto_internal (tree, rtx, rtx);
375 static int expand_fixup (tree, rtx, rtx);
376 static void expand_nl_goto_receiver (void);
377 static void fixup_gotos (struct nesting *, rtx, tree, rtx, int);
378 static bool check_operand_nalternatives (tree, tree);
379 static bool check_unique_operand_names (tree, tree);
380 static char *resolve_operand_name_1 (char *, tree, tree);
381 static void expand_null_return_1 (rtx);
382 static enum br_predictor return_prediction (rtx);
383 static rtx shift_return_value (rtx);
384 static void expand_value_return (rtx);
385 static void expand_cleanups (tree, int, int);
386 static void check_seenlabel (void);
387 static void do_jump_if_equal (rtx, rtx, rtx, int);
388 static int estimate_case_costs (case_node_ptr);
389 static bool same_case_target_p (rtx, rtx);
390 static void strip_default_case_nodes (case_node_ptr *, rtx);
391 static bool lshift_cheap_p (void);
392 static int case_bit_test_cmp (const void *, const void *);
393 static void emit_case_bit_tests (tree, tree, tree, tree, case_node_ptr, rtx);
394 static void group_case_nodes (case_node_ptr);
395 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
396 static int node_has_low_bound (case_node_ptr, tree);
397 static int node_has_high_bound (case_node_ptr, tree);
398 static int node_is_bounded (case_node_ptr, tree);
399 static void emit_jump_if_reachable (rtx);
400 static void emit_case_nodes (rtx, case_node_ptr, rtx, tree);
401 static struct case_node *case_tree2list (case_node *, case_node *);
402 \f
403 void
404 using_eh_for_cleanups (void)
405 {
406   using_eh_for_cleanups_p = 1;
407 }
408
409 void
410 init_stmt_for_function (void)
411 {
412   cfun->stmt = ggc_alloc_cleared (sizeof (struct stmt_status));
413 }
414 \f
415 /* Record the current file and line.  Called from emit_line_note.  */
416
417 void
418 set_file_and_line_for_stmt (location_t location)
419 {
420   /* If we're outputting an inline function, and we add a line note,
421      there may be no CFUN->STMT information.  So, there's no need to
422      update it.  */
423   if (cfun->stmt)
424     emit_locus = location;
425 }
426
427 /* Emit a no-op instruction.  */
428
429 void
430 emit_nop (void)
431 {
432   rtx last_insn;
433
434   last_insn = get_last_insn ();
435   if (!optimize
436       && (GET_CODE (last_insn) == CODE_LABEL
437           || (GET_CODE (last_insn) == NOTE
438               && prev_real_insn (last_insn) == 0)))
439     emit_insn (gen_nop ());
440 }
441 \f
442 /* Return the rtx-label that corresponds to a LABEL_DECL,
443    creating it if necessary.  */
444
445 rtx
446 label_rtx (tree label)
447 {
448   if (TREE_CODE (label) != LABEL_DECL)
449     abort ();
450
451   if (!DECL_RTL_SET_P (label))
452     {
453       rtx r = gen_label_rtx ();
454       SET_DECL_RTL (label, r);
455       if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
456         LABEL_PRESERVE_P (r) = 1;
457     }
458
459   return DECL_RTL (label);
460 }
461
462 /* As above, but also put it on the forced-reference list of the
463    function that contains it.  */
464 rtx
465 force_label_rtx (tree label)
466 {
467   rtx ref = label_rtx (label);
468   tree function = decl_function_context (label);
469   struct function *p;
470
471   if (!function)
472     abort ();
473
474   if (function != current_function_decl)
475     p = find_function_data (function);
476   else
477     p = cfun;
478
479   p->expr->x_forced_labels = gen_rtx_EXPR_LIST (VOIDmode, ref,
480                                                 p->expr->x_forced_labels);
481   return ref;
482 }
483
484 /* Add an unconditional jump to LABEL as the next sequential instruction.  */
485
486 void
487 emit_jump (rtx label)
488 {
489   do_pending_stack_adjust ();
490   emit_jump_insn (gen_jump (label));
491   emit_barrier ();
492 }
493
494 /* Emit code to jump to the address
495    specified by the pointer expression EXP.  */
496
497 void
498 expand_computed_goto (tree exp)
499 {
500   rtx x = expand_expr (exp, NULL_RTX, VOIDmode, 0);
501
502   x = convert_memory_address (Pmode, x);
503
504   emit_queue ();
505   do_pending_stack_adjust ();
506   emit_indirect_jump (x);
507 }
508 \f
509 /* Handle goto statements and the labels that they can go to.  */
510
511 /* Specify the location in the RTL code of a label LABEL,
512    which is a LABEL_DECL tree node.
513
514    This is used for the kind of label that the user can jump to with a
515    goto statement, and for alternatives of a switch or case statement.
516    RTL labels generated for loops and conditionals don't go through here;
517    they are generated directly at the RTL level, by other functions below.
518
519    Note that this has nothing to do with defining label *names*.
520    Languages vary in how they do that and what that even means.  */
521
522 void
523 expand_label (tree label)
524 {
525   struct label_chain *p;
526   rtx label_r = label_rtx (label);
527
528   do_pending_stack_adjust ();
529   emit_label (label_r);
530   if (DECL_NAME (label))
531     LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
532
533   if (DECL_NONLOCAL (label))
534     {
535       expand_nl_goto_receiver ();
536       nonlocal_goto_handler_labels
537         = gen_rtx_EXPR_LIST (VOIDmode, label_r,
538                              nonlocal_goto_handler_labels);
539     }
540
541   if (FORCED_LABEL (label))
542     forced_labels = gen_rtx_EXPR_LIST (VOIDmode, label_r, forced_labels);
543       
544   if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
545     maybe_set_first_label_num (label_r);
546
547   if (stack_block_stack != 0)
548     {
549       p = ggc_alloc (sizeof (struct label_chain));
550       p->next = stack_block_stack->data.block.label_chain;
551       stack_block_stack->data.block.label_chain = p;
552       p->label = label;
553     }
554 }
555
556 /* Generate RTL code for a `goto' statement with target label LABEL.
557    LABEL should be a LABEL_DECL tree node that was or will later be
558    defined with `expand_label'.  */
559
560 void
561 expand_goto (tree label)
562 {
563 #ifdef ENABLE_CHECKING
564   /* Check for a nonlocal goto to a containing function.  Should have
565      gotten translated to __builtin_nonlocal_goto.  */
566   tree context = decl_function_context (label);
567   if (context != 0 && context != current_function_decl)
568     abort ();
569 #endif
570
571   expand_goto_internal (label, label_rtx (label), NULL_RTX);
572 }
573
574 /* Generate RTL code for a `goto' statement with target label BODY.
575    LABEL should be a LABEL_REF.
576    LAST_INSN, if non-0, is the rtx we should consider as the last
577    insn emitted (for the purposes of cleaning up a return).  */
578
579 static void
580 expand_goto_internal (tree body, rtx label, rtx last_insn)
581 {
582   struct nesting *block;
583   rtx stack_level = 0;
584
585   if (GET_CODE (label) != CODE_LABEL)
586     abort ();
587
588   /* If label has already been defined, we can tell now
589      whether and how we must alter the stack level.  */
590
591   if (PREV_INSN (label) != 0)
592     {
593       /* Find the innermost pending block that contains the label.
594          (Check containment by comparing insn-uids.)
595          Then restore the outermost stack level within that block,
596          and do cleanups of all blocks contained in it.  */
597       for (block = block_stack; block; block = block->next)
598         {
599           if (INSN_UID (block->data.block.first_insn) < INSN_UID (label))
600             break;
601           if (block->data.block.stack_level != 0)
602             stack_level = block->data.block.stack_level;
603           /* Execute the cleanups for blocks we are exiting.  */
604           if (block->data.block.cleanups != 0)
605             {
606               expand_cleanups (block->data.block.cleanups, 1, 1);
607               do_pending_stack_adjust ();
608             }
609         }
610
611       if (stack_level)
612         {
613           /* Ensure stack adjust isn't done by emit_jump, as this
614              would clobber the stack pointer.  This one should be
615              deleted as dead by flow.  */
616           clear_pending_stack_adjust ();
617           do_pending_stack_adjust ();
618
619           /* Don't do this adjust if it's to the end label and this function
620              is to return with a depressed stack pointer.  */
621           if (label == return_label
622               && (((TREE_CODE (TREE_TYPE (current_function_decl))
623                    == FUNCTION_TYPE)
624                    && (TYPE_RETURNS_STACK_DEPRESSED
625                        (TREE_TYPE (current_function_decl))))))
626             ;
627           else
628             emit_stack_restore (SAVE_BLOCK, stack_level, NULL_RTX);
629         }
630
631       if (body != 0 && DECL_TOO_LATE (body))
632         error ("jump to `%s' invalidly jumps into binding contour",
633                IDENTIFIER_POINTER (DECL_NAME (body)));
634     }
635   /* Label not yet defined: may need to put this goto
636      on the fixup list.  */
637   else if (! expand_fixup (body, label, last_insn))
638     {
639       /* No fixup needed.  Record that the label is the target
640          of at least one goto that has no fixup.  */
641       if (body != 0)
642         TREE_ADDRESSABLE (body) = 1;
643     }
644
645   emit_jump (label);
646 }
647 \f
648 /* Generate if necessary a fixup for a goto
649    whose target label in tree structure (if any) is TREE_LABEL
650    and whose target in rtl is RTL_LABEL.
651
652    If LAST_INSN is nonzero, we pretend that the jump appears
653    after insn LAST_INSN instead of at the current point in the insn stream.
654
655    The fixup will be used later to insert insns just before the goto.
656    Those insns will restore the stack level as appropriate for the
657    target label, and will (in the case of C++) also invoke any object
658    destructors which have to be invoked when we exit the scopes which
659    are exited by the goto.
660
661    Value is nonzero if a fixup is made.  */
662
663 static int
664 expand_fixup (tree tree_label, rtx rtl_label, rtx last_insn)
665 {
666   struct nesting *block, *end_block;
667
668   /* See if we can recognize which block the label will be output in.
669      This is possible in some very common cases.
670      If we succeed, set END_BLOCK to that block.
671      Otherwise, set it to 0.  */
672
673   if (cond_stack
674       && (rtl_label == cond_stack->data.cond.endif_label
675           || rtl_label == cond_stack->data.cond.next_label))
676     end_block = cond_stack;
677   else
678     end_block = 0;
679
680   /* Now set END_BLOCK to the binding level to which we will return.  */
681
682   if (end_block)
683     {
684       struct nesting *next_block = end_block->all;
685       block = block_stack;
686
687       /* First see if the END_BLOCK is inside the innermost binding level.
688          If so, then no cleanups or stack levels are relevant.  */
689       while (next_block && next_block != block)
690         next_block = next_block->all;
691
692       if (next_block)
693         return 0;
694
695       /* Otherwise, set END_BLOCK to the innermost binding level
696          which is outside the relevant control-structure nesting.  */
697       next_block = block_stack->next;
698       for (block = block_stack; block != end_block; block = block->all)
699         if (block == next_block)
700           next_block = next_block->next;
701       end_block = next_block;
702     }
703
704   /* Does any containing block have a stack level or cleanups?
705      If not, no fixup is needed, and that is the normal case
706      (the only case, for standard C).  */
707   for (block = block_stack; block != end_block; block = block->next)
708     if (block->data.block.stack_level != 0
709         || block->data.block.cleanups != 0)
710       break;
711
712   if (block != end_block)
713     {
714       /* Ok, a fixup is needed.  Add a fixup to the list of such.  */
715       struct goto_fixup *fixup = ggc_alloc (sizeof (struct goto_fixup));
716       /* In case an old stack level is restored, make sure that comes
717          after any pending stack adjust.  */
718       /* ?? If the fixup isn't to come at the present position,
719          doing the stack adjust here isn't useful.  Doing it with our
720          settings at that location isn't useful either.  Let's hope
721          someone does it!  */
722       if (last_insn == 0)
723         do_pending_stack_adjust ();
724       fixup->target = tree_label;
725       fixup->target_rtl = rtl_label;
726
727       /* Create a BLOCK node and a corresponding matched set of
728          NOTE_INSN_BLOCK_BEG and NOTE_INSN_BLOCK_END notes at
729          this point.  The notes will encapsulate any and all fixup
730          code which we might later insert at this point in the insn
731          stream.  Also, the BLOCK node will be the parent (i.e. the
732          `SUPERBLOCK') of any other BLOCK nodes which we might create
733          later on when we are expanding the fixup code.
734
735          Note that optimization passes might move the *_BLOCK notes away,
736          so we use a NOTE_INSN_DELETED as a placeholder.  */
737
738       {
739         rtx original_before_jump
740           = last_insn ? last_insn : get_last_insn ();
741         rtx start;
742         rtx end;
743         tree block;
744
745         block = make_node (BLOCK);
746         TREE_USED (block) = 1;
747
748         BLOCK_CHAIN (block)
749           = BLOCK_CHAIN (DECL_INITIAL (current_function_decl));
750         BLOCK_CHAIN (DECL_INITIAL (current_function_decl))
751           = block;
752
753         start_sequence ();
754         start = emit_note (NOTE_INSN_BLOCK_BEG);
755         NOTE_BLOCK (start) = block;
756         fixup->before_jump = emit_note (NOTE_INSN_DELETED);
757         end = emit_note (NOTE_INSN_BLOCK_END);
758         NOTE_BLOCK (end) = block;
759         fixup->context = block;
760         end_sequence ();
761         emit_insn_after (start, original_before_jump);
762       }
763
764       fixup->block_start_count = current_block_start_count;
765       fixup->stack_level = 0;
766       fixup->cleanup_list_list
767         = ((block->data.block.outer_cleanups
768             || block->data.block.cleanups)
769            ? tree_cons (NULL_TREE, block->data.block.cleanups,
770                         block->data.block.outer_cleanups)
771            : 0);
772       fixup->next = goto_fixup_chain;
773       goto_fixup_chain = fixup;
774     }
775
776   return block != 0;
777 }
778 \f
779 /* Expand any needed fixups in the outputmost binding level of the
780    function.  FIRST_INSN is the first insn in the function.  */
781
782 void
783 expand_fixups (rtx first_insn)
784 {
785   fixup_gotos (NULL, NULL_RTX, NULL_TREE, first_insn, 0);
786 }
787
788 /* When exiting a binding contour, process all pending gotos requiring fixups.
789    THISBLOCK is the structure that describes the block being exited.
790    STACK_LEVEL is the rtx for the stack level to restore exiting this contour.
791    CLEANUP_LIST is a list of expressions to evaluate on exiting this contour.
792    FIRST_INSN is the insn that began this contour.
793
794    Gotos that jump out of this contour must restore the
795    stack level and do the cleanups before actually jumping.
796
797    DONT_JUMP_IN positive means report error if there is a jump into this
798    contour from before the beginning of the contour.  This is also done if
799    STACK_LEVEL is nonzero unless DONT_JUMP_IN is negative.  */
800
801 static void
802 fixup_gotos (struct nesting *thisblock, rtx stack_level,
803              tree cleanup_list, rtx first_insn, int dont_jump_in)
804 {
805   struct goto_fixup *f, *prev;
806
807   /* F is the fixup we are considering; PREV is the previous one.  */
808   /* We run this loop in two passes so that cleanups of exited blocks
809      are run first, and blocks that are exited are marked so
810      afterwards.  */
811
812   for (prev = 0, f = goto_fixup_chain; f; prev = f, f = f->next)
813     {
814       /* Test for a fixup that is inactive because it is already handled.  */
815       if (f->before_jump == 0)
816         {
817           /* Delete inactive fixup from the chain, if that is easy to do.  */
818           if (prev != 0)
819             prev->next = f->next;
820         }
821       /* Has this fixup's target label been defined?
822          If so, we can finalize it.  */
823       else if (PREV_INSN (f->target_rtl) != 0)
824         {
825           rtx cleanup_insns;
826
827           /* If this fixup jumped into this contour from before the beginning
828              of this contour, report an error.   This code used to use
829              the first non-label insn after f->target_rtl, but that's
830              wrong since such can be added, by things like put_var_into_stack
831              and have INSN_UIDs that are out of the range of the block.  */
832           /* ??? Bug: this does not detect jumping in through intermediate
833              blocks that have stack levels or cleanups.
834              It detects only a problem with the innermost block
835              around the label.  */
836           if (f->target != 0
837               && (dont_jump_in > 0 || (dont_jump_in == 0 && stack_level)
838                   || cleanup_list)
839               && INSN_UID (first_insn) < INSN_UID (f->target_rtl)
840               && INSN_UID (first_insn) > INSN_UID (f->before_jump)
841               && ! DECL_ERROR_ISSUED (f->target))
842             {
843               error ("%Jlabel '%D' used before containing binding contour",
844                      f->target, f->target);
845               /* Prevent multiple errors for one label.  */
846               DECL_ERROR_ISSUED (f->target) = 1;
847             }
848
849           /* We will expand the cleanups into a sequence of their own and
850              then later on we will attach this new sequence to the insn
851              stream just ahead of the actual jump insn.  */
852
853           start_sequence ();
854
855           /* Temporarily restore the lexical context where we will
856              logically be inserting the fixup code.  We do this for the
857              sake of getting the debugging information right.  */
858
859           lang_hooks.decls.pushlevel (0);
860           lang_hooks.decls.set_block (f->context);
861
862           /* Expand the cleanups for blocks this jump exits.  */
863           if (f->cleanup_list_list)
864             {
865               tree lists;
866               for (lists = f->cleanup_list_list; lists; lists = TREE_CHAIN (lists))
867                 /* Marked elements correspond to blocks that have been closed.
868                    Do their cleanups.  */
869                 if (TREE_ADDRESSABLE (lists)
870                     && TREE_VALUE (lists) != 0)
871                   {
872                     expand_cleanups (TREE_VALUE (lists), 1, 1);
873                     /* Pop any pushes done in the cleanups,
874                        in case function is about to return.  */
875                     do_pending_stack_adjust ();
876                   }
877             }
878
879           /* Restore stack level for the biggest contour that this
880              jump jumps out of.  */
881           if (f->stack_level
882               && ! (f->target_rtl == return_label
883                     && ((TREE_CODE (TREE_TYPE (current_function_decl))
884                          == FUNCTION_TYPE)
885                         && (TYPE_RETURNS_STACK_DEPRESSED
886                             (TREE_TYPE (current_function_decl))))))
887             emit_stack_restore (SAVE_BLOCK, f->stack_level, f->before_jump);
888
889           /* Finish up the sequence containing the insns which implement the
890              necessary cleanups, and then attach that whole sequence to the
891              insn stream just ahead of the actual jump insn.  Attaching it
892              at that point insures that any cleanups which are in fact
893              implicit C++ object destructions (which must be executed upon
894              leaving the block) appear (to the debugger) to be taking place
895              in an area of the generated code where the object(s) being
896              destructed are still "in scope".  */
897
898           cleanup_insns = get_insns ();
899           lang_hooks.decls.poplevel (1, 0, 0);
900
901           end_sequence ();
902           emit_insn_after (cleanup_insns, f->before_jump);
903
904           f->before_jump = 0;
905         }
906     }
907
908   /* For any still-undefined labels, do the cleanups for this block now.
909      We must do this now since items in the cleanup list may go out
910      of scope when the block ends.  */
911   for (prev = 0, f = goto_fixup_chain; f; prev = f, f = f->next)
912     if (f->before_jump != 0
913         && PREV_INSN (f->target_rtl) == 0
914         /* Label has still not appeared.  If we are exiting a block with
915            a stack level to restore, that started before the fixup,
916            mark this stack level as needing restoration
917            when the fixup is later finalized.  */
918         && thisblock != 0
919         /* Note: if THISBLOCK == 0 and we have a label that hasn't appeared, it
920            means the label is undefined.  That's erroneous, but possible.  */
921         && (thisblock->data.block.block_start_count
922             <= f->block_start_count))
923       {
924         tree lists = f->cleanup_list_list;
925         rtx cleanup_insns;
926
927         for (; lists; lists = TREE_CHAIN (lists))
928           /* If the following elt. corresponds to our containing block
929              then the elt. must be for this block.  */
930           if (TREE_CHAIN (lists) == thisblock->data.block.outer_cleanups)
931             {
932               start_sequence ();
933               lang_hooks.decls.pushlevel (0);
934               lang_hooks.decls.set_block (f->context);
935               expand_cleanups (TREE_VALUE (lists), 1, 1);
936               do_pending_stack_adjust ();
937               cleanup_insns = get_insns ();
938               lang_hooks.decls.poplevel (1, 0, 0);
939               end_sequence ();
940               if (cleanup_insns != 0)
941                 f->before_jump
942                   = emit_insn_after (cleanup_insns, f->before_jump);
943
944               f->cleanup_list_list = TREE_CHAIN (lists);
945             }
946
947         if (stack_level)
948           f->stack_level = stack_level;
949       }
950 }
951 \f
952 /* Return the number of times character C occurs in string S.  */
953 static int
954 n_occurrences (int c, const char *s)
955 {
956   int n = 0;
957   while (*s)
958     n += (*s++ == c);
959   return n;
960 }
961 \f
962 /* Generate RTL for an asm statement (explicit assembler code).
963    STRING is a STRING_CST node containing the assembler code text,
964    or an ADDR_EXPR containing a STRING_CST.  VOL nonzero means the
965    insn is volatile; don't optimize it.  */
966
967 void
968 expand_asm (tree string, int vol)
969 {
970   rtx body;
971
972   if (TREE_CODE (string) == ADDR_EXPR)
973     string = TREE_OPERAND (string, 0);
974
975   body = gen_rtx_ASM_INPUT (VOIDmode, TREE_STRING_POINTER (string));
976
977   MEM_VOLATILE_P (body) = vol;
978
979   emit_insn (body);
980
981   clear_last_expr ();
982 }
983
984 /* Parse the output constraint pointed to by *CONSTRAINT_P.  It is the
985    OPERAND_NUMth output operand, indexed from zero.  There are NINPUTS
986    inputs and NOUTPUTS outputs to this extended-asm.  Upon return,
987    *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
988    memory operand.  Similarly, *ALLOWS_REG will be TRUE iff the
989    constraint allows the use of a register operand.  And, *IS_INOUT
990    will be true if the operand is read-write, i.e., if it is used as
991    an input as well as an output.  If *CONSTRAINT_P is not in
992    canonical form, it will be made canonical.  (Note that `+' will be
993    replaced with `=' as part of this process.)
994
995    Returns TRUE if all went well; FALSE if an error occurred.  */
996
997 bool
998 parse_output_constraint (const char **constraint_p, int operand_num,
999                          int ninputs, int noutputs, bool *allows_mem,
1000                          bool *allows_reg, bool *is_inout)
1001 {
1002   const char *constraint = *constraint_p;
1003   const char *p;
1004
1005   /* Assume the constraint doesn't allow the use of either a register
1006      or memory.  */
1007   *allows_mem = false;
1008   *allows_reg = false;
1009
1010   /* Allow the `=' or `+' to not be at the beginning of the string,
1011      since it wasn't explicitly documented that way, and there is a
1012      large body of code that puts it last.  Swap the character to
1013      the front, so as not to uglify any place else.  */
1014   p = strchr (constraint, '=');
1015   if (!p)
1016     p = strchr (constraint, '+');
1017
1018   /* If the string doesn't contain an `=', issue an error
1019      message.  */
1020   if (!p)
1021     {
1022       error ("output operand constraint lacks `='");
1023       return false;
1024     }
1025
1026   /* If the constraint begins with `+', then the operand is both read
1027      from and written to.  */
1028   *is_inout = (*p == '+');
1029
1030   /* Canonicalize the output constraint so that it begins with `='.  */
1031   if (p != constraint || is_inout)
1032     {
1033       char *buf;
1034       size_t c_len = strlen (constraint);
1035
1036       if (p != constraint)
1037         warning ("output constraint `%c' for operand %d is not at the beginning",
1038                  *p, operand_num);
1039
1040       /* Make a copy of the constraint.  */
1041       buf = alloca (c_len + 1);
1042       strcpy (buf, constraint);
1043       /* Swap the first character and the `=' or `+'.  */
1044       buf[p - constraint] = buf[0];
1045       /* Make sure the first character is an `='.  (Until we do this,
1046          it might be a `+'.)  */
1047       buf[0] = '=';
1048       /* Replace the constraint with the canonicalized string.  */
1049       *constraint_p = ggc_alloc_string (buf, c_len);
1050       constraint = *constraint_p;
1051     }
1052
1053   /* Loop through the constraint string.  */
1054   for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
1055     switch (*p)
1056       {
1057       case '+':
1058       case '=':
1059         error ("operand constraint contains incorrectly positioned '+' or '='");
1060         return false;
1061
1062       case '%':
1063         if (operand_num + 1 == ninputs + noutputs)
1064           {
1065             error ("`%%' constraint used with last operand");
1066             return false;
1067           }
1068         break;
1069
1070       case 'V':  case 'm':  case 'o':
1071         *allows_mem = true;
1072         break;
1073
1074       case '?':  case '!':  case '*':  case '&':  case '#':
1075       case 'E':  case 'F':  case 'G':  case 'H':
1076       case 's':  case 'i':  case 'n':
1077       case 'I':  case 'J':  case 'K':  case 'L':  case 'M':
1078       case 'N':  case 'O':  case 'P':  case ',':
1079         break;
1080
1081       case '0':  case '1':  case '2':  case '3':  case '4':
1082       case '5':  case '6':  case '7':  case '8':  case '9':
1083       case '[':
1084         error ("matching constraint not valid in output operand");
1085         return false;
1086
1087       case '<':  case '>':
1088         /* ??? Before flow, auto inc/dec insns are not supposed to exist,
1089            excepting those that expand_call created.  So match memory
1090            and hope.  */
1091         *allows_mem = true;
1092         break;
1093
1094       case 'g':  case 'X':
1095         *allows_reg = true;
1096         *allows_mem = true;
1097         break;
1098
1099       case 'p': case 'r':
1100         *allows_reg = true;
1101         break;
1102
1103       default:
1104         if (!ISALPHA (*p))
1105           break;
1106         if (REG_CLASS_FROM_CONSTRAINT (*p, p) != NO_REGS)
1107           *allows_reg = true;
1108 #ifdef EXTRA_CONSTRAINT_STR
1109         else if (EXTRA_ADDRESS_CONSTRAINT (*p, p))
1110           *allows_reg = true;
1111         else if (EXTRA_MEMORY_CONSTRAINT (*p, p))
1112           *allows_mem = true;
1113         else
1114           {
1115             /* Otherwise we can't assume anything about the nature of
1116                the constraint except that it isn't purely registers.
1117                Treat it like "g" and hope for the best.  */
1118             *allows_reg = true;
1119             *allows_mem = true;
1120           }
1121 #endif
1122         break;
1123       }
1124
1125   return true;
1126 }
1127
1128 /* Similar, but for input constraints.  */
1129
1130 bool
1131 parse_input_constraint (const char **constraint_p, int input_num,
1132                         int ninputs, int noutputs, int ninout,
1133                         const char * const * constraints,
1134                         bool *allows_mem, bool *allows_reg)
1135 {
1136   const char *constraint = *constraint_p;
1137   const char *orig_constraint = constraint;
1138   size_t c_len = strlen (constraint);
1139   size_t j;
1140   bool saw_match = false;
1141
1142   /* Assume the constraint doesn't allow the use of either
1143      a register or memory.  */
1144   *allows_mem = false;
1145   *allows_reg = false;
1146
1147   /* Make sure constraint has neither `=', `+', nor '&'.  */
1148
1149   for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
1150     switch (constraint[j])
1151       {
1152       case '+':  case '=':  case '&':
1153         if (constraint == orig_constraint)
1154           {
1155             error ("input operand constraint contains `%c'", constraint[j]);
1156             return false;
1157           }
1158         break;
1159
1160       case '%':
1161         if (constraint == orig_constraint
1162             && input_num + 1 == ninputs - ninout)
1163           {
1164             error ("`%%' constraint used with last operand");
1165             return false;
1166           }
1167         break;
1168
1169       case 'V':  case 'm':  case 'o':
1170         *allows_mem = true;
1171         break;
1172
1173       case '<':  case '>':
1174       case '?':  case '!':  case '*':  case '#':
1175       case 'E':  case 'F':  case 'G':  case 'H':
1176       case 's':  case 'i':  case 'n':
1177       case 'I':  case 'J':  case 'K':  case 'L':  case 'M':
1178       case 'N':  case 'O':  case 'P':  case ',':
1179         break;
1180
1181         /* Whether or not a numeric constraint allows a register is
1182            decided by the matching constraint, and so there is no need
1183            to do anything special with them.  We must handle them in
1184            the default case, so that we don't unnecessarily force
1185            operands to memory.  */
1186       case '0':  case '1':  case '2':  case '3':  case '4':
1187       case '5':  case '6':  case '7':  case '8':  case '9':
1188         {
1189           char *end;
1190           unsigned long match;
1191
1192           saw_match = true;
1193
1194           match = strtoul (constraint + j, &end, 10);
1195           if (match >= (unsigned long) noutputs)
1196             {
1197               error ("matching constraint references invalid operand number");
1198               return false;
1199             }
1200
1201           /* Try and find the real constraint for this dup.  Only do this
1202              if the matching constraint is the only alternative.  */
1203           if (*end == '\0'
1204               && (j == 0 || (j == 1 && constraint[0] == '%')))
1205             {
1206               constraint = constraints[match];
1207               *constraint_p = constraint;
1208               c_len = strlen (constraint);
1209               j = 0;
1210               /* ??? At the end of the loop, we will skip the first part of
1211                  the matched constraint.  This assumes not only that the
1212                  other constraint is an output constraint, but also that
1213                  the '=' or '+' come first.  */
1214               break;
1215             }
1216           else
1217             j = end - constraint;
1218           /* Anticipate increment at end of loop.  */
1219           j--;
1220         }
1221         /* Fall through.  */
1222
1223       case 'p':  case 'r':
1224         *allows_reg = true;
1225         break;
1226
1227       case 'g':  case 'X':
1228         *allows_reg = true;
1229         *allows_mem = true;
1230         break;
1231
1232       default:
1233         if (! ISALPHA (constraint[j]))
1234           {
1235             error ("invalid punctuation `%c' in constraint", constraint[j]);
1236             return false;
1237           }
1238         if (REG_CLASS_FROM_CONSTRAINT (constraint[j], constraint + j)
1239             != NO_REGS)
1240           *allows_reg = true;
1241 #ifdef EXTRA_CONSTRAINT_STR
1242         else if (EXTRA_ADDRESS_CONSTRAINT (constraint[j], constraint + j))
1243           *allows_reg = true;
1244         else if (EXTRA_MEMORY_CONSTRAINT (constraint[j], constraint + j))
1245           *allows_mem = true;
1246         else
1247           {
1248             /* Otherwise we can't assume anything about the nature of
1249                the constraint except that it isn't purely registers.
1250                Treat it like "g" and hope for the best.  */
1251             *allows_reg = true;
1252             *allows_mem = true;
1253           }
1254 #endif
1255         break;
1256       }
1257
1258   if (saw_match && !*allows_reg)
1259     warning ("matching constraint does not allow a register");
1260
1261   return true;
1262 }
1263
1264 /* INPUT is one of the input operands from EXPR, an ASM_EXPR.  Returns true
1265    if it is an operand which must be passed in memory (i.e. an "m"
1266    constraint), false otherwise.  */
1267
1268 bool
1269 asm_op_is_mem_input (tree input, tree expr)
1270 {
1271   const char *constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (input)));
1272   tree outputs = ASM_OUTPUTS (expr);
1273   int noutputs = list_length (outputs);
1274   const char **constraints
1275     = (const char **) alloca ((noutputs) * sizeof (const char *));
1276   int i = 0;
1277   bool allows_mem, allows_reg;
1278   tree t;
1279
1280   /* Collect output constraints.  */
1281   for (t = outputs; t ; t = TREE_CHAIN (t), i++)
1282     constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1283
1284   /* We pass 0 for input_num, ninputs and ninout; they are only used for
1285      error checking which will be done at expand time.  */
1286   parse_input_constraint (&constraint, 0, 0, noutputs, 0, constraints,
1287                           &allows_mem, &allows_reg);
1288   return (!allows_reg && allows_mem);
1289 }
1290
1291 /* Check for overlap between registers marked in CLOBBERED_REGS and
1292    anything inappropriate in DECL.  Emit error and return TRUE for error,
1293    FALSE for ok.  */
1294
1295 static bool
1296 decl_conflicts_with_clobbers_p (tree decl, const HARD_REG_SET clobbered_regs)
1297 {
1298   /* Conflicts between asm-declared register variables and the clobber
1299      list are not allowed.  */
1300   if ((TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == PARM_DECL)
1301       && DECL_REGISTER (decl)
1302       && REG_P (DECL_RTL (decl))
1303       && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
1304     {
1305       rtx reg = DECL_RTL (decl);
1306       unsigned int regno;
1307
1308       for (regno = REGNO (reg);
1309            regno < (REGNO (reg)
1310                     + hard_regno_nregs[REGNO (reg)][GET_MODE (reg)]);
1311            regno++)
1312         if (TEST_HARD_REG_BIT (clobbered_regs, regno))
1313           {
1314             error ("asm-specifier for variable `%s' conflicts with asm clobber list",
1315                    IDENTIFIER_POINTER (DECL_NAME (decl)));
1316
1317             /* Reset registerness to stop multiple errors emitted for a
1318                single variable.  */
1319             DECL_REGISTER (decl) = 0;
1320             return true;
1321           }
1322     }
1323   return false;
1324 }
1325
1326 /* Generate RTL for an asm statement with arguments.
1327    STRING is the instruction template.
1328    OUTPUTS is a list of output arguments (lvalues); INPUTS a list of inputs.
1329    Each output or input has an expression in the TREE_VALUE and
1330    and a tree list in TREE_PURPOSE which in turn contains a constraint
1331    name in TREE_VALUE (or NULL_TREE) and a constraint string
1332    in TREE_PURPOSE.
1333    CLOBBERS is a list of STRING_CST nodes each naming a hard register
1334    that is clobbered by this insn.
1335
1336    Not all kinds of lvalue that may appear in OUTPUTS can be stored directly.
1337    Some elements of OUTPUTS may be replaced with trees representing temporary
1338    values.  The caller should copy those temporary values to the originally
1339    specified lvalues.
1340
1341    VOL nonzero means the insn is volatile; don't optimize it.  */
1342
1343 void
1344 expand_asm_operands (tree string, tree outputs, tree inputs,
1345                      tree clobbers, int vol, location_t locus)
1346 {
1347   rtvec argvec, constraintvec;
1348   rtx body;
1349   int ninputs = list_length (inputs);
1350   int noutputs = list_length (outputs);
1351   int ninout;
1352   int nclobbers;
1353   HARD_REG_SET clobbered_regs;
1354   int clobber_conflict_found = 0;
1355   tree tail;
1356   tree t;
1357   int i;
1358   /* Vector of RTX's of evaluated output operands.  */
1359   rtx *output_rtx = alloca (noutputs * sizeof (rtx));
1360   int *inout_opnum = alloca (noutputs * sizeof (int));
1361   rtx *real_output_rtx = alloca (noutputs * sizeof (rtx));
1362   enum machine_mode *inout_mode
1363     = alloca (noutputs * sizeof (enum machine_mode));
1364   const char **constraints
1365     = alloca ((noutputs + ninputs) * sizeof (const char *));
1366   int old_generating_concat_p = generating_concat_p;
1367
1368   /* An ASM with no outputs needs to be treated as volatile, for now.  */
1369   if (noutputs == 0)
1370     vol = 1;
1371
1372   if (! check_operand_nalternatives (outputs, inputs))
1373     return;
1374
1375   string = resolve_asm_operand_names (string, outputs, inputs);
1376
1377   /* Collect constraints.  */
1378   i = 0;
1379   for (t = outputs; t ; t = TREE_CHAIN (t), i++)
1380     constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1381   for (t = inputs; t ; t = TREE_CHAIN (t), i++)
1382     constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1383
1384   /* Sometimes we wish to automatically clobber registers across an asm.
1385      Case in point is when the i386 backend moved from cc0 to a hard reg --
1386      maintaining source-level compatibility means automatically clobbering
1387      the flags register.  */
1388   clobbers = targetm.md_asm_clobbers (clobbers);
1389
1390   /* Count the number of meaningful clobbered registers, ignoring what
1391      we would ignore later.  */
1392   nclobbers = 0;
1393   CLEAR_HARD_REG_SET (clobbered_regs);
1394   for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
1395     {
1396       const char *regname = TREE_STRING_POINTER (TREE_VALUE (tail));
1397
1398       i = decode_reg_name (regname);
1399       if (i >= 0 || i == -4)
1400         ++nclobbers;
1401       else if (i == -2)
1402         error ("unknown register name `%s' in `asm'", regname);
1403
1404       /* Mark clobbered registers.  */
1405       if (i >= 0)
1406         {
1407           /* Clobbering the PIC register is an error */
1408           if (i == (int) PIC_OFFSET_TABLE_REGNUM)
1409             {
1410               error ("PIC register `%s' clobbered in `asm'", regname);
1411               return;
1412             }
1413
1414           SET_HARD_REG_BIT (clobbered_regs, i);
1415         }
1416     }
1417
1418   clear_last_expr ();
1419
1420   /* First pass over inputs and outputs checks validity and sets
1421      mark_addressable if needed.  */
1422
1423   ninout = 0;
1424   for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1425     {
1426       tree val = TREE_VALUE (tail);
1427       tree type = TREE_TYPE (val);
1428       const char *constraint;
1429       bool is_inout;
1430       bool allows_reg;
1431       bool allows_mem;
1432
1433       /* If there's an erroneous arg, emit no insn.  */
1434       if (type == error_mark_node)
1435         return;
1436
1437       /* Try to parse the output constraint.  If that fails, there's
1438          no point in going further.  */
1439       constraint = constraints[i];
1440       if (!parse_output_constraint (&constraint, i, ninputs, noutputs,
1441                                     &allows_mem, &allows_reg, &is_inout))
1442         return;
1443
1444       if (! allows_reg
1445           && (allows_mem
1446               || is_inout
1447               || (DECL_P (val)
1448                   && REG_P (DECL_RTL (val))
1449                   && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type))))
1450         lang_hooks.mark_addressable (val);
1451
1452       if (is_inout)
1453         ninout++;
1454     }
1455
1456   ninputs += ninout;
1457   if (ninputs + noutputs > MAX_RECOG_OPERANDS)
1458     {
1459       error ("more than %d operands in `asm'", MAX_RECOG_OPERANDS);
1460       return;
1461     }
1462
1463   for (i = 0, tail = inputs; tail; i++, tail = TREE_CHAIN (tail))
1464     {
1465       bool allows_reg, allows_mem;
1466       const char *constraint;
1467
1468       /* If there's an erroneous arg, emit no insn, because the ASM_INPUT
1469          would get VOIDmode and that could cause a crash in reload.  */
1470       if (TREE_TYPE (TREE_VALUE (tail)) == error_mark_node)
1471         return;
1472
1473       constraint = constraints[i + noutputs];
1474       if (! parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
1475                                     constraints, &allows_mem, &allows_reg))
1476         return;
1477
1478       if (! allows_reg && allows_mem)
1479         lang_hooks.mark_addressable (TREE_VALUE (tail));
1480     }
1481
1482   /* Second pass evaluates arguments.  */
1483
1484   ninout = 0;
1485   for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1486     {
1487       tree val = TREE_VALUE (tail);
1488       tree type = TREE_TYPE (val);
1489       bool is_inout;
1490       bool allows_reg;
1491       bool allows_mem;
1492       rtx op;
1493
1494       if (!parse_output_constraint (&constraints[i], i, ninputs,
1495                                     noutputs, &allows_mem, &allows_reg,
1496                                     &is_inout))
1497         abort ();
1498
1499       /* If an output operand is not a decl or indirect ref and our constraint
1500          allows a register, make a temporary to act as an intermediate.
1501          Make the asm insn write into that, then our caller will copy it to
1502          the real output operand.  Likewise for promoted variables.  */
1503
1504       generating_concat_p = 0;
1505
1506       real_output_rtx[i] = NULL_RTX;
1507       if ((TREE_CODE (val) == INDIRECT_REF
1508            && allows_mem)
1509           || (DECL_P (val)
1510               && (allows_mem || REG_P (DECL_RTL (val)))
1511               && ! (REG_P (DECL_RTL (val))
1512                     && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type)))
1513           || ! allows_reg
1514           || is_inout)
1515         {
1516           op = expand_expr (val, NULL_RTX, VOIDmode, EXPAND_WRITE);
1517           if (GET_CODE (op) == MEM)
1518             op = validize_mem (op);
1519
1520           if (! allows_reg && GET_CODE (op) != MEM)
1521             error ("output number %d not directly addressable", i);
1522           if ((! allows_mem && GET_CODE (op) == MEM)
1523               || GET_CODE (op) == CONCAT)
1524             {
1525               real_output_rtx[i] = protect_from_queue (op, 1);
1526               op = gen_reg_rtx (GET_MODE (op));
1527               if (is_inout)
1528                 emit_move_insn (op, real_output_rtx[i]);
1529             }
1530         }
1531       else
1532         {
1533           op = assign_temp (type, 0, 0, 1);
1534           op = validize_mem (op);
1535           TREE_VALUE (tail) = make_tree (type, op);
1536         }
1537       output_rtx[i] = op;
1538
1539       generating_concat_p = old_generating_concat_p;
1540
1541       if (is_inout)
1542         {
1543           inout_mode[ninout] = TYPE_MODE (type);
1544           inout_opnum[ninout++] = i;
1545         }
1546
1547       if (decl_conflicts_with_clobbers_p (val, clobbered_regs))
1548         clobber_conflict_found = 1;
1549     }
1550
1551   /* Make vectors for the expression-rtx, constraint strings,
1552      and named operands.  */
1553
1554   argvec = rtvec_alloc (ninputs);
1555   constraintvec = rtvec_alloc (ninputs);
1556
1557   body = gen_rtx_ASM_OPERANDS ((noutputs == 0 ? VOIDmode
1558                                 : GET_MODE (output_rtx[0])),
1559                                TREE_STRING_POINTER (string),
1560                                empty_string, 0, argvec, constraintvec,
1561                                locus);
1562
1563   MEM_VOLATILE_P (body) = vol;
1564
1565   /* Eval the inputs and put them into ARGVEC.
1566      Put their constraints into ASM_INPUTs and store in CONSTRAINTS.  */
1567
1568   for (i = 0, tail = inputs; tail; tail = TREE_CHAIN (tail), ++i)
1569     {
1570       bool allows_reg, allows_mem;
1571       const char *constraint;
1572       tree val, type;
1573       rtx op;
1574
1575       constraint = constraints[i + noutputs];
1576       if (! parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
1577                                     constraints, &allows_mem, &allows_reg))
1578         abort ();
1579
1580       generating_concat_p = 0;
1581
1582       val = TREE_VALUE (tail);
1583       type = TREE_TYPE (val);
1584       op = expand_expr (val, NULL_RTX, VOIDmode,
1585                         (allows_mem && !allows_reg
1586                          ? EXPAND_MEMORY : EXPAND_NORMAL));
1587
1588       /* Never pass a CONCAT to an ASM.  */
1589       if (GET_CODE (op) == CONCAT)
1590         op = force_reg (GET_MODE (op), op);
1591       else if (GET_CODE (op) == MEM)
1592         op = validize_mem (op);
1593
1594       if (asm_operand_ok (op, constraint) <= 0)
1595         {
1596           if (allows_reg)
1597             op = force_reg (TYPE_MODE (type), op);
1598           else if (!allows_mem)
1599             warning ("asm operand %d probably doesn't match constraints",
1600                      i + noutputs);
1601           else if (GET_CODE (op) == MEM)
1602             {
1603               /* We won't recognize either volatile memory or memory
1604                  with a queued address as available a memory_operand
1605                  at this point.  Ignore it: clearly this *is* a memory.  */
1606             }
1607           else
1608             {
1609               warning ("use of memory input without lvalue in "
1610                        "asm operand %d is deprecated", i + noutputs);
1611
1612               if (CONSTANT_P (op))
1613                 {
1614                   rtx mem = force_const_mem (TYPE_MODE (type), op);
1615                   if (mem)
1616                     op = validize_mem (mem);
1617                   else
1618                     op = force_reg (TYPE_MODE (type), op);
1619                 }
1620               if (REG_P (op)
1621                   || GET_CODE (op) == SUBREG
1622                   || GET_CODE (op) == ADDRESSOF
1623                   || GET_CODE (op) == CONCAT)
1624                 {
1625                   tree qual_type = build_qualified_type (type,
1626                                                          (TYPE_QUALS (type)
1627                                                           | TYPE_QUAL_CONST));
1628                   rtx memloc = assign_temp (qual_type, 1, 1, 1);
1629                   memloc = validize_mem (memloc);
1630                   emit_move_insn (memloc, op);
1631                   op = memloc;
1632                 }
1633             }
1634         }
1635
1636       generating_concat_p = old_generating_concat_p;
1637       ASM_OPERANDS_INPUT (body, i) = op;
1638
1639       ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, i)
1640         = gen_rtx_ASM_INPUT (TYPE_MODE (type), constraints[i + noutputs]);
1641
1642       if (decl_conflicts_with_clobbers_p (val, clobbered_regs))
1643         clobber_conflict_found = 1;
1644     }
1645
1646   /* Protect all the operands from the queue now that they have all been
1647      evaluated.  */
1648
1649   generating_concat_p = 0;
1650
1651   for (i = 0; i < ninputs - ninout; i++)
1652     ASM_OPERANDS_INPUT (body, i)
1653       = protect_from_queue (ASM_OPERANDS_INPUT (body, i), 0);
1654
1655   for (i = 0; i < noutputs; i++)
1656     output_rtx[i] = protect_from_queue (output_rtx[i], 1);
1657
1658   /* For in-out operands, copy output rtx to input rtx.  */
1659   for (i = 0; i < ninout; i++)
1660     {
1661       int j = inout_opnum[i];
1662       char buffer[16];
1663
1664       ASM_OPERANDS_INPUT (body, ninputs - ninout + i)
1665         = output_rtx[j];
1666
1667       sprintf (buffer, "%d", j);
1668       ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, ninputs - ninout + i)
1669         = gen_rtx_ASM_INPUT (inout_mode[i], ggc_strdup (buffer));
1670     }
1671
1672   generating_concat_p = old_generating_concat_p;
1673
1674   /* Now, for each output, construct an rtx
1675      (set OUTPUT (asm_operands INSN OUTPUTCONSTRAINT OUTPUTNUMBER
1676                                ARGVEC CONSTRAINTS OPNAMES))
1677      If there is more than one, put them inside a PARALLEL.  */
1678
1679   if (noutputs == 1 && nclobbers == 0)
1680     {
1681       ASM_OPERANDS_OUTPUT_CONSTRAINT (body) = constraints[0];
1682       emit_insn (gen_rtx_SET (VOIDmode, output_rtx[0], body));
1683     }
1684
1685   else if (noutputs == 0 && nclobbers == 0)
1686     {
1687       /* No output operands: put in a raw ASM_OPERANDS rtx.  */
1688       emit_insn (body);
1689     }
1690
1691   else
1692     {
1693       rtx obody = body;
1694       int num = noutputs;
1695
1696       if (num == 0)
1697         num = 1;
1698
1699       body = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num + nclobbers));
1700
1701       /* For each output operand, store a SET.  */
1702       for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1703         {
1704           XVECEXP (body, 0, i)
1705             = gen_rtx_SET (VOIDmode,
1706                            output_rtx[i],
1707                            gen_rtx_ASM_OPERANDS
1708                            (GET_MODE (output_rtx[i]),
1709                             TREE_STRING_POINTER (string),
1710                             constraints[i], i, argvec, constraintvec,
1711                             locus));
1712
1713           MEM_VOLATILE_P (SET_SRC (XVECEXP (body, 0, i))) = vol;
1714         }
1715
1716       /* If there are no outputs (but there are some clobbers)
1717          store the bare ASM_OPERANDS into the PARALLEL.  */
1718
1719       if (i == 0)
1720         XVECEXP (body, 0, i++) = obody;
1721
1722       /* Store (clobber REG) for each clobbered register specified.  */
1723
1724       for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
1725         {
1726           const char *regname = TREE_STRING_POINTER (TREE_VALUE (tail));
1727           int j = decode_reg_name (regname);
1728           rtx clobbered_reg;
1729
1730           if (j < 0)
1731             {
1732               if (j == -3)      /* `cc', which is not a register */
1733                 continue;
1734
1735               if (j == -4)      /* `memory', don't cache memory across asm */
1736                 {
1737                   XVECEXP (body, 0, i++)
1738                     = gen_rtx_CLOBBER (VOIDmode,
1739                                        gen_rtx_MEM
1740                                        (BLKmode,
1741                                         gen_rtx_SCRATCH (VOIDmode)));
1742                   continue;
1743                 }
1744
1745               /* Ignore unknown register, error already signaled.  */
1746               continue;
1747             }
1748
1749           /* Use QImode since that's guaranteed to clobber just one reg.  */
1750           clobbered_reg = gen_rtx_REG (QImode, j);
1751
1752           /* Do sanity check for overlap between clobbers and respectively
1753              input and outputs that hasn't been handled.  Such overlap
1754              should have been detected and reported above.  */
1755           if (!clobber_conflict_found)
1756             {
1757               int opno;
1758
1759               /* We test the old body (obody) contents to avoid tripping
1760                  over the under-construction body.  */
1761               for (opno = 0; opno < noutputs; opno++)
1762                 if (reg_overlap_mentioned_p (clobbered_reg, output_rtx[opno]))
1763                   internal_error ("asm clobber conflict with output operand");
1764
1765               for (opno = 0; opno < ninputs - ninout; opno++)
1766                 if (reg_overlap_mentioned_p (clobbered_reg,
1767                                              ASM_OPERANDS_INPUT (obody, opno)))
1768                   internal_error ("asm clobber conflict with input operand");
1769             }
1770
1771           XVECEXP (body, 0, i++)
1772             = gen_rtx_CLOBBER (VOIDmode, clobbered_reg);
1773         }
1774
1775       emit_insn (body);
1776     }
1777
1778   /* For any outputs that needed reloading into registers, spill them
1779      back to where they belong.  */
1780   for (i = 0; i < noutputs; ++i)
1781     if (real_output_rtx[i])
1782       emit_move_insn (real_output_rtx[i], output_rtx[i]);
1783
1784   free_temp_slots ();
1785 }
1786
1787 void
1788 expand_asm_expr (tree exp)
1789 {
1790   int noutputs, i;
1791   tree outputs, tail;
1792   tree *o;
1793
1794   if (ASM_INPUT_P (exp))
1795     {
1796       expand_asm (ASM_STRING (exp), ASM_VOLATILE_P (exp));
1797       return;
1798     }
1799
1800   outputs = ASM_OUTPUTS (exp);
1801   noutputs = list_length (outputs);
1802   /* o[I] is the place that output number I should be written.  */
1803   o = (tree *) alloca (noutputs * sizeof (tree));
1804
1805   /* Record the contents of OUTPUTS before it is modified.  */
1806   for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1807     o[i] = TREE_VALUE (tail);
1808
1809   /* Generate the ASM_OPERANDS insn; store into the TREE_VALUEs of
1810      OUTPUTS some trees for where the values were actually stored.  */
1811   expand_asm_operands (ASM_STRING (exp), outputs, ASM_INPUTS (exp),
1812                        ASM_CLOBBERS (exp), ASM_VOLATILE_P (exp),
1813                        input_location);
1814
1815   /* Copy all the intermediate outputs into the specified outputs.  */
1816   for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1817     {
1818       if (o[i] != TREE_VALUE (tail))
1819         {
1820           expand_assignment (o[i], TREE_VALUE (tail), 0);
1821           free_temp_slots ();
1822
1823           /* Restore the original value so that it's correct the next
1824              time we expand this function.  */
1825           TREE_VALUE (tail) = o[i];
1826         }
1827     }
1828
1829   /* Those MODIFY_EXPRs could do autoincrements.  */
1830   emit_queue ();
1831 }
1832
1833 /* A subroutine of expand_asm_operands.  Check that all operands have
1834    the same number of alternatives.  Return true if so.  */
1835
1836 static bool
1837 check_operand_nalternatives (tree outputs, tree inputs)
1838 {
1839   if (outputs || inputs)
1840     {
1841       tree tmp = TREE_PURPOSE (outputs ? outputs : inputs);
1842       int nalternatives
1843         = n_occurrences (',', TREE_STRING_POINTER (TREE_VALUE (tmp)));
1844       tree next = inputs;
1845
1846       if (nalternatives + 1 > MAX_RECOG_ALTERNATIVES)
1847         {
1848           error ("too many alternatives in `asm'");
1849           return false;
1850         }
1851
1852       tmp = outputs;
1853       while (tmp)
1854         {
1855           const char *constraint
1856             = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tmp)));
1857
1858           if (n_occurrences (',', constraint) != nalternatives)
1859             {
1860               error ("operand constraints for `asm' differ in number of alternatives");
1861               return false;
1862             }
1863
1864           if (TREE_CHAIN (tmp))
1865             tmp = TREE_CHAIN (tmp);
1866           else
1867             tmp = next, next = 0;
1868         }
1869     }
1870
1871   return true;
1872 }
1873
1874 /* A subroutine of expand_asm_operands.  Check that all operand names
1875    are unique.  Return true if so.  We rely on the fact that these names
1876    are identifiers, and so have been canonicalized by get_identifier,
1877    so all we need are pointer comparisons.  */
1878
1879 static bool
1880 check_unique_operand_names (tree outputs, tree inputs)
1881 {
1882   tree i, j;
1883
1884   for (i = outputs; i ; i = TREE_CHAIN (i))
1885     {
1886       tree i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1887       if (! i_name)
1888         continue;
1889
1890       for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1891         if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1892           goto failure;
1893     }
1894
1895   for (i = inputs; i ; i = TREE_CHAIN (i))
1896     {
1897       tree i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1898       if (! i_name)
1899         continue;
1900
1901       for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1902         if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1903           goto failure;
1904       for (j = outputs; j ; j = TREE_CHAIN (j))
1905         if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1906           goto failure;
1907     }
1908
1909   return true;
1910
1911  failure:
1912   error ("duplicate asm operand name '%s'",
1913          TREE_STRING_POINTER (TREE_PURPOSE (TREE_PURPOSE (i))));
1914   return false;
1915 }
1916
1917 /* A subroutine of expand_asm_operands.  Resolve the names of the operands
1918    in *POUTPUTS and *PINPUTS to numbers, and replace the name expansions in
1919    STRING and in the constraints to those numbers.  */
1920
1921 tree
1922 resolve_asm_operand_names (tree string, tree outputs, tree inputs)
1923 {
1924   char *buffer;
1925   char *p;
1926   const char *c;
1927   tree t;
1928
1929   check_unique_operand_names (outputs, inputs);
1930
1931   /* Substitute [<name>] in input constraint strings.  There should be no
1932      named operands in output constraints.  */
1933   for (t = inputs; t ; t = TREE_CHAIN (t))
1934     {
1935       c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1936       if (strchr (c, '[') != NULL)
1937         {
1938           p = buffer = xstrdup (c);
1939           while ((p = strchr (p, '[')) != NULL)
1940             p = resolve_operand_name_1 (p, outputs, inputs);
1941           TREE_VALUE (TREE_PURPOSE (t))
1942             = build_string (strlen (buffer), buffer);
1943           free (buffer);
1944         }
1945     }
1946
1947   /* Now check for any needed substitutions in the template.  */
1948   c = TREE_STRING_POINTER (string);
1949   while ((c = strchr (c, '%')) != NULL)
1950     {
1951       if (c[1] == '[')
1952         break;
1953       else if (ISALPHA (c[1]) && c[2] == '[')
1954         break;
1955       else
1956         {
1957           c += 1;
1958           continue;
1959         }
1960     }
1961
1962   if (c)
1963     {
1964       /* OK, we need to make a copy so we can perform the substitutions.
1965          Assume that we will not need extra space--we get to remove '['
1966          and ']', which means we cannot have a problem until we have more
1967          than 999 operands.  */
1968       buffer = xstrdup (TREE_STRING_POINTER (string));
1969       p = buffer + (c - TREE_STRING_POINTER (string));
1970       
1971       while ((p = strchr (p, '%')) != NULL)
1972         {
1973           if (p[1] == '[')
1974             p += 1;
1975           else if (ISALPHA (p[1]) && p[2] == '[')
1976             p += 2;
1977           else
1978             {
1979               p += 1;
1980               continue;
1981             }
1982
1983           p = resolve_operand_name_1 (p, outputs, inputs);
1984         }
1985
1986       string = build_string (strlen (buffer), buffer);
1987       free (buffer);
1988     }
1989
1990   return string;
1991 }
1992
1993 /* A subroutine of resolve_operand_names.  P points to the '[' for a
1994    potential named operand of the form [<name>].  In place, replace
1995    the name and brackets with a number.  Return a pointer to the
1996    balance of the string after substitution.  */
1997
1998 static char *
1999 resolve_operand_name_1 (char *p, tree outputs, tree inputs)
2000 {
2001   char *q;
2002   int op;
2003   tree t;
2004   size_t len;
2005
2006   /* Collect the operand name.  */
2007   q = strchr (p, ']');
2008   if (!q)
2009     {
2010       error ("missing close brace for named operand");
2011       return strchr (p, '\0');
2012     }
2013   len = q - p - 1;
2014
2015   /* Resolve the name to a number.  */
2016   for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
2017     {
2018       tree name = TREE_PURPOSE (TREE_PURPOSE (t));
2019       if (name)
2020         {
2021           const char *c = TREE_STRING_POINTER (name);
2022           if (strncmp (c, p + 1, len) == 0 && c[len] == '\0')
2023             goto found;
2024         }
2025     }
2026   for (t = inputs; t ; t = TREE_CHAIN (t), op++)
2027     {
2028       tree name = TREE_PURPOSE (TREE_PURPOSE (t));
2029       if (name)
2030         {
2031           const char *c = TREE_STRING_POINTER (name);
2032           if (strncmp (c, p + 1, len) == 0 && c[len] == '\0')
2033             goto found;
2034         }
2035     }
2036
2037   *q = '\0';
2038   error ("undefined named operand '%s'", p + 1);
2039   op = 0;
2040  found:
2041
2042   /* Replace the name with the number.  Unfortunately, not all libraries
2043      get the return value of sprintf correct, so search for the end of the
2044      generated string by hand.  */
2045   sprintf (p, "%d", op);
2046   p = strchr (p, '\0');
2047
2048   /* Verify the no extra buffer space assumption.  */
2049   if (p > q)
2050     abort ();
2051
2052   /* Shift the rest of the buffer down to fill the gap.  */
2053   memmove (p, q + 1, strlen (q + 1) + 1);
2054
2055   return p;
2056 }
2057 \f
2058 /* Generate RTL to evaluate the expression EXP
2059    and remember it in case this is the VALUE in a ({... VALUE; }) constr.
2060    Provided just for backward-compatibility.  expand_expr_stmt_value()
2061    should be used for new code.  */
2062
2063 void
2064 expand_expr_stmt (tree exp)
2065 {
2066   expand_expr_stmt_value (exp, -1, 1);
2067 }
2068
2069 /* Generate RTL to evaluate the expression EXP.  WANT_VALUE tells
2070    whether to (1) save the value of the expression, (0) discard it or
2071    (-1) use expr_stmts_for_value to tell.  The use of -1 is
2072    deprecated, and retained only for backward compatibility.  */
2073
2074 void
2075 expand_expr_stmt_value (tree exp, int want_value, int maybe_last)
2076 {
2077   rtx value;
2078   tree type;
2079   rtx alt_rtl = NULL;
2080
2081   if (want_value == -1)
2082     want_value = expr_stmts_for_value != 0;
2083
2084   /* If -Wextra, warn about statements with no side effects,
2085      except for an explicit cast to void (e.g. for assert()), and
2086      except for last statement in ({...}) where they may be useful.  */
2087   if (! want_value
2088       && (expr_stmts_for_value == 0 || ! maybe_last)
2089       && exp != error_mark_node
2090       && warn_unused_value)
2091     {
2092       if (TREE_SIDE_EFFECTS (exp))
2093         warn_if_unused_value (exp, emit_locus);
2094       else if (!VOID_TYPE_P (TREE_TYPE (exp)) && !TREE_NO_WARNING (exp))
2095         warning ("%Hstatement with no effect", &emit_locus);
2096     }
2097
2098   /* If EXP is of function type and we are expanding statements for
2099      value, convert it to pointer-to-function.  */
2100   if (want_value && TREE_CODE (TREE_TYPE (exp)) == FUNCTION_TYPE)
2101     exp = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (exp)), exp);
2102
2103   /* The call to `expand_expr' could cause last_expr_type and
2104      last_expr_value to get reset.  Therefore, we set last_expr_value
2105      and last_expr_type *after* calling expand_expr.  */
2106   value = expand_expr_real (exp, want_value ? NULL_RTX : const0_rtx,
2107                             VOIDmode, 0, &alt_rtl);
2108   type = TREE_TYPE (exp);
2109
2110   /* If all we do is reference a volatile value in memory,
2111      copy it to a register to be sure it is actually touched.  */
2112   if (value && GET_CODE (value) == MEM && TREE_THIS_VOLATILE (exp))
2113     {
2114       if (TYPE_MODE (type) == VOIDmode)
2115         ;
2116       else if (TYPE_MODE (type) != BLKmode)
2117         value = copy_to_reg (value);
2118       else
2119         {
2120           rtx lab = gen_label_rtx ();
2121
2122           /* Compare the value with itself to reference it.  */
2123           emit_cmp_and_jump_insns (value, value, EQ,
2124                                    expand_expr (TYPE_SIZE (type),
2125                                                 NULL_RTX, VOIDmode, 0),
2126                                    BLKmode, 0, lab);
2127           emit_label (lab);
2128         }
2129     }
2130
2131   /* If this expression is part of a ({...}) and is in memory, we may have
2132      to preserve temporaries.  */
2133   preserve_temp_slots (value);
2134
2135   /* Free any temporaries used to evaluate this expression.  Any temporary
2136      used as a result of this expression will already have been preserved
2137      above.  */
2138   free_temp_slots ();
2139
2140   if (want_value)
2141     {
2142       last_expr_value = value;
2143       last_expr_alt_rtl = alt_rtl;
2144       last_expr_type = type;
2145     }
2146
2147   emit_queue ();
2148 }
2149
2150 /* Warn if EXP contains any computations whose results are not used.
2151    Return 1 if a warning is printed; 0 otherwise.  LOCUS is the 
2152    (potential) location of the expression.  */
2153
2154 int
2155 warn_if_unused_value (tree exp, location_t locus)
2156 {
2157  restart:
2158   if (TREE_USED (exp))
2159     return 0;
2160
2161   /* Don't warn about void constructs.  This includes casting to void,
2162      void function calls, and statement expressions with a final cast
2163      to void.  */
2164   if (VOID_TYPE_P (TREE_TYPE (exp)))
2165     return 0;
2166
2167   if (EXPR_LOCUS (exp))
2168     locus = *EXPR_LOCUS (exp);
2169
2170   switch (TREE_CODE (exp))
2171     {
2172     case PREINCREMENT_EXPR:
2173     case POSTINCREMENT_EXPR:
2174     case PREDECREMENT_EXPR:
2175     case POSTDECREMENT_EXPR:
2176     case MODIFY_EXPR:
2177     case INIT_EXPR:
2178     case TARGET_EXPR:
2179     case CALL_EXPR:
2180     case RTL_EXPR:
2181     case TRY_CATCH_EXPR:
2182     case WITH_CLEANUP_EXPR:
2183     case EXIT_EXPR:
2184       return 0;
2185
2186     case BIND_EXPR:
2187       /* For a binding, warn if no side effect within it.  */
2188       exp = BIND_EXPR_BODY (exp);
2189       goto restart;
2190
2191     case SAVE_EXPR:
2192       exp = TREE_OPERAND (exp, 0);
2193       goto restart;
2194
2195     case TRUTH_ORIF_EXPR:
2196     case TRUTH_ANDIF_EXPR:
2197       /* In && or ||, warn if 2nd operand has no side effect.  */
2198       exp = TREE_OPERAND (exp, 1);
2199       goto restart;
2200
2201     case COMPOUND_EXPR:
2202       if (TREE_NO_WARNING (exp))
2203         return 0;
2204       if (warn_if_unused_value (TREE_OPERAND (exp, 0), locus))
2205         return 1;
2206       /* Let people do `(foo (), 0)' without a warning.  */
2207       if (TREE_CONSTANT (TREE_OPERAND (exp, 1)))
2208         return 0;
2209       exp = TREE_OPERAND (exp, 1);
2210       goto restart;
2211
2212     case NOP_EXPR:
2213     case CONVERT_EXPR:
2214     case NON_LVALUE_EXPR:
2215       /* Don't warn about conversions not explicit in the user's program.  */
2216       if (TREE_NO_WARNING (exp))
2217         return 0;
2218       /* Assignment to a cast usually results in a cast of a modify.
2219          Don't complain about that.  There can be an arbitrary number of
2220          casts before the modify, so we must loop until we find the first
2221          non-cast expression and then test to see if that is a modify.  */
2222       {
2223         tree tem = TREE_OPERAND (exp, 0);
2224
2225         while (TREE_CODE (tem) == CONVERT_EXPR || TREE_CODE (tem) == NOP_EXPR)
2226           tem = TREE_OPERAND (tem, 0);
2227
2228         if (TREE_CODE (tem) == MODIFY_EXPR || TREE_CODE (tem) == INIT_EXPR
2229             || TREE_CODE (tem) == CALL_EXPR)
2230           return 0;
2231       }
2232       goto maybe_warn;
2233
2234     case INDIRECT_REF:
2235       /* Don't warn about automatic dereferencing of references, since
2236          the user cannot control it.  */
2237       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == REFERENCE_TYPE)
2238         {
2239           exp = TREE_OPERAND (exp, 0);
2240           goto restart;
2241         }
2242       /* Fall through.  */
2243
2244     default:
2245       /* Referencing a volatile value is a side effect, so don't warn.  */
2246       if ((DECL_P (exp)
2247            || TREE_CODE_CLASS (TREE_CODE (exp)) == 'r')
2248           && TREE_THIS_VOLATILE (exp))
2249         return 0;
2250
2251       /* If this is an expression which has no operands, there is no value
2252          to be unused.  There are no such language-independent codes,
2253          but front ends may define such.  */
2254       if (TREE_CODE_CLASS (TREE_CODE (exp)) == 'e'
2255           && TREE_CODE_LENGTH (TREE_CODE (exp)) == 0)
2256         return 0;
2257
2258     maybe_warn:
2259       /* If this is an expression with side effects, don't warn.  */
2260       if (TREE_SIDE_EFFECTS (exp))
2261         return 0;
2262
2263       warning ("%Hvalue computed is not used", &locus);
2264       return 1;
2265     }
2266 }
2267
2268 /* Clear out the memory of the last expression evaluated.  */
2269
2270 void
2271 clear_last_expr (void)
2272 {
2273   last_expr_type = NULL_TREE;
2274   last_expr_value = NULL_RTX;
2275   last_expr_alt_rtl = NULL_RTX;
2276 }
2277
2278 /* Begin a statement-expression, i.e., a series of statements which
2279    may return a value.  Return the RTL_EXPR for this statement expr.
2280    The caller must save that value and pass it to
2281    expand_end_stmt_expr.  If HAS_SCOPE is nonzero, temporaries created
2282    in the statement-expression are deallocated at the end of the
2283    expression.  */
2284
2285 tree
2286 expand_start_stmt_expr (int has_scope)
2287 {
2288   tree t;
2289
2290   /* Make the RTL_EXPR node temporary, not momentary,
2291      so that rtl_expr_chain doesn't become garbage.  */
2292   t = make_node (RTL_EXPR);
2293   do_pending_stack_adjust ();
2294   if (has_scope)
2295     start_sequence_for_rtl_expr (t);
2296   else
2297     start_sequence ();
2298   NO_DEFER_POP;
2299   expr_stmts_for_value++;
2300   return t;
2301 }
2302
2303 /* Restore the previous state at the end of a statement that returns a value.
2304    Returns a tree node representing the statement's value and the
2305    insns to compute the value.
2306
2307    The nodes of that expression have been freed by now, so we cannot use them.
2308    But we don't want to do that anyway; the expression has already been
2309    evaluated and now we just want to use the value.  So generate a RTL_EXPR
2310    with the proper type and RTL value.
2311
2312    If the last substatement was not an expression,
2313    return something with type `void'.  */
2314
2315 tree
2316 expand_end_stmt_expr (tree t)
2317 {
2318   OK_DEFER_POP;
2319
2320   if (! last_expr_value || ! last_expr_type)
2321     {
2322       last_expr_value = const0_rtx;
2323       last_expr_alt_rtl = NULL_RTX;
2324       last_expr_type = void_type_node;
2325     }
2326   else if (!REG_P (last_expr_value) && ! CONSTANT_P (last_expr_value))
2327     /* Remove any possible QUEUED.  */
2328     last_expr_value = protect_from_queue (last_expr_value, 0);
2329
2330   emit_queue ();
2331
2332   TREE_TYPE (t) = last_expr_type;
2333   RTL_EXPR_RTL (t) = last_expr_value;
2334   RTL_EXPR_ALT_RTL (t) = last_expr_alt_rtl;
2335   RTL_EXPR_SEQUENCE (t) = get_insns ();
2336
2337   rtl_expr_chain = tree_cons (NULL_TREE, t, rtl_expr_chain);
2338
2339   end_sequence ();
2340
2341   /* Don't consider deleting this expr or containing exprs at tree level.  */
2342   TREE_SIDE_EFFECTS (t) = 1;
2343   /* Propagate volatility of the actual RTL expr.  */
2344   TREE_THIS_VOLATILE (t) = volatile_refs_p (last_expr_value);
2345
2346   clear_last_expr ();
2347   expr_stmts_for_value--;
2348
2349   return t;
2350 }
2351 \f
2352 /* Generate RTL for the start of an if-then.  COND is the expression
2353    whose truth should be tested.
2354
2355    If EXITFLAG is nonzero, this conditional is visible to
2356    `exit_something'.  */
2357
2358 void
2359 expand_start_cond (tree cond, int exitflag)
2360 {
2361   struct nesting *thiscond = ALLOC_NESTING ();
2362
2363   /* Make an entry on cond_stack for the cond we are entering.  */
2364
2365   thiscond->desc = COND_NESTING;
2366   thiscond->next = cond_stack;
2367   thiscond->all = nesting_stack;
2368   thiscond->depth = ++nesting_depth;
2369   thiscond->data.cond.next_label = gen_label_rtx ();
2370   /* Before we encounter an `else', we don't need a separate exit label
2371      unless there are supposed to be exit statements
2372      to exit this conditional.  */
2373   thiscond->exit_label = exitflag ? gen_label_rtx () : 0;
2374   thiscond->data.cond.endif_label = thiscond->exit_label;
2375   cond_stack = thiscond;
2376   nesting_stack = thiscond;
2377
2378   do_jump (cond, thiscond->data.cond.next_label, NULL_RTX);
2379 }
2380
2381 /* Generate RTL between then-clause and the elseif-clause
2382    of an if-then-elseif-....  */
2383
2384 void
2385 expand_start_elseif (tree cond)
2386 {
2387   if (cond_stack->data.cond.endif_label == 0)
2388     cond_stack->data.cond.endif_label = gen_label_rtx ();
2389   emit_jump (cond_stack->data.cond.endif_label);
2390   emit_label (cond_stack->data.cond.next_label);
2391   cond_stack->data.cond.next_label = gen_label_rtx ();
2392   do_jump (cond, cond_stack->data.cond.next_label, NULL_RTX);
2393 }
2394
2395 /* Generate RTL between the then-clause and the else-clause
2396    of an if-then-else.  */
2397
2398 void
2399 expand_start_else (void)
2400 {
2401   if (cond_stack->data.cond.endif_label == 0)
2402     cond_stack->data.cond.endif_label = gen_label_rtx ();
2403
2404   emit_jump (cond_stack->data.cond.endif_label);
2405   emit_label (cond_stack->data.cond.next_label);
2406   cond_stack->data.cond.next_label = 0;  /* No more _else or _elseif calls.  */
2407 }
2408
2409 /* After calling expand_start_else, turn this "else" into an "else if"
2410    by providing another condition.  */
2411
2412 void
2413 expand_elseif (tree cond)
2414 {
2415   cond_stack->data.cond.next_label = gen_label_rtx ();
2416   do_jump (cond, cond_stack->data.cond.next_label, NULL_RTX);
2417 }
2418
2419 /* Generate RTL for the end of an if-then.
2420    Pop the record for it off of cond_stack.  */
2421
2422 void
2423 expand_end_cond (void)
2424 {
2425   struct nesting *thiscond = cond_stack;
2426
2427   do_pending_stack_adjust ();
2428   if (thiscond->data.cond.next_label)
2429     emit_label (thiscond->data.cond.next_label);
2430   if (thiscond->data.cond.endif_label)
2431     emit_label (thiscond->data.cond.endif_label);
2432
2433   POPSTACK (cond_stack);
2434   clear_last_expr ();
2435 }
2436 \f
2437 /* Return nonzero if we should preserve sub-expressions as separate
2438    pseudos.  We never do so if we aren't optimizing.  We always do so
2439    if -fexpensive-optimizations.  */
2440
2441 int
2442 preserve_subexpressions_p (void)
2443 {
2444   if (flag_expensive_optimizations)
2445     return 1;
2446
2447   if (optimize == 0 || cfun == 0 || cfun->stmt == 0)
2448     return 0;
2449
2450   return 1;
2451 }
2452
2453 \f
2454 /* Generate RTL to return from the current function, with no value.
2455    (That is, we do not do anything about returning any value.)  */
2456
2457 void
2458 expand_null_return (void)
2459 {
2460   rtx last_insn;
2461
2462   last_insn = get_last_insn ();
2463
2464   /* If this function was declared to return a value, but we
2465      didn't, clobber the return registers so that they are not
2466      propagated live to the rest of the function.  */
2467   clobber_return_register ();
2468
2469   expand_null_return_1 (last_insn);
2470 }
2471
2472 /* Generate RTL to return directly from the current function.
2473    (That is, we bypass any return value.)  */
2474
2475 void
2476 expand_naked_return (void)
2477 {
2478   rtx last_insn, end_label;
2479
2480   last_insn = get_last_insn ();
2481   end_label = naked_return_label;
2482
2483   clear_pending_stack_adjust ();
2484   do_pending_stack_adjust ();
2485   clear_last_expr ();
2486
2487   if (end_label == 0)
2488     end_label = naked_return_label = gen_label_rtx ();
2489   expand_goto_internal (NULL_TREE, end_label, last_insn);
2490 }
2491
2492 /* Try to guess whether the value of return means error code.  */
2493 static enum br_predictor
2494 return_prediction (rtx val)
2495 {
2496   /* Different heuristics for pointers and scalars.  */
2497   if (POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
2498     {
2499       /* NULL is usually not returned.  */
2500       if (val == const0_rtx)
2501         return PRED_NULL_RETURN;
2502     }
2503   else
2504     {
2505       /* Negative return values are often used to indicate
2506          errors.  */
2507       if (GET_CODE (val) == CONST_INT
2508           && INTVAL (val) < 0)
2509         return PRED_NEGATIVE_RETURN;
2510       /* Constant return values are also usually erors,
2511          zero/one often mean booleans so exclude them from the
2512          heuristics.  */
2513       if (CONSTANT_P (val)
2514           && (val != const0_rtx && val != const1_rtx))
2515         return PRED_CONST_RETURN;
2516     }
2517   return PRED_NO_PREDICTION;
2518 }
2519
2520
2521 /* If the current function returns values in the most significant part
2522    of a register, shift return value VAL appropriately.  The mode of
2523    the function's return type is known not to be BLKmode.  */
2524
2525 static rtx
2526 shift_return_value (rtx val)
2527 {
2528   tree type;
2529
2530   type = TREE_TYPE (DECL_RESULT (current_function_decl));
2531   if (targetm.calls.return_in_msb (type))
2532     {
2533       rtx target;
2534       HOST_WIDE_INT shift;
2535
2536       target = DECL_RTL (DECL_RESULT (current_function_decl));
2537       shift = (GET_MODE_BITSIZE (GET_MODE (target))
2538                - BITS_PER_UNIT * int_size_in_bytes (type));
2539       if (shift > 0)
2540         val = expand_binop (GET_MODE (target), ashl_optab,
2541                             gen_lowpart (GET_MODE (target), val),
2542                             GEN_INT (shift), target, 1, OPTAB_WIDEN);
2543     }
2544   return val;
2545 }
2546
2547
2548 /* Generate RTL to return from the current function, with value VAL.  */
2549
2550 static void
2551 expand_value_return (rtx val)
2552 {
2553   rtx last_insn;
2554   rtx return_reg;
2555   enum br_predictor pred;
2556
2557   if (flag_guess_branch_prob
2558       && (pred = return_prediction (val)) != PRED_NO_PREDICTION)
2559     {
2560       /* Emit information for branch prediction.  */
2561       rtx note;
2562
2563       note = emit_note (NOTE_INSN_PREDICTION);
2564
2565       NOTE_PREDICTION (note) = NOTE_PREDICT (pred, NOT_TAKEN);
2566
2567     }
2568
2569   last_insn = get_last_insn ();
2570   return_reg = DECL_RTL (DECL_RESULT (current_function_decl));
2571
2572   /* Copy the value to the return location
2573      unless it's already there.  */
2574
2575   if (return_reg != val)
2576     {
2577       tree type = TREE_TYPE (DECL_RESULT (current_function_decl));
2578       if (targetm.calls.promote_function_return (TREE_TYPE (current_function_decl)))
2579       {
2580         int unsignedp = TYPE_UNSIGNED (type);
2581         enum machine_mode old_mode
2582           = DECL_MODE (DECL_RESULT (current_function_decl));
2583         enum machine_mode mode
2584           = promote_mode (type, old_mode, &unsignedp, 1);
2585
2586         if (mode != old_mode)
2587           val = convert_modes (mode, old_mode, val, unsignedp);
2588       }
2589       if (GET_CODE (return_reg) == PARALLEL)
2590         emit_group_load (return_reg, val, type, int_size_in_bytes (type));
2591       else
2592         emit_move_insn (return_reg, val);
2593     }
2594
2595   expand_null_return_1 (last_insn);
2596 }
2597
2598 /* Output a return with no value.  If LAST_INSN is nonzero,
2599    pretend that the return takes place after LAST_INSN.  */
2600
2601 static void
2602 expand_null_return_1 (rtx last_insn)
2603 {
2604   rtx end_label = cleanup_label ? cleanup_label : return_label;
2605
2606   clear_pending_stack_adjust ();
2607   do_pending_stack_adjust ();
2608   clear_last_expr ();
2609
2610   if (end_label == 0)
2611      end_label = return_label = gen_label_rtx ();
2612   expand_goto_internal (NULL_TREE, end_label, last_insn);
2613 }
2614 \f
2615 /* Generate RTL to evaluate the expression RETVAL and return it
2616    from the current function.  */
2617
2618 void
2619 expand_return (tree retval)
2620 {
2621   /* If there are any cleanups to be performed, then they will
2622      be inserted following LAST_INSN.  It is desirable
2623      that the last_insn, for such purposes, should be the
2624      last insn before computing the return value.  Otherwise, cleanups
2625      which call functions can clobber the return value.  */
2626   /* ??? rms: I think that is erroneous, because in C++ it would
2627      run destructors on variables that might be used in the subsequent
2628      computation of the return value.  */
2629   rtx last_insn = 0;
2630   rtx result_rtl;
2631   rtx val = 0;
2632   tree retval_rhs;
2633
2634   /* If function wants no value, give it none.  */
2635   if (TREE_CODE (TREE_TYPE (TREE_TYPE (current_function_decl))) == VOID_TYPE)
2636     {
2637       expand_expr (retval, NULL_RTX, VOIDmode, 0);
2638       emit_queue ();
2639       expand_null_return ();
2640       return;
2641     }
2642
2643   if (retval == error_mark_node)
2644     {
2645       /* Treat this like a return of no value from a function that
2646          returns a value.  */
2647       expand_null_return ();
2648       return;
2649     }
2650   else if (TREE_CODE (retval) == RESULT_DECL)
2651     retval_rhs = retval;
2652   else if ((TREE_CODE (retval) == MODIFY_EXPR || TREE_CODE (retval) == INIT_EXPR)
2653            && TREE_CODE (TREE_OPERAND (retval, 0)) == RESULT_DECL)
2654     retval_rhs = TREE_OPERAND (retval, 1);
2655   else
2656     retval_rhs = retval;
2657
2658   last_insn = get_last_insn ();
2659
2660   result_rtl = DECL_RTL (DECL_RESULT (current_function_decl));
2661
2662   /* If the result is an aggregate that is being returned in one (or more)
2663      registers, load the registers here.  The compiler currently can't handle
2664      copying a BLKmode value into registers.  We could put this code in a
2665      more general area (for use by everyone instead of just function
2666      call/return), but until this feature is generally usable it is kept here
2667      (and in expand_call).  The value must go into a pseudo in case there
2668      are cleanups that will clobber the real return register.  */
2669
2670   if (retval_rhs != 0
2671       && TYPE_MODE (TREE_TYPE (retval_rhs)) == BLKmode
2672       && REG_P (result_rtl))
2673     {
2674       int i;
2675       unsigned HOST_WIDE_INT bitpos, xbitpos;
2676       unsigned HOST_WIDE_INT padding_correction = 0;
2677       unsigned HOST_WIDE_INT bytes
2678         = int_size_in_bytes (TREE_TYPE (retval_rhs));
2679       int n_regs = (bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
2680       unsigned int bitsize
2681         = MIN (TYPE_ALIGN (TREE_TYPE (retval_rhs)), BITS_PER_WORD);
2682       rtx *result_pseudos = alloca (sizeof (rtx) * n_regs);
2683       rtx result_reg, src = NULL_RTX, dst = NULL_RTX;
2684       rtx result_val = expand_expr (retval_rhs, NULL_RTX, VOIDmode, 0);
2685       enum machine_mode tmpmode, result_reg_mode;
2686
2687       if (bytes == 0)
2688         {
2689           expand_null_return ();
2690           return;
2691         }
2692
2693       /* If the structure doesn't take up a whole number of words, see
2694          whether the register value should be padded on the left or on
2695          the right.  Set PADDING_CORRECTION to the number of padding
2696          bits needed on the left side.
2697
2698          In most ABIs, the structure will be returned at the least end of
2699          the register, which translates to right padding on little-endian
2700          targets and left padding on big-endian targets.  The opposite
2701          holds if the structure is returned at the most significant
2702          end of the register.  */
2703       if (bytes % UNITS_PER_WORD != 0
2704           && (targetm.calls.return_in_msb (TREE_TYPE (retval_rhs))
2705               ? !BYTES_BIG_ENDIAN
2706               : BYTES_BIG_ENDIAN))
2707         padding_correction = (BITS_PER_WORD - ((bytes % UNITS_PER_WORD)
2708                                                * BITS_PER_UNIT));
2709
2710       /* Copy the structure BITSIZE bits at a time.  */
2711       for (bitpos = 0, xbitpos = padding_correction;
2712            bitpos < bytes * BITS_PER_UNIT;
2713            bitpos += bitsize, xbitpos += bitsize)
2714         {
2715           /* We need a new destination pseudo each time xbitpos is
2716              on a word boundary and when xbitpos == padding_correction
2717              (the first time through).  */
2718           if (xbitpos % BITS_PER_WORD == 0
2719               || xbitpos == padding_correction)
2720             {
2721               /* Generate an appropriate register.  */
2722               dst = gen_reg_rtx (word_mode);
2723               result_pseudos[xbitpos / BITS_PER_WORD] = dst;
2724
2725               /* Clear the destination before we move anything into it.  */
2726               emit_move_insn (dst, CONST0_RTX (GET_MODE (dst)));
2727             }
2728
2729           /* We need a new source operand each time bitpos is on a word
2730              boundary.  */
2731           if (bitpos % BITS_PER_WORD == 0)
2732             src = operand_subword_force (result_val,
2733                                          bitpos / BITS_PER_WORD,
2734                                          BLKmode);
2735
2736           /* Use bitpos for the source extraction (left justified) and
2737              xbitpos for the destination store (right justified).  */
2738           store_bit_field (dst, bitsize, xbitpos % BITS_PER_WORD, word_mode,
2739                            extract_bit_field (src, bitsize,
2740                                               bitpos % BITS_PER_WORD, 1,
2741                                               NULL_RTX, word_mode, word_mode,
2742                                               BITS_PER_WORD),
2743                            BITS_PER_WORD);
2744         }
2745
2746       tmpmode = GET_MODE (result_rtl);
2747       if (tmpmode == BLKmode)
2748         {
2749           /* Find the smallest integer mode large enough to hold the
2750              entire structure and use that mode instead of BLKmode
2751              on the USE insn for the return register.  */
2752           for (tmpmode = GET_CLASS_NARROWEST_MODE (MODE_INT);
2753                tmpmode != VOIDmode;
2754                tmpmode = GET_MODE_WIDER_MODE (tmpmode))
2755             /* Have we found a large enough mode?  */
2756             if (GET_MODE_SIZE (tmpmode) >= bytes)
2757               break;
2758
2759           /* No suitable mode found.  */
2760           if (tmpmode == VOIDmode)
2761             abort ();
2762
2763           PUT_MODE (result_rtl, tmpmode);
2764         }
2765
2766       if (GET_MODE_SIZE (tmpmode) < GET_MODE_SIZE (word_mode))
2767         result_reg_mode = word_mode;
2768       else
2769         result_reg_mode = tmpmode;
2770       result_reg = gen_reg_rtx (result_reg_mode);
2771
2772       emit_queue ();
2773       for (i = 0; i < n_regs; i++)
2774         emit_move_insn (operand_subword (result_reg, i, 0, result_reg_mode),
2775                         result_pseudos[i]);
2776
2777       if (tmpmode != result_reg_mode)
2778         result_reg = gen_lowpart (tmpmode, result_reg);
2779
2780       expand_value_return (result_reg);
2781     }
2782   else if (retval_rhs != 0
2783            && !VOID_TYPE_P (TREE_TYPE (retval_rhs))
2784            && (REG_P (result_rtl)
2785                || (GET_CODE (result_rtl) == PARALLEL)))
2786     {
2787       /* Calculate the return value into a temporary (usually a pseudo
2788          reg).  */
2789       tree ot = TREE_TYPE (DECL_RESULT (current_function_decl));
2790       tree nt = build_qualified_type (ot, TYPE_QUALS (ot) | TYPE_QUAL_CONST);
2791
2792       val = assign_temp (nt, 0, 0, 1);
2793       val = expand_expr (retval_rhs, val, GET_MODE (val), 0);
2794       val = force_not_mem (val);
2795       emit_queue ();
2796       /* Return the calculated value, doing cleanups first.  */
2797       expand_value_return (shift_return_value (val));
2798     }
2799   else
2800     {
2801       /* No cleanups or no hard reg used;
2802          calculate value into hard return reg.  */
2803       expand_expr (retval, const0_rtx, VOIDmode, 0);
2804       emit_queue ();
2805       expand_value_return (result_rtl);
2806     }
2807 }
2808 \f
2809 /* Generate the RTL code for entering a binding contour.
2810    The variables are declared one by one, by calls to `expand_decl'.
2811
2812    FLAGS is a bitwise or of the following flags:
2813
2814      1 - Nonzero if this construct should be visible to
2815          `exit_something'.
2816
2817      2 - Nonzero if this contour does not require a
2818          NOTE_INSN_BLOCK_BEG note.  Virtually all calls from
2819          language-independent code should set this flag because they
2820          will not create corresponding BLOCK nodes.  (There should be
2821          a one-to-one correspondence between NOTE_INSN_BLOCK_BEG notes
2822          and BLOCKs.)  If this flag is set, MARK_ENDS should be zero
2823          when expand_end_bindings is called.
2824
2825     If we are creating a NOTE_INSN_BLOCK_BEG note, a BLOCK may
2826     optionally be supplied.  If so, it becomes the NOTE_BLOCK for the
2827     note.  */
2828
2829 void
2830 expand_start_bindings_and_block (int flags, tree block)
2831 {
2832   struct nesting *thisblock = ALLOC_NESTING ();
2833   rtx note;
2834   int exit_flag = ((flags & 1) != 0);
2835   int block_flag = ((flags & 2) == 0);
2836
2837   /* If a BLOCK is supplied, then the caller should be requesting a
2838      NOTE_INSN_BLOCK_BEG note.  */
2839   if (!block_flag && block)
2840     abort ();
2841
2842   /* Create a note to mark the beginning of the block.  */
2843   note = emit_note (NOTE_INSN_DELETED);
2844
2845   /* Make an entry on block_stack for the block we are entering.  */
2846
2847   thisblock->desc = BLOCK_NESTING;
2848   thisblock->next = block_stack;
2849   thisblock->all = nesting_stack;
2850   thisblock->depth = ++nesting_depth;
2851   thisblock->data.block.stack_level = 0;
2852   thisblock->data.block.cleanups = 0;
2853   thisblock->data.block.exception_region = 0;
2854   thisblock->data.block.block_target_temp_slot_level = target_temp_slot_level;
2855
2856   thisblock->data.block.conditional_code = 0;
2857   thisblock->data.block.last_unconditional_cleanup = note;
2858   /* When we insert instructions after the last unconditional cleanup,
2859      we don't adjust last_insn.  That means that a later add_insn will
2860      clobber the instructions we've just added.  The easiest way to
2861      fix this is to just insert another instruction here, so that the
2862      instructions inserted after the last unconditional cleanup are
2863      never the last instruction.  */
2864   emit_note (NOTE_INSN_DELETED);
2865
2866   if (block_stack
2867       && !(block_stack->data.block.cleanups == NULL_TREE
2868            && block_stack->data.block.outer_cleanups == NULL_TREE))
2869     thisblock->data.block.outer_cleanups
2870       = tree_cons (NULL_TREE, block_stack->data.block.cleanups,
2871                    block_stack->data.block.outer_cleanups);
2872   else
2873     thisblock->data.block.outer_cleanups = 0;
2874   thisblock->data.block.label_chain = 0;
2875   thisblock->data.block.innermost_stack_block = stack_block_stack;
2876   thisblock->data.block.first_insn = note;
2877   thisblock->data.block.block_start_count = ++current_block_start_count;
2878   thisblock->exit_label = exit_flag ? gen_label_rtx () : 0;
2879   block_stack = thisblock;
2880   nesting_stack = thisblock;
2881
2882   /* Make a new level for allocating stack slots.  */
2883   push_temp_slots ();
2884 }
2885
2886 /* Specify the scope of temporaries created by TARGET_EXPRs.  Similar
2887    to CLEANUP_POINT_EXPR, but handles cases when a series of calls to
2888    expand_expr are made.  After we end the region, we know that all
2889    space for all temporaries that were created by TARGET_EXPRs will be
2890    destroyed and their space freed for reuse.  */
2891
2892 void
2893 expand_start_target_temps (void)
2894 {
2895   /* This is so that even if the result is preserved, the space
2896      allocated will be freed, as we know that it is no longer in use.  */
2897   push_temp_slots ();
2898
2899   /* Start a new binding layer that will keep track of all cleanup
2900      actions to be performed.  */
2901   expand_start_bindings (2);
2902
2903   target_temp_slot_level = temp_slot_level;
2904 }
2905
2906 void
2907 expand_end_target_temps (void)
2908 {
2909   expand_end_bindings (NULL_TREE, 0, 0);
2910
2911   /* This is so that even if the result is preserved, the space
2912      allocated will be freed, as we know that it is no longer in use.  */
2913   pop_temp_slots ();
2914 }
2915
2916 /* Given a pointer to a BLOCK node return nonzero if (and only if) the node
2917    in question represents the outermost pair of curly braces (i.e. the "body
2918    block") of a function or method.
2919
2920    For any BLOCK node representing a "body block" of a function or method, the
2921    BLOCK_SUPERCONTEXT of the node will point to another BLOCK node which
2922    represents the outermost (function) scope for the function or method (i.e.
2923    the one which includes the formal parameters).  The BLOCK_SUPERCONTEXT of
2924    *that* node in turn will point to the relevant FUNCTION_DECL node.  */
2925
2926 int
2927 is_body_block (tree stmt)
2928 {
2929   if (lang_hooks.no_body_blocks)
2930     return 0;
2931
2932   if (TREE_CODE (stmt) == BLOCK)
2933     {
2934       tree parent = BLOCK_SUPERCONTEXT (stmt);
2935
2936       if (parent && TREE_CODE (parent) == BLOCK)
2937         {
2938           tree grandparent = BLOCK_SUPERCONTEXT (parent);
2939
2940           if (grandparent && TREE_CODE (grandparent) == FUNCTION_DECL)
2941             return 1;
2942         }
2943     }
2944
2945   return 0;
2946 }
2947
2948 /* True if we are currently emitting insns in an area of output code
2949    that is controlled by a conditional expression.  This is used by
2950    the cleanup handling code to generate conditional cleanup actions.  */
2951
2952 int
2953 conditional_context (void)
2954 {
2955   return block_stack && block_stack->data.block.conditional_code;
2956 }
2957
2958 /* Return an opaque pointer to the current nesting level, so frontend code
2959    can check its own sanity.  */
2960
2961 struct nesting *
2962 current_nesting_level (void)
2963 {
2964   return cfun ? block_stack : 0;
2965 }
2966
2967 /* Emit code to restore vital registers at the beginning of a nonlocal goto
2968    handler.  */
2969 static void
2970 expand_nl_goto_receiver (void)
2971 {
2972   /* Clobber the FP when we get here, so we have to make sure it's
2973      marked as used by this function.  */
2974   emit_insn (gen_rtx_USE (VOIDmode, hard_frame_pointer_rtx));
2975
2976   /* Mark the static chain as clobbered here so life information
2977      doesn't get messed up for it.  */
2978   emit_insn (gen_rtx_CLOBBER (VOIDmode, static_chain_rtx));
2979
2980 #ifdef HAVE_nonlocal_goto
2981   if (! HAVE_nonlocal_goto)
2982 #endif
2983     /* First adjust our frame pointer to its actual value.  It was
2984        previously set to the start of the virtual area corresponding to
2985        the stacked variables when we branched here and now needs to be
2986        adjusted to the actual hardware fp value.
2987
2988        Assignments are to virtual registers are converted by
2989        instantiate_virtual_regs into the corresponding assignment
2990        to the underlying register (fp in this case) that makes
2991        the original assignment true.
2992        So the following insn will actually be
2993        decrementing fp by STARTING_FRAME_OFFSET.  */
2994     emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
2995
2996 #if ARG_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
2997   if (fixed_regs[ARG_POINTER_REGNUM])
2998     {
2999 #ifdef ELIMINABLE_REGS
3000       /* If the argument pointer can be eliminated in favor of the
3001          frame pointer, we don't need to restore it.  We assume here
3002          that if such an elimination is present, it can always be used.
3003          This is the case on all known machines; if we don't make this
3004          assumption, we do unnecessary saving on many machines.  */
3005       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
3006       size_t i;
3007
3008       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
3009         if (elim_regs[i].from == ARG_POINTER_REGNUM
3010             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
3011           break;
3012
3013       if (i == ARRAY_SIZE (elim_regs))
3014 #endif
3015         {
3016           /* Now restore our arg pointer from the address at which it
3017              was saved in our stack frame.  */
3018           emit_move_insn (virtual_incoming_args_rtx,
3019                           copy_to_reg (get_arg_pointer_save_area (cfun)));
3020         }
3021     }
3022 #endif
3023
3024 #ifdef HAVE_nonlocal_goto_receiver
3025   if (HAVE_nonlocal_goto_receiver)
3026     emit_insn (gen_nonlocal_goto_receiver ());
3027 #endif
3028
3029   /* @@@ This is a kludge.  Not all machine descriptions define a blockage
3030      insn, but we must not allow the code we just generated to be reordered
3031      by scheduling.  Specifically, the update of the frame pointer must
3032      happen immediately, not later.  So emit an ASM_INPUT to act as blockage
3033      insn.  */
3034   emit_insn (gen_rtx_ASM_INPUT (VOIDmode, ""));
3035 }
3036
3037 /* Warn about any unused VARS (which may contain nodes other than
3038    VAR_DECLs, but such nodes are ignored).  The nodes are connected
3039    via the TREE_CHAIN field.  */
3040
3041 void
3042 warn_about_unused_variables (tree vars)
3043 {
3044   tree decl;
3045
3046   if (warn_unused_variable)
3047     for (decl = vars; decl; decl = TREE_CHAIN (decl))
3048       if (TREE_CODE (decl) == VAR_DECL
3049           && ! TREE_USED (decl)
3050           && ! DECL_IN_SYSTEM_HEADER (decl)
3051           && DECL_NAME (decl) && ! DECL_ARTIFICIAL (decl))
3052         warning ("%Junused variable '%D'", decl, decl);
3053 }
3054
3055 /* Generate RTL code to terminate a binding contour.
3056
3057    VARS is the chain of VAR_DECL nodes for the variables bound in this
3058    contour.  There may actually be other nodes in this chain, but any
3059    nodes other than VAR_DECLS are ignored.
3060
3061    MARK_ENDS is nonzero if we should put a note at the beginning
3062    and end of this binding contour.
3063
3064    DONT_JUMP_IN is positive if it is not valid to jump into this contour,
3065    zero if we can jump into this contour only if it does not have a saved
3066    stack level, and negative if we are not to check for invalid use of
3067    labels (because the front end does that).  */
3068
3069 void
3070 expand_end_bindings (tree vars, int mark_ends ATTRIBUTE_UNUSED,
3071                      int dont_jump_in)
3072 {
3073   struct nesting *thisblock = block_stack;
3074
3075   /* If any of the variables in this scope were not used, warn the
3076      user.  */
3077   warn_about_unused_variables (vars);
3078
3079   if (thisblock->exit_label)
3080     {
3081       do_pending_stack_adjust ();
3082       emit_label (thisblock->exit_label);
3083     }
3084
3085   /* Don't allow jumping into a block that has a stack level.
3086      Cleanups are allowed, though.  */
3087   if (dont_jump_in > 0
3088       || (dont_jump_in == 0 && thisblock->data.block.stack_level != 0))
3089     {
3090       struct label_chain *chain;
3091
3092       /* Any labels in this block are no longer valid to go to.
3093          Mark them to cause an error message.  */
3094       for (chain = thisblock->data.block.label_chain; chain; chain = chain->next)
3095         {
3096           DECL_TOO_LATE (chain->label) = 1;
3097           /* If any goto without a fixup came to this label,
3098              that must be an error, because gotos without fixups
3099              come from outside all saved stack-levels.  */
3100           if (TREE_ADDRESSABLE (chain->label))
3101             error ("%Jlabel '%D' used before containing binding contour",
3102                    chain->label, chain->label);
3103         }
3104     }
3105
3106   /* Restore stack level in effect before the block
3107      (only if variable-size objects allocated).  */
3108   /* Perform any cleanups associated with the block.  */
3109
3110   if (thisblock->data.block.stack_level != 0
3111       || thisblock->data.block.cleanups != 0)
3112     {
3113       int reachable;
3114       rtx insn;
3115
3116       /* Don't let cleanups affect ({...}) constructs.  */
3117       int old_expr_stmts_for_value = expr_stmts_for_value;
3118       rtx old_last_expr_value = last_expr_value;
3119       rtx old_last_expr_alt_rtl = last_expr_alt_rtl;
3120       tree old_last_expr_type = last_expr_type;
3121       expr_stmts_for_value = 0;
3122
3123       /* Only clean up here if this point can actually be reached.  */
3124       insn = get_last_insn ();
3125       if (GET_CODE (insn) == NOTE)
3126         insn = prev_nonnote_insn (insn);
3127       reachable = (! insn || GET_CODE (insn) != BARRIER);
3128
3129       /* Do the cleanups.  */
3130       expand_cleanups (thisblock->data.block.cleanups, 0, reachable);
3131       if (reachable)
3132         do_pending_stack_adjust ();
3133
3134       expr_stmts_for_value = old_expr_stmts_for_value;
3135       last_expr_value = old_last_expr_value;
3136       last_expr_alt_rtl = old_last_expr_alt_rtl;
3137       last_expr_type = old_last_expr_type;
3138
3139       /* Restore the stack level.  */
3140
3141       if (reachable && thisblock->data.block.stack_level != 0)
3142         {
3143           emit_stack_restore (thisblock->next ? SAVE_BLOCK : SAVE_FUNCTION,
3144                               thisblock->data.block.stack_level, NULL_RTX);
3145           if (cfun->nonlocal_goto_save_area)
3146             update_nonlocal_goto_save_area ();
3147         }
3148
3149       /* Any gotos out of this block must also do these things.
3150          Also report any gotos with fixups that came to labels in this
3151          level.  */
3152       fixup_gotos (thisblock,
3153                    thisblock->data.block.stack_level,
3154                    thisblock->data.block.cleanups,
3155                    thisblock->data.block.first_insn,
3156                    dont_jump_in);
3157     }
3158
3159   /* Mark the beginning and end of the scope if requested.
3160      We do this now, after running cleanups on the variables
3161      just going out of scope, so they are in scope for their cleanups.  */
3162
3163   /* Get rid of the beginning-mark if we don't make an end-mark.  */
3164   NOTE_LINE_NUMBER (thisblock->data.block.first_insn) = NOTE_INSN_DELETED;
3165
3166   /* Restore the temporary level of TARGET_EXPRs.  */
3167   target_temp_slot_level = thisblock->data.block.block_target_temp_slot_level;
3168
3169   /* Restore block_stack level for containing block.  */
3170
3171   stack_block_stack = thisblock->data.block.innermost_stack_block;
3172   POPSTACK (block_stack);
3173
3174   /* Pop the stack slot nesting and free any slots at this level.  */
3175   pop_temp_slots ();
3176 }
3177 \f
3178 /* Generate code to save the stack pointer at the start of the current block
3179    and set up to restore it on exit.  */
3180
3181 void
3182 save_stack_pointer (void)
3183 {
3184   struct nesting *thisblock = block_stack;
3185
3186   if (thisblock->data.block.stack_level == 0)
3187     {
3188       emit_stack_save (thisblock->next ? SAVE_BLOCK : SAVE_FUNCTION,
3189                        &thisblock->data.block.stack_level,
3190                        thisblock->data.block.first_insn);
3191       stack_block_stack = thisblock;
3192     }
3193 }
3194 \f
3195 /* Generate RTL for the automatic variable declaration DECL.
3196    (Other kinds of declarations are simply ignored if seen here.)  */
3197
3198 void
3199 expand_decl (tree decl)
3200 {
3201   tree type;
3202
3203   type = TREE_TYPE (decl);
3204
3205   /* For a CONST_DECL, set mode, alignment, and sizes from those of the
3206      type in case this node is used in a reference.  */
3207   if (TREE_CODE (decl) == CONST_DECL)
3208     {
3209       DECL_MODE (decl) = TYPE_MODE (type);
3210       DECL_ALIGN (decl) = TYPE_ALIGN (type);
3211       DECL_SIZE (decl) = TYPE_SIZE (type);
3212       DECL_SIZE_UNIT (decl) = TYPE_SIZE_UNIT (type);
3213       return;
3214     }
3215
3216   /* Otherwise, only automatic variables need any expansion done.  Static and
3217      external variables, and external functions, will be handled by
3218      `assemble_variable' (called from finish_decl).  TYPE_DECL requires
3219      nothing.  PARM_DECLs are handled in `assign_parms'.  */
3220   if (TREE_CODE (decl) != VAR_DECL)
3221     return;
3222
3223   if (TREE_STATIC (decl) || DECL_EXTERNAL (decl))
3224     return;
3225
3226   /* Create the RTL representation for the variable.  */
3227
3228   if (type == error_mark_node)
3229     SET_DECL_RTL (decl, gen_rtx_MEM (BLKmode, const0_rtx));
3230
3231   else if (DECL_SIZE (decl) == 0)
3232     /* Variable with incomplete type.  */
3233     {
3234       rtx x;
3235       if (DECL_INITIAL (decl) == 0)
3236         /* Error message was already done; now avoid a crash.  */
3237         x = gen_rtx_MEM (BLKmode, const0_rtx);
3238       else
3239         /* An initializer is going to decide the size of this array.
3240            Until we know the size, represent its address with a reg.  */
3241         x = gen_rtx_MEM (BLKmode, gen_reg_rtx (Pmode));
3242
3243       set_mem_attributes (x, decl, 1);
3244       SET_DECL_RTL (decl, x);
3245     }
3246   else if (DECL_MODE (decl) != BLKmode
3247            /* If -ffloat-store, don't put explicit float vars
3248               into regs.  */
3249            && !(flag_float_store
3250                 && TREE_CODE (type) == REAL_TYPE)
3251            && ! TREE_THIS_VOLATILE (decl)
3252            && ! DECL_NONLOCAL (decl)
3253            && (DECL_REGISTER (decl) || DECL_ARTIFICIAL (decl) || optimize))
3254     {
3255       /* Automatic variable that can go in a register.  */
3256       int unsignedp = TYPE_UNSIGNED (type);
3257       enum machine_mode reg_mode
3258         = promote_mode (type, DECL_MODE (decl), &unsignedp, 0);
3259
3260       SET_DECL_RTL (decl, gen_reg_rtx (reg_mode));
3261
3262       /* Note if the object is a user variable.  */
3263       if (!DECL_ARTIFICIAL (decl))
3264         {
3265           mark_user_reg (DECL_RTL (decl));
3266
3267           /* Trust user variables which have a pointer type to really
3268              be pointers.  Do not trust compiler generated temporaries
3269              as our type system is totally busted as it relates to
3270              pointer arithmetic which translates into lots of compiler
3271              generated objects with pointer types, but which are not really
3272              pointers.  */
3273           if (POINTER_TYPE_P (type))
3274             mark_reg_pointer (DECL_RTL (decl),
3275                               TYPE_ALIGN (TREE_TYPE (TREE_TYPE (decl))));
3276         }
3277
3278       maybe_set_unchanging (DECL_RTL (decl), decl);
3279
3280       /* If something wants our address, try to use ADDRESSOF.  */
3281       if (TREE_ADDRESSABLE (decl))
3282         put_var_into_stack (decl, /*rescan=*/false);
3283     }
3284
3285   else if (TREE_CODE (DECL_SIZE_UNIT (decl)) == INTEGER_CST
3286            && ! (flag_stack_check && ! STACK_CHECK_BUILTIN
3287                  && 0 < compare_tree_int (DECL_SIZE_UNIT (decl),
3288                                           STACK_CHECK_MAX_VAR_SIZE)))
3289     {
3290       /* Variable of fixed size that goes on the stack.  */
3291       rtx oldaddr = 0;
3292       rtx addr;
3293       rtx x;
3294
3295       /* If we previously made RTL for this decl, it must be an array
3296          whose size was determined by the initializer.
3297          The old address was a register; set that register now
3298          to the proper address.  */
3299       if (DECL_RTL_SET_P (decl))
3300         {
3301           if (GET_CODE (DECL_RTL (decl)) != MEM
3302               || !REG_P (XEXP (DECL_RTL (decl), 0)))
3303             abort ();
3304           oldaddr = XEXP (DECL_RTL (decl), 0);
3305         }
3306
3307       /* Set alignment we actually gave this decl.  */
3308       DECL_ALIGN (decl) = (DECL_MODE (decl) == BLKmode ? BIGGEST_ALIGNMENT
3309                            : GET_MODE_BITSIZE (DECL_MODE (decl)));
3310       DECL_USER_ALIGN (decl) = 0;
3311
3312       x = assign_temp (decl, 1, 1, 1);
3313       set_mem_attributes (x, decl, 1);
3314       SET_DECL_RTL (decl, x);
3315
3316       if (oldaddr)
3317         {
3318           addr = force_operand (XEXP (DECL_RTL (decl), 0), oldaddr);
3319           if (addr != oldaddr)
3320             emit_move_insn (oldaddr, addr);
3321         }
3322     }
3323   else
3324     /* Dynamic-size object: must push space on the stack.  */
3325     {
3326       rtx address, size, x;
3327
3328       /* Record the stack pointer on entry to block, if have
3329          not already done so.  */
3330       do_pending_stack_adjust ();
3331       save_stack_pointer ();
3332
3333       /* Compute the variable's size, in bytes.  This will expand any
3334          needed SAVE_EXPRs for the first time.  */
3335       size = expand_expr (DECL_SIZE_UNIT (decl), NULL_RTX, VOIDmode, 0);
3336       free_temp_slots ();
3337
3338       /* Allocate space on the stack for the variable.  Note that
3339          DECL_ALIGN says how the variable is to be aligned and we
3340          cannot use it to conclude anything about the alignment of
3341          the size.  */
3342       address = allocate_dynamic_stack_space (size, NULL_RTX,
3343                                               TYPE_ALIGN (TREE_TYPE (decl)));
3344
3345       /* Reference the variable indirect through that rtx.  */
3346       x = gen_rtx_MEM (DECL_MODE (decl), address);
3347       set_mem_attributes (x, decl, 1);
3348       SET_DECL_RTL (decl, x);
3349
3350
3351       /* Indicate the alignment we actually gave this variable.  */
3352 #ifdef STACK_BOUNDARY
3353       DECL_ALIGN (decl) = STACK_BOUNDARY;
3354 #else
3355       DECL_ALIGN (decl) = BIGGEST_ALIGNMENT;
3356 #endif
3357       DECL_USER_ALIGN (decl) = 0;
3358     }
3359 }
3360 \f
3361 /* Emit code to allocate T_SIZE bytes of dynamic stack space for ALLOC.  */
3362 void
3363 expand_stack_alloc (tree alloc, tree t_size)
3364 {
3365   rtx address, dest, size;
3366   tree var, type;
3367
3368   if (TREE_CODE (alloc) != ADDR_EXPR)
3369     abort ();
3370   var = TREE_OPERAND (alloc, 0);
3371   if (TREE_CODE (var) != VAR_DECL)
3372     abort ();
3373
3374   type = TREE_TYPE (var);
3375
3376   /* Compute the variable's size, in bytes.  */
3377   size = expand_expr (t_size, NULL_RTX, VOIDmode, 0);
3378   free_temp_slots ();
3379
3380   /* Allocate space on the stack for the variable.  */
3381   address = XEXP (DECL_RTL (var), 0);
3382   dest = allocate_dynamic_stack_space (size, address, TYPE_ALIGN (type));
3383   if (dest != address)
3384     emit_move_insn (address, dest);
3385
3386   /* Indicate the alignment we actually gave this variable.  */
3387 #ifdef STACK_BOUNDARY
3388   DECL_ALIGN (var) = STACK_BOUNDARY;
3389 #else
3390   DECL_ALIGN (var) = BIGGEST_ALIGNMENT;
3391 #endif
3392   DECL_USER_ALIGN (var) = 0;
3393 }
3394
3395 /* Emit code to save the current value of stack.  */
3396 rtx
3397 expand_stack_save (void)
3398 {
3399   rtx ret = NULL_RTX;
3400
3401   do_pending_stack_adjust ();
3402   emit_stack_save (SAVE_BLOCK, &ret, NULL_RTX);
3403   return ret;
3404 }
3405
3406 /* Emit code to restore the current value of stack.  */
3407 void
3408 expand_stack_restore (tree var)
3409 {
3410   rtx sa = DECL_RTL (var);
3411
3412   emit_stack_restore (SAVE_BLOCK, sa, NULL_RTX);
3413 }
3414 \f
3415 /* Emit code to perform the initialization of a declaration DECL.  */
3416
3417 void
3418 expand_decl_init (tree decl)
3419 {
3420   int was_used = TREE_USED (decl);
3421
3422   /* If this is a CONST_DECL, we don't have to generate any code.  Likewise
3423      for static decls.  */
3424   if (TREE_CODE (decl) == CONST_DECL
3425       || TREE_STATIC (decl))
3426     return;
3427
3428   /* Compute and store the initial value now.  */
3429
3430   push_temp_slots ();
3431
3432   if (DECL_INITIAL (decl) == error_mark_node)
3433     {
3434       enum tree_code code = TREE_CODE (TREE_TYPE (decl));
3435
3436       if (code == INTEGER_TYPE || code == REAL_TYPE || code == ENUMERAL_TYPE
3437           || code == POINTER_TYPE || code == REFERENCE_TYPE)
3438         expand_assignment (decl, convert (TREE_TYPE (decl), integer_zero_node),
3439                            0);
3440       emit_queue ();
3441     }
3442   else if (DECL_INITIAL (decl) && TREE_CODE (DECL_INITIAL (decl)) != TREE_LIST)
3443     {
3444       emit_line_note (DECL_SOURCE_LOCATION (decl));
3445       expand_assignment (decl, DECL_INITIAL (decl), 0);
3446       emit_queue ();
3447     }
3448
3449   /* Don't let the initialization count as "using" the variable.  */
3450   TREE_USED (decl) = was_used;
3451
3452   /* Free any temporaries we made while initializing the decl.  */
3453   preserve_temp_slots (NULL_RTX);
3454   free_temp_slots ();
3455   pop_temp_slots ();
3456 }
3457
3458 /* CLEANUP is an expression to be executed at exit from this binding contour;
3459    for example, in C++, it might call the destructor for this variable.
3460
3461    We wrap CLEANUP in an UNSAVE_EXPR node, so that we can expand the
3462    CLEANUP multiple times, and have the correct semantics.  This
3463    happens in exception handling, for gotos, returns, breaks that
3464    leave the current scope.
3465
3466    If CLEANUP is nonzero and DECL is zero, we record a cleanup
3467    that is not associated with any particular variable.  */
3468
3469 int
3470 expand_decl_cleanup (tree decl, tree cleanup)
3471 {
3472   struct nesting *thisblock;
3473
3474   /* Error if we are not in any block.  */
3475   if (cfun == 0 || block_stack == 0)
3476     return 0;
3477
3478   thisblock = block_stack;
3479
3480   /* Record the cleanup if there is one.  */
3481
3482   if (cleanup != 0)
3483     {
3484       tree t;
3485       rtx seq;
3486       tree *cleanups = &thisblock->data.block.cleanups;
3487       int cond_context = conditional_context ();
3488
3489       if (cond_context)
3490         {
3491           rtx flag = gen_reg_rtx (word_mode);
3492           rtx set_flag_0;
3493           tree cond;
3494
3495           start_sequence ();
3496           emit_move_insn (flag, const0_rtx);
3497           set_flag_0 = get_insns ();
3498           end_sequence ();
3499
3500           thisblock->data.block.last_unconditional_cleanup
3501             = emit_insn_after (set_flag_0,
3502                                 thisblock->data.block.last_unconditional_cleanup);
3503
3504           emit_move_insn (flag, const1_rtx);
3505
3506           cond = build_decl (VAR_DECL, NULL_TREE,
3507                              lang_hooks.types.type_for_mode (word_mode, 1));
3508           SET_DECL_RTL (cond, flag);
3509
3510           /* Conditionalize the cleanup.  */
3511           cleanup = build (COND_EXPR, void_type_node,
3512                            lang_hooks.truthvalue_conversion (cond),
3513                            cleanup, integer_zero_node);
3514           cleanup = fold (cleanup);
3515
3516           cleanups = &thisblock->data.block.cleanups;
3517         }
3518
3519       cleanup = unsave_expr (cleanup);
3520
3521       t = *cleanups = tree_cons (decl, cleanup, *cleanups);
3522
3523       if (! cond_context)
3524         /* If this block has a cleanup, it belongs in stack_block_stack.  */
3525         stack_block_stack = thisblock;
3526
3527       if (cond_context)
3528         {
3529           start_sequence ();
3530         }
3531
3532       if (! using_eh_for_cleanups_p)
3533         TREE_ADDRESSABLE (t) = 1;
3534       else
3535         expand_eh_region_start ();
3536
3537       if (cond_context)
3538         {
3539           seq = get_insns ();
3540           end_sequence ();
3541           if (seq)
3542             thisblock->data.block.last_unconditional_cleanup
3543               = emit_insn_after (seq,
3544                                  thisblock->data.block.last_unconditional_cleanup);
3545         }
3546       else
3547         {
3548           thisblock->data.block.last_unconditional_cleanup
3549             = get_last_insn ();
3550           /* When we insert instructions after the last unconditional cleanup,
3551              we don't adjust last_insn.  That means that a later add_insn will
3552              clobber the instructions we've just added.  The easiest way to
3553              fix this is to just insert another instruction here, so that the
3554              instructions inserted after the last unconditional cleanup are
3555              never the last instruction.  */
3556           emit_note (NOTE_INSN_DELETED);
3557         }
3558     }
3559   return 1;
3560 }
3561
3562 /* Like expand_decl_cleanup, but maybe only run the cleanup if an exception
3563    is thrown.  */
3564
3565 int
3566 expand_decl_cleanup_eh (tree decl, tree cleanup, int eh_only)
3567 {
3568   int ret = expand_decl_cleanup (decl, cleanup);
3569   if (cleanup && ret)
3570     {
3571       tree node = block_stack->data.block.cleanups;
3572       CLEANUP_EH_ONLY (node) = eh_only;
3573     }
3574   return ret;
3575 }
3576 \f
3577 /* DECL is an anonymous union.  CLEANUP is a cleanup for DECL.
3578    DECL_ELTS is the list of elements that belong to DECL's type.
3579    In each, the TREE_VALUE is a VAR_DECL, and the TREE_PURPOSE a cleanup.  */
3580
3581 void
3582 expand_anon_union_decl (tree decl, tree cleanup, tree decl_elts)
3583 {
3584   struct nesting *thisblock = cfun == 0 ? 0 : block_stack;
3585   rtx x;
3586   tree t;
3587
3588   /* If any of the elements are addressable, so is the entire union.  */
3589   for (t = decl_elts; t; t = TREE_CHAIN (t))
3590     if (TREE_ADDRESSABLE (TREE_VALUE (t)))
3591       {
3592         TREE_ADDRESSABLE (decl) = 1;
3593         break;
3594       }
3595
3596   expand_decl (decl);
3597   expand_decl_cleanup (decl, cleanup);
3598   x = DECL_RTL (decl);
3599
3600   /* Go through the elements, assigning RTL to each.  */
3601   for (t = decl_elts; t; t = TREE_CHAIN (t))
3602     {
3603       tree decl_elt = TREE_VALUE (t);
3604       tree cleanup_elt = TREE_PURPOSE (t);
3605       enum machine_mode mode = TYPE_MODE (TREE_TYPE (decl_elt));
3606
3607       /* If any of the elements are addressable, so is the entire
3608          union.  */
3609       if (TREE_USED (decl_elt))
3610         TREE_USED (decl) = 1;
3611
3612       /* Propagate the union's alignment to the elements.  */
3613       DECL_ALIGN (decl_elt) = DECL_ALIGN (decl);
3614       DECL_USER_ALIGN (decl_elt) = DECL_USER_ALIGN (decl);
3615
3616       /* If the element has BLKmode and the union doesn't, the union is
3617          aligned such that the element doesn't need to have BLKmode, so
3618          change the element's mode to the appropriate one for its size.  */
3619       if (mode == BLKmode && DECL_MODE (decl) != BLKmode)
3620         DECL_MODE (decl_elt) = mode
3621           = mode_for_size_tree (DECL_SIZE (decl_elt), MODE_INT, 1);
3622
3623       /* (SUBREG (MEM ...)) at RTL generation time is invalid, so we
3624          instead create a new MEM rtx with the proper mode.  */
3625       if (GET_CODE (x) == MEM)
3626         {
3627           if (mode == GET_MODE (x))
3628             SET_DECL_RTL (decl_elt, x);
3629           else
3630             SET_DECL_RTL (decl_elt, adjust_address_nv (x, mode, 0));
3631         }
3632       else if (REG_P (x))
3633         {
3634           if (mode == GET_MODE (x))
3635             SET_DECL_RTL (decl_elt, x);
3636           else
3637             SET_DECL_RTL (decl_elt, gen_lowpart_SUBREG (mode, x));
3638         }
3639       else
3640         abort ();
3641
3642       /* Record the cleanup if there is one.  */
3643
3644       if (cleanup != 0)
3645         thisblock->data.block.cleanups
3646           = tree_cons (decl_elt, cleanup_elt,
3647                        thisblock->data.block.cleanups);
3648     }
3649 }
3650 \f
3651 /* Expand a list of cleanups LIST.
3652    Elements may be expressions or may be nested lists.
3653
3654    If IN_FIXUP is nonzero, we are generating this cleanup for a fixup
3655    goto and handle protection regions specially in that case.
3656
3657    If REACHABLE, we emit code, otherwise just inform the exception handling
3658    code about this finalization.  */
3659
3660 static void
3661 expand_cleanups (tree list, int in_fixup, int reachable)
3662 {
3663   tree tail;
3664   for (tail = list; tail; tail = TREE_CHAIN (tail))
3665     if (TREE_CODE (TREE_VALUE (tail)) == TREE_LIST)
3666       expand_cleanups (TREE_VALUE (tail), in_fixup, reachable);
3667     else
3668       {
3669         if (! in_fixup && using_eh_for_cleanups_p)
3670           expand_eh_region_end_cleanup (TREE_VALUE (tail));
3671
3672         if (reachable && !CLEANUP_EH_ONLY (tail))
3673           {
3674             /* Cleanups may be run multiple times.  For example,
3675                when exiting a binding contour, we expand the
3676                cleanups associated with that contour.  When a goto
3677                within that binding contour has a target outside that
3678                contour, it will expand all cleanups from its scope to
3679                the target.  Though the cleanups are expanded multiple
3680                times, the control paths are non-overlapping so the
3681                cleanups will not be executed twice.  */
3682
3683             /* We may need to protect from outer cleanups.  */
3684             if (in_fixup && using_eh_for_cleanups_p)
3685               {
3686                 expand_eh_region_start ();
3687
3688                 expand_expr (TREE_VALUE (tail), const0_rtx, VOIDmode, 0);
3689
3690                 expand_eh_region_end_fixup (TREE_VALUE (tail));
3691               }
3692             else
3693               expand_expr (TREE_VALUE (tail), const0_rtx, VOIDmode, 0);
3694
3695             free_temp_slots ();
3696           }
3697       }
3698 }
3699
3700 /* Mark when the context we are emitting RTL for as a conditional
3701    context, so that any cleanup actions we register with
3702    expand_decl_init will be properly conditionalized when those
3703    cleanup actions are later performed.  Must be called before any
3704    expression (tree) is expanded that is within a conditional context.  */
3705
3706 void
3707 start_cleanup_deferral (void)
3708 {
3709   /* block_stack can be NULL if we are inside the parameter list.  It is
3710      OK to do nothing, because cleanups aren't possible here.  */
3711   if (block_stack)
3712     ++block_stack->data.block.conditional_code;
3713 }
3714
3715 /* Mark the end of a conditional region of code.  Because cleanup
3716    deferrals may be nested, we may still be in a conditional region
3717    after we end the currently deferred cleanups, only after we end all
3718    deferred cleanups, are we back in unconditional code.  */
3719
3720 void
3721 end_cleanup_deferral (void)
3722 {
3723   /* block_stack can be NULL if we are inside the parameter list.  It is
3724      OK to do nothing, because cleanups aren't possible here.  */
3725   if (block_stack)
3726     --block_stack->data.block.conditional_code;
3727 }
3728
3729 tree
3730 last_cleanup_this_contour (void)
3731 {
3732   if (block_stack == 0)
3733     return 0;
3734
3735   return block_stack->data.block.cleanups;
3736 }
3737
3738
3739 /* Return nonzero if any containing block has a stack level or
3740    cleanups.  */
3741
3742 int
3743 containing_blocks_have_cleanups_or_stack_level (void)
3744 {
3745   struct nesting *block;
3746
3747   for (block = block_stack; block; block = block->next)
3748     if (block->data.block.stack_level != 0
3749         || block->data.block.cleanups != 0)
3750       return 1;
3751
3752   return 0;
3753 }
3754
3755 /* Return 1 if there are any pending cleanups at this point.
3756    Check the current contour as well as contours that enclose
3757    the current contour.  */
3758
3759 int
3760 any_pending_cleanups (void)
3761 {
3762   struct nesting *block;
3763
3764   if (cfun == NULL || cfun->stmt == NULL || block_stack == 0)
3765     return 0;
3766
3767   if (block_stack->data.block.cleanups != NULL)
3768     return 1;
3769
3770   if (block_stack->data.block.outer_cleanups == 0)
3771     return 0;
3772
3773   for (block = block_stack->next; block; block = block->next)
3774     if (block->data.block.cleanups != 0)
3775       return 1;
3776
3777   return 0;
3778 }
3779 \f
3780 /* Enter a case (Pascal) or switch (C) statement.
3781    Push a block onto case_stack and nesting_stack
3782    to accumulate the case-labels that are seen
3783    and to record the labels generated for the statement.
3784
3785    EXIT_FLAG is nonzero if `exit_something' should exit this case stmt.
3786    Otherwise, this construct is transparent for `exit_something'.
3787
3788    EXPR is the index-expression to be dispatched on.
3789    TYPE is its nominal type.  We could simply convert EXPR to this type,
3790    but instead we take short cuts.  */
3791
3792 void
3793 expand_start_case (int exit_flag, tree expr, tree type,
3794                    const char *printname)
3795 {
3796   struct nesting *thiscase = ALLOC_NESTING ();
3797
3798   /* Make an entry on case_stack for the case we are entering.  */
3799
3800   thiscase->desc = CASE_NESTING;
3801   thiscase->next = case_stack;
3802   thiscase->all = nesting_stack;
3803   thiscase->depth = ++nesting_depth;
3804   thiscase->exit_label = exit_flag ? gen_label_rtx () : 0;
3805   thiscase->data.case_stmt.case_list = 0;
3806   thiscase->data.case_stmt.index_expr = expr;
3807   thiscase->data.case_stmt.nominal_type = type;
3808   thiscase->data.case_stmt.default_label = 0;
3809   thiscase->data.case_stmt.printname = printname;
3810   thiscase->data.case_stmt.line_number_status = force_line_numbers ();
3811   case_stack = thiscase;
3812   nesting_stack = thiscase;
3813
3814   do_pending_stack_adjust ();
3815   emit_queue ();
3816
3817   /* Make sure case_stmt.start points to something that won't
3818      need any transformation before expand_end_case.  */
3819   if (GET_CODE (get_last_insn ()) != NOTE)
3820     emit_note (NOTE_INSN_DELETED);
3821
3822   thiscase->data.case_stmt.start = get_last_insn ();
3823
3824   start_cleanup_deferral ();
3825 }
3826 \f
3827 static void
3828 check_seenlabel (void)
3829 {
3830   /* If this is the first label, warn if any insns have been emitted.  */
3831   if (case_stack->data.case_stmt.line_number_status >= 0)
3832     {
3833       rtx insn;
3834
3835       restore_line_number_status
3836         (case_stack->data.case_stmt.line_number_status);
3837       case_stack->data.case_stmt.line_number_status = -1;
3838
3839       for (insn = case_stack->data.case_stmt.start;
3840            insn;
3841            insn = NEXT_INSN (insn))
3842         {
3843           if (GET_CODE (insn) == CODE_LABEL)
3844             break;
3845           if (GET_CODE (insn) != NOTE
3846               && (GET_CODE (insn) != INSN || GET_CODE (PATTERN (insn)) != USE))
3847             {
3848               do
3849                 insn = PREV_INSN (insn);
3850               while (insn && (GET_CODE (insn) != NOTE || NOTE_LINE_NUMBER (insn) < 0));
3851
3852               /* If insn is zero, then there must have been a syntax error.  */
3853               if (insn)
3854                 {
3855                   location_t locus;
3856 #ifdef USE_MAPPED_LOCATION
3857                   locus = NOTE_SOURCE_LOCATION (insn);
3858 #else
3859                   locus.file = NOTE_SOURCE_FILE (insn);
3860                   locus.line = NOTE_LINE_NUMBER (insn);
3861 #endif
3862                   warning ("%Hunreachable code at beginning of %s", &locus,
3863                            case_stack->data.case_stmt.printname);
3864                 }
3865               break;
3866             }
3867         }
3868     }
3869 }
3870
3871 /* Accumulate one case or default label inside a case or switch statement.
3872    VALUE is the value of the case (a null pointer, for a default label).
3873    The function CONVERTER, when applied to arguments T and V,
3874    converts the value V to the type T.
3875
3876    If not currently inside a case or switch statement, return 1 and do
3877    nothing.  The caller will print a language-specific error message.
3878    If VALUE is a duplicate or overlaps, return 2 and do nothing
3879    except store the (first) duplicate node in *DUPLICATE.
3880    If VALUE is out of range, return 3 and do nothing.
3881    If we are jumping into the scope of a cleanup or var-sized array, return 5.
3882    Return 0 on success.
3883
3884    Extended to handle range statements.  */
3885
3886 int
3887 pushcase (tree value, tree (*converter) (tree, tree), tree label,
3888           tree *duplicate)
3889 {
3890   tree index_type;
3891   tree nominal_type;
3892
3893   /* Fail if not inside a real case statement.  */
3894   if (! (case_stack && case_stack->data.case_stmt.start))
3895     return 1;
3896
3897   if (stack_block_stack
3898       && stack_block_stack->depth > case_stack->depth)
3899     return 5;
3900
3901   index_type = TREE_TYPE (case_stack->data.case_stmt.index_expr);
3902   nominal_type = case_stack->data.case_stmt.nominal_type;
3903
3904   /* If the index is erroneous, avoid more problems: pretend to succeed.  */
3905   if (index_type == error_mark_node)
3906     return 0;
3907
3908   /* Convert VALUE to the type in which the comparisons are nominally done.  */
3909   if (value != 0)
3910     value = (*converter) (nominal_type, value);
3911
3912   check_seenlabel ();
3913
3914   /* Fail if this value is out of range for the actual type of the index
3915      (which may be narrower than NOMINAL_TYPE).  */
3916   if (value != 0
3917       && (TREE_CONSTANT_OVERFLOW (value)
3918           || ! int_fits_type_p (value, index_type)))
3919     return 3;
3920
3921   return add_case_node (value, value, label, duplicate, false);
3922 }
3923
3924 /* Like pushcase but this case applies to all values between VALUE1 and
3925    VALUE2 (inclusive).  If VALUE1 is NULL, the range starts at the lowest
3926    value of the index type and ends at VALUE2.  If VALUE2 is NULL, the range
3927    starts at VALUE1 and ends at the highest value of the index type.
3928    If both are NULL, this case applies to all values.
3929
3930    The return value is the same as that of pushcase but there is one
3931    additional error code: 4 means the specified range was empty.  */
3932
3933 int
3934 pushcase_range (tree value1, tree value2, tree (*converter) (tree, tree),
3935                 tree label, tree *duplicate)
3936 {
3937   tree index_type;
3938   tree nominal_type;
3939
3940   /* Fail if not inside a real case statement.  */
3941   if (! (case_stack && case_stack->data.case_stmt.start))
3942     return 1;
3943
3944   if (stack_block_stack
3945       && stack_block_stack->depth > case_stack->depth)
3946     return 5;
3947
3948   index_type = TREE_TYPE (case_stack->data.case_stmt.index_expr);
3949   nominal_type = case_stack->data.case_stmt.nominal_type;
3950
3951   /* If the index is erroneous, avoid more problems: pretend to succeed.  */
3952   if (index_type == error_mark_node)
3953     return 0;
3954
3955   check_seenlabel ();
3956
3957   /* Convert VALUEs to type in which the comparisons are nominally done
3958      and replace any unspecified value with the corresponding bound.  */
3959   if (value1 == 0)
3960     value1 = TYPE_MIN_VALUE (index_type);
3961   if (value2 == 0)
3962     value2 = TYPE_MAX_VALUE (index_type);
3963
3964   /* Fail if the range is empty.  Do this before any conversion since
3965      we want to allow out-of-range empty ranges.  */
3966   if (value2 != 0 && tree_int_cst_lt (value2, value1))
3967     return 4;
3968
3969   /* If the max was unbounded, use the max of the nominal_type we are
3970      converting to.  Do this after the < check above to suppress false
3971      positives.  */
3972   if (value2 == 0)
3973     value2 = TYPE_MAX_VALUE (nominal_type);
3974
3975   value1 = (*converter) (nominal_type, value1);
3976   value2 = (*converter) (nominal_type, value2);
3977
3978   /* Fail if these values are out of range.  */
3979   if (TREE_CONSTANT_OVERFLOW (value1)
3980       || ! int_fits_type_p (value1, index_type))
3981     return 3;
3982
3983   if (TREE_CONSTANT_OVERFLOW (value2)
3984       || ! int_fits_type_p (value2, index_type))
3985     return 3;
3986
3987   return add_case_node (value1, value2, label, duplicate, false);
3988 }
3989
3990 /* Do the actual insertion of a case label for pushcase and pushcase_range
3991    into case_stack->data.case_stmt.case_list.  Use an AVL tree to avoid
3992    slowdown for large switch statements.  */
3993
3994 int
3995 add_case_node (tree low, tree high, tree label, tree *duplicate,
3996                bool dont_expand_label)
3997 {
3998   struct case_node *p, **q, *r;
3999
4000   /* If there's no HIGH value, then this is not a case range; it's
4001      just a simple case label.  But that's just a degenerate case
4002      range.  */
4003   if (!high)
4004     high = low;
4005
4006   /* Handle default labels specially.  */
4007   if (!high && !low)
4008     {
4009       if (case_stack->data.case_stmt.default_label != 0)
4010         {
4011           *duplicate = case_stack->data.case_stmt.default_label;
4012           return 2;
4013         }
4014       case_stack->data.case_stmt.default_label = label;
4015       if (!dont_expand_label)
4016         expand_label (label);
4017       return 0;
4018     }
4019
4020   q = &case_stack->data.case_stmt.case_list;
4021   p = *q;
4022
4023   while ((r = *q))
4024     {
4025       p = r;
4026
4027       /* Keep going past elements distinctly greater than HIGH.  */
4028       if (tree_int_cst_lt (high, p->low))
4029         q = &p->left;
4030
4031       /* or distinctly less than LOW.  */
4032       else if (tree_int_cst_lt (p->high, low))
4033         q = &p->right;
4034
4035       else
4036         {
4037           /* We have an overlap; this is an error.  */
4038           *duplicate = p->code_label;
4039           return 2;
4040         }
4041     }
4042
4043   /* Add this label to the chain, and succeed.  */
4044
4045   r = ggc_alloc (sizeof (struct case_node));
4046   r->low = low;
4047
4048   /* If the bounds are equal, turn this into the one-value case.  */
4049   if (tree_int_cst_equal (low, high))
4050     r->high = r->low;
4051   else
4052     r->high = high;
4053
4054   r->code_label = label;
4055   if (!dont_expand_label)
4056     expand_label (label);
4057
4058   *q = r;
4059   r->parent = p;
4060   r->left = 0;
4061   r->right = 0;
4062   r->balance = 0;
4063
4064   while (p)
4065     {
4066       struct case_node *s;
4067
4068       if (r == p->left)
4069         {
4070           int b;
4071
4072           if (! (b = p->balance))
4073             /* Growth propagation from left side.  */
4074             p->balance = -1;
4075           else if (b < 0)
4076             {
4077               if (r->balance < 0)
4078                 {
4079                   /* R-Rotation */
4080                   if ((p->left = s = r->right))
4081                     s->parent = p;
4082
4083                   r->right = p;
4084                   p->balance = 0;
4085                   r->balance = 0;
4086                   s = p->parent;
4087                   p->parent = r;
4088
4089                   if ((r->parent = s))
4090                     {
4091                       if (s->left == p)
4092                         s->left = r;
4093                       else
4094                         s->right = r;
4095                     }
4096                   else
4097                     case_stack->data.case_stmt.case_list = r;
4098                 }
4099               else
4100                 /* r->balance == +1 */
4101                 {
4102                   /* LR-Rotation */
4103
4104                   int b2;
4105                   struct case_node *t = r->right;
4106
4107                   if ((p->left = s = t->right))
4108                     s->parent = p;
4109
4110                   t->right = p;
4111                   if ((r->right = s = t->left))
4112                     s->parent = r;
4113
4114                   t->left = r;
4115                   b = t->balance;
4116                   b2 = b < 0;
4117                   p->balance = b2;
4118                   b2 = -b2 - b;
4119                   r->balance = b2;
4120                   t->balance = 0;
4121                   s = p->parent;
4122                   p->parent = t;
4123                   r->parent = t;
4124
4125                   if ((t->parent = s))
4126                     {
4127                       if (s->left == p)
4128                         s->left = t;
4129                       else
4130                         s->right = t;
4131                     }
4132                   else
4133                     case_stack->data.case_stmt.case_list = t;
4134                 }
4135               break;
4136             }
4137
4138           else
4139             {
4140               /* p->balance == +1; growth of left side balances the node.  */
4141               p->balance = 0;
4142               break;
4143             }
4144         }
4145       else
4146         /* r == p->right */
4147         {
4148           int b;
4149
4150           if (! (b = p->balance))
4151             /* Growth propagation from right side.  */
4152             p->balance++;
4153           else if (b > 0)
4154             {
4155               if (r->balance > 0)
4156                 {
4157                   /* L-Rotation */
4158
4159                   if ((p->right = s = r->left))
4160                     s->parent = p;
4161
4162                   r->left = p;
4163                   p->balance = 0;
4164                   r->balance = 0;
4165                   s = p->parent;
4166                   p->parent = r;
4167                   if ((r->parent = s))
4168                     {
4169                       if (s->left == p)
4170                         s->left = r;
4171                       else
4172                         s->right = r;
4173                     }
4174
4175                   else
4176                     case_stack->data.case_stmt.case_list = r;
4177                 }
4178
4179               else
4180                 /* r->balance == -1 */
4181                 {
4182                   /* RL-Rotation */
4183                   int b2;
4184                   struct case_node *t = r->left;
4185
4186                   if ((p->right = s = t->left))
4187                     s->parent = p;
4188
4189                   t->left = p;
4190
4191                   if ((r->left = s = t->right))
4192                     s->parent = r;
4193
4194                   t->right = r;
4195                   b = t->balance;
4196                   b2 = b < 0;
4197                   r->balance = b2;
4198                   b2 = -b2 - b;
4199                   p->balance = b2;
4200                   t->balance = 0;
4201                   s = p->parent;
4202                   p->parent = t;
4203                   r->parent = t;
4204
4205                   if ((t->parent = s))
4206                     {
4207                       if (s->left == p)
4208                         s->left = t;
4209                       else
4210                         s->right = t;
4211                     }
4212
4213                   else
4214                     case_stack->data.case_stmt.case_list = t;
4215                 }
4216               break;
4217             }
4218           else
4219             {
4220               /* p->balance == -1; growth of right side balances the node.  */
4221               p->balance = 0;
4222               break;
4223             }
4224         }
4225
4226       r = p;
4227       p = p->parent;
4228     }
4229
4230   return 0;
4231 }
4232 \f
4233 /* Maximum number of case bit tests.  */
4234 #define MAX_CASE_BIT_TESTS  3
4235
4236 /* By default, enable case bit tests on targets with ashlsi3.  */
4237 #ifndef CASE_USE_BIT_TESTS
4238 #define CASE_USE_BIT_TESTS  (ashl_optab->handlers[word_mode].insn_code \
4239                              != CODE_FOR_nothing)
4240 #endif
4241
4242
4243 /* A case_bit_test represents a set of case nodes that may be
4244    selected from using a bit-wise comparison.  HI and LO hold
4245    the integer to be tested against, LABEL contains the label
4246    to jump to upon success and BITS counts the number of case
4247    nodes handled by this test, typically the number of bits
4248    set in HI:LO.  */
4249
4250 struct case_bit_test
4251 {
4252   HOST_WIDE_INT hi;
4253   HOST_WIDE_INT lo;
4254   rtx label;
4255   int bits;
4256 };
4257
4258 /* Determine whether "1 << x" is relatively cheap in word_mode.  */
4259
4260 static
4261 bool lshift_cheap_p (void)
4262 {
4263   static bool init = false;
4264   static bool cheap = true;
4265
4266   if (!init)
4267     {
4268       rtx reg = gen_rtx_REG (word_mode, 10000);
4269       int cost = rtx_cost (gen_rtx_ASHIFT (word_mode, const1_rtx, reg), SET);
4270       cheap = cost < COSTS_N_INSNS (3);
4271       init = true;
4272     }
4273
4274   return cheap;
4275 }
4276
4277 /* Comparison function for qsort to order bit tests by decreasing
4278    number of case nodes, i.e. the node with the most cases gets
4279    tested first.  */
4280
4281 static int
4282 case_bit_test_cmp (const void *p1, const void *p2)
4283 {
4284   const struct case_bit_test *d1 = p1;
4285   const struct case_bit_test *d2 = p2;
4286
4287   return d2->bits - d1->bits;
4288 }
4289
4290 /*  Expand a switch statement by a short sequence of bit-wise
4291     comparisons.  "switch(x)" is effectively converted into
4292     "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
4293     integer constants.
4294
4295     INDEX_EXPR is the value being switched on, which is of
4296     type INDEX_TYPE.  MINVAL is the lowest case value of in
4297     the case nodes, of INDEX_TYPE type, and RANGE is highest
4298     value minus MINVAL, also of type INDEX_TYPE.  NODES is
4299     the set of case nodes, and DEFAULT_LABEL is the label to
4300     branch to should none of the cases match.
4301
4302     There *MUST* be MAX_CASE_BIT_TESTS or less unique case
4303     node targets.  */
4304
4305 static void
4306 emit_case_bit_tests (tree index_type, tree index_expr, tree minval,
4307                      tree range, case_node_ptr nodes, rtx default_label)
4308 {
4309   struct case_bit_test test[MAX_CASE_BIT_TESTS];
4310   enum machine_mode mode;
4311   rtx expr, index, label;
4312   unsigned int i,j,lo,hi;
4313   struct case_node *n;
4314   unsigned int count;
4315
4316   count = 0;
4317   for (n = nodes; n; n = n->right)
4318     {
4319       label = label_rtx (n->code_label);
4320       for (i = 0; i < count; i++)
4321         if (same_case_target_p (label, test[i].label))
4322           break;
4323
4324       if (i == count)
4325         {
4326           if (count >= MAX_CASE_BIT_TESTS)
4327             abort ();
4328           test[i].hi = 0;
4329           test[i].lo = 0;
4330           test[i].label = label;
4331           test[i].bits = 1;
4332           count++;
4333         }
4334       else
4335         test[i].bits++;
4336
4337       lo = tree_low_cst (fold (build (MINUS_EXPR, index_type,
4338                                       n->low, minval)), 1);
4339       hi = tree_low_cst (fold (build (MINUS_EXPR, index_type,
4340                                       n->high, minval)), 1);
4341       for (j = lo; j <= hi; j++)
4342         if (j >= HOST_BITS_PER_WIDE_INT)
4343           test[i].hi |= (HOST_WIDE_INT) 1 << (j - HOST_BITS_PER_INT);
4344         else
4345           test[i].lo |= (HOST_WIDE_INT) 1 << j;
4346     }
4347
4348   qsort (test, count, sizeof(*test), case_bit_test_cmp);
4349
4350   index_expr = fold (build (MINUS_EXPR, index_type,
4351                             convert (index_type, index_expr),
4352                             convert (index_type, minval)));
4353   index = expand_expr (index_expr, NULL_RTX, VOIDmode, 0);
4354   emit_queue ();
4355   index = protect_from_queue (index, 0);
4356   do_pending_stack_adjust ();
4357
4358   mode = TYPE_MODE (index_type);
4359   expr = expand_expr (range, NULL_RTX, VOIDmode, 0);
4360   emit_cmp_and_jump_insns (index, expr, GTU, NULL_RTX, mode, 1,
4361                            default_label);
4362
4363   index = convert_to_mode (word_mode, index, 0);
4364   index = expand_binop (word_mode, ashl_optab, const1_rtx,
4365                         index, NULL_RTX, 1, OPTAB_WIDEN);
4366
4367   for (i = 0; i < count; i++)
4368     {
4369       expr = immed_double_const (test[i].lo, test[i].hi, word_mode);
4370       expr = expand_binop (word_mode, and_optab, index, expr,
4371                            NULL_RTX, 1, OPTAB_WIDEN);
4372       emit_cmp_and_jump_insns (expr, const0_rtx, NE, NULL_RTX,
4373                                word_mode, 1, test[i].label);
4374     }
4375
4376   emit_jump (default_label);
4377 }
4378
4379 #ifndef HAVE_casesi
4380 #define HAVE_casesi 0
4381 #endif
4382
4383 #ifndef HAVE_tablejump
4384 #define HAVE_tablejump 0
4385 #endif
4386
4387 /* Terminate a case (Pascal) or switch (C) statement
4388    in which ORIG_INDEX is the expression to be tested.
4389    If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
4390    type as given in the source before any compiler conversions.
4391    Generate the code to test it and jump to the right place.  */
4392
4393 void
4394 expand_end_case_type (tree orig_index, tree orig_type)
4395 {
4396   tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
4397   rtx default_label = 0;
4398   struct case_node *n, *m;
4399   unsigned int count, uniq;
4400   rtx index;
4401   rtx table_label;
4402   int ncases;
4403   rtx *labelvec;
4404   int i;
4405   rtx before_case, end, lab;
4406   struct nesting *thiscase = case_stack;
4407   tree index_expr, index_type;
4408   bool exit_done = false;
4409   int unsignedp;
4410
4411   /* Don't crash due to previous errors.  */
4412   if (thiscase == NULL)
4413     return;
4414
4415   index_expr = thiscase->data.case_stmt.index_expr;
4416   index_type = TREE_TYPE (index_expr);
4417   unsignedp = TYPE_UNSIGNED (index_type);
4418   if (orig_type == NULL)
4419     orig_type = TREE_TYPE (orig_index);
4420
4421   do_pending_stack_adjust ();
4422
4423   /* This might get a spurious warning in the presence of a syntax error;
4424      it could be fixed by moving the call to check_seenlabel after the
4425      check for error_mark_node, and copying the code of check_seenlabel that
4426      deals with case_stack->data.case_stmt.line_number_status /
4427      restore_line_number_status in front of the call to end_cleanup_deferral;
4428      However, this might miss some useful warnings in the presence of
4429      non-syntax errors.  */
4430   check_seenlabel ();
4431
4432   /* An ERROR_MARK occurs for various reasons including invalid data type.  */
4433   if (index_type != error_mark_node)
4434     {
4435       /* If we don't have a default-label, create one here,
4436          after the body of the switch.  */
4437       if (thiscase->data.case_stmt.default_label == 0)
4438         {
4439           thiscase->data.case_stmt.default_label
4440             = build_decl (LABEL_DECL, NULL_TREE, NULL_TREE);
4441           /* Share the exit label if possible.  */
4442           if (thiscase->exit_label)
4443             {
4444               SET_DECL_RTL (thiscase->data.case_stmt.default_label,
4445                             thiscase->exit_label);
4446               exit_done = true;
4447             }
4448           expand_label (thiscase->data.case_stmt.default_label);
4449         }
4450       default_label = label_rtx (thiscase->data.case_stmt.default_label);
4451
4452       before_case = get_last_insn ();
4453
4454       if (thiscase->data.case_stmt.case_list
4455           && thiscase->data.case_stmt.case_list->left)
4456         thiscase->data.case_stmt.case_list
4457           = case_tree2list (thiscase->data.case_stmt.case_list, 0);
4458
4459       /* Simplify the case-list before we count it.  */
4460       group_case_nodes (thiscase->data.case_stmt.case_list);
4461       strip_default_case_nodes (&thiscase->data.case_stmt.case_list,
4462                                 default_label);
4463
4464       /* Get upper and lower bounds of case values.
4465          Also convert all the case values to the index expr's data type.  */
4466
4467       uniq = 0;
4468       count = 0;
4469       for (n = thiscase->data.case_stmt.case_list; n; n = n->right)
4470         {
4471           /* Check low and high label values are integers.  */
4472           if (TREE_CODE (n->low) != INTEGER_CST)
4473             abort ();
4474           if (TREE_CODE (n->high) != INTEGER_CST)
4475             abort ();
4476
4477           n->low = convert (index_type, n->low);
4478           n->high = convert (index_type, n->high);
4479
4480           /* Count the elements and track the largest and smallest
4481              of them (treating them as signed even if they are not).  */
4482           if (count++ == 0)
4483             {
4484               minval = n->low;
4485               maxval = n->high;
4486             }
4487           else
4488             {
4489               if (INT_CST_LT (n->low, minval))
4490                 minval = n->low;
4491               if (INT_CST_LT (maxval, n->high))
4492                 maxval = n->high;
4493             }
4494           /* A range counts double, since it requires two compares.  */
4495           if (! tree_int_cst_equal (n->low, n->high))
4496             count++;
4497
4498           /* Count the number of unique case node targets.  */
4499           uniq++;
4500           lab = label_rtx (n->code_label);
4501           for (m = thiscase->data.case_stmt.case_list; m != n; m = m->right)
4502             if (same_case_target_p (label_rtx (m->code_label), lab))
4503               {
4504                 uniq--;
4505                 break;
4506               }
4507         }
4508
4509       /* Compute span of values.  */
4510       if (count != 0)
4511         range = fold (build (MINUS_EXPR, index_type, maxval, minval));
4512
4513       end_cleanup_deferral ();
4514
4515       if (count == 0)
4516         {
4517           expand_expr (index_expr, const0_rtx, VOIDmode, 0);
4518           emit_queue ();
4519           emit_jump (default_label);
4520         }
4521
4522       /* Try implementing this switch statement by a short sequence of
4523          bit-wise comparisons.  However, we let the binary-tree case
4524          below handle constant index expressions.  */
4525       else if (CASE_USE_BIT_TESTS
4526                && ! TREE_CONSTANT (index_expr)
4527                && compare_tree_int (range, GET_MODE_BITSIZE (word_mode)) < 0
4528                && compare_tree_int (range, 0) > 0
4529                && lshift_cheap_p ()
4530                && ((uniq == 1 && count >= 3)
4531                    || (uniq == 2 && count >= 5)
4532                    || (uniq == 3 && count >= 6)))
4533         {
4534           /* Optimize the case where all the case values fit in a
4535              word without having to subtract MINVAL.  In this case,
4536              we can optimize away the subtraction.  */
4537           if (compare_tree_int (minval, 0) > 0
4538               && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
4539             {
4540               minval = integer_zero_node;
4541               range = maxval;
4542             }
4543           emit_case_bit_tests (index_type, index_expr, minval, range,
4544                                thiscase->data.case_stmt.case_list,
4545                                default_label);
4546         }
4547
4548       /* If range of values is much bigger than number of values,
4549          make a sequence of conditional branches instead of a dispatch.
4550          If the switch-index is a constant, do it this way
4551          because we can optimize it.  */
4552
4553       else if (count < case_values_threshold ()
4554                || compare_tree_int (range,
4555                                     (optimize_size ? 3 : 10) * count) > 0
4556                /* RANGE may be signed, and really large ranges will show up
4557                   as negative numbers.  */
4558                || compare_tree_int (range, 0) < 0
4559 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
4560                || flag_pic
4561 #endif
4562                || TREE_CONSTANT (index_expr)
4563                /* If neither casesi or tablejump is available, we can
4564                   only go this way.  */
4565                || (!HAVE_casesi && !HAVE_tablejump))
4566         {
4567           index = expand_expr (index_expr, NULL_RTX, VOIDmode, 0);
4568
4569           /* If the index is a short or char that we do not have
4570              an insn to handle comparisons directly, convert it to
4571              a full integer now, rather than letting each comparison
4572              generate the conversion.  */
4573
4574           if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
4575               && ! have_insn_for (COMPARE, GET_MODE (index)))
4576             {
4577               enum machine_mode wider_mode;
4578               for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
4579                    wider_mode = GET_MODE_WIDER_MODE (wider_mode))
4580                 if (have_insn_for (COMPARE, wider_mode))
4581                   {
4582                     index = convert_to_mode (wider_mode, index, unsignedp);
4583                     break;
4584                   }
4585             }
4586
4587           emit_queue ();
4588           do_pending_stack_adjust ();
4589
4590           index = protect_from_queue (index, 0);
4591           if (GET_CODE (index) == MEM)
4592             index = copy_to_reg (index);
4593           if (GET_CODE (index) == CONST_INT
4594               || TREE_CODE (index_expr) == INTEGER_CST)
4595             {
4596               /* Make a tree node with the proper constant value
4597                  if we don't already have one.  */
4598               if (TREE_CODE (index_expr) != INTEGER_CST)
4599                 {
4600                   index_expr
4601                     = build_int_2 (INTVAL (index),
4602                                    unsignedp || INTVAL (index) >= 0 ? 0 : -1);
4603                   index_expr = convert (index_type, index_expr);
4604                 }
4605
4606               /* For constant index expressions we need only
4607                  issue an unconditional branch to the appropriate
4608                  target code.  The job of removing any unreachable
4609                  code is left to the optimization phase if the
4610                  "-O" option is specified.  */
4611               for (n = thiscase->data.case_stmt.case_list; n; n = n->right)
4612                 if (! tree_int_cst_lt (index_expr, n->low)
4613                     && ! tree_int_cst_lt (n->high, index_expr))
4614                   break;
4615
4616               if (n)
4617                 emit_jump (label_rtx (n->code_label));
4618               else
4619                 emit_jump (default_label);
4620             }
4621           else
4622             {
4623               /* If the index expression is not constant we generate
4624                  a binary decision tree to select the appropriate
4625                  target code.  This is done as follows:
4626
4627                  The list of cases is rearranged into a binary tree,
4628                  nearly optimal assuming equal probability for each case.
4629
4630                  The tree is transformed into RTL, eliminating
4631                  redundant test conditions at the same time.
4632
4633                  If program flow could reach the end of the
4634                  decision tree an unconditional jump to the
4635                  default code is emitted.  */
4636
4637               use_cost_table
4638                 = (TREE_CODE (orig_type) != ENUMERAL_TYPE
4639                    && estimate_case_costs (thiscase->data.case_stmt.case_list));
4640               balance_case_nodes (&thiscase->data.case_stmt.case_list, NULL);
4641               emit_case_nodes (index, thiscase->data.case_stmt.case_list,
4642                                default_label, index_type);
4643               emit_jump_if_reachable (default_label);
4644             }
4645         }
4646       else
4647         {
4648           table_label = gen_label_rtx ();
4649           if (! try_casesi (index_type, index_expr, minval, range,
4650                             table_label, default_label))
4651             {
4652               index_type = thiscase->data.case_stmt.nominal_type;
4653
4654               /* Index jumptables from zero for suitable values of
4655                  minval to avoid a subtraction.  */
4656               if (! optimize_size
4657                   && compare_tree_int (minval, 0) > 0
4658                   && compare_tree_int (minval, 3) < 0)
4659                 {
4660                   minval = integer_zero_node;
4661                   range = maxval;
4662                 }
4663
4664               if (! try_tablejump (index_type, index_expr, minval, range,
4665                                    table_label, default_label))
4666                 abort ();
4667             }
4668
4669           /* Get table of labels to jump to, in order of case index.  */
4670
4671           ncases = tree_low_cst (range, 0) + 1;
4672           labelvec = alloca (ncases * sizeof (rtx));
4673           memset (labelvec, 0, ncases * sizeof (rtx));
4674
4675           for (n = thiscase->data.case_stmt.case_list; n; n = n->right)
4676             {
4677               /* Compute the low and high bounds relative to the minimum
4678                  value since that should fit in a HOST_WIDE_INT while the
4679                  actual values may not.  */
4680               HOST_WIDE_INT i_low
4681                 = tree_low_cst (fold (build (MINUS_EXPR, index_type,
4682                                              n->low, minval)), 1);
4683               HOST_WIDE_INT i_high
4684                 = tree_low_cst (fold (build (MINUS_EXPR, index_type,
4685                                              n->high, minval)), 1);
4686               HOST_WIDE_INT i;
4687
4688               for (i = i_low; i <= i_high; i ++)
4689                 labelvec[i]
4690                   = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
4691             }
4692
4693           /* Fill in the gaps with the default.  */
4694           for (i = 0; i < ncases; i++)
4695             if (labelvec[i] == 0)
4696               labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
4697
4698           /* Output the table.  */
4699           emit_label (table_label);
4700
4701           if (CASE_VECTOR_PC_RELATIVE || flag_pic)
4702             emit_jump_insn (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
4703                                                    gen_rtx_LABEL_REF (Pmode, table_label),
4704                                                    gen_rtvec_v (ncases, labelvec),
4705                                                    const0_rtx, const0_rtx));
4706           else
4707             emit_jump_insn (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
4708                                               gen_rtvec_v (ncases, labelvec)));
4709
4710           /* If the case insn drops through the table,
4711              after the table we must jump to the default-label.
4712              Otherwise record no drop-through after the table.  */
4713 #ifdef CASE_DROPS_THROUGH
4714           emit_jump (default_label);
4715 #else
4716           emit_barrier ();
4717 #endif
4718         }
4719
4720       before_case = NEXT_INSN (before_case);
4721       end = get_last_insn ();
4722       if (squeeze_notes (&before_case, &end))
4723         abort ();
4724       reorder_insns (before_case, end,
4725                      thiscase->data.case_stmt.start);
4726     }
4727   else
4728     end_cleanup_deferral ();
4729
4730   if (thiscase->exit_label && !exit_done)
4731     emit_label (thiscase->exit_label);
4732
4733   POPSTACK (case_stack);
4734
4735   free_temp_slots ();
4736 }
4737
4738 /* Convert the tree NODE into a list linked by the right field, with the left
4739    field zeroed.  RIGHT is used for recursion; it is a list to be placed
4740    rightmost in the resulting list.  */
4741
4742 static struct case_node *
4743 case_tree2list (struct case_node *node, struct case_node *right)
4744 {
4745   struct case_node *left;
4746
4747   if (node->right)
4748     right = case_tree2list (node->right, right);
4749
4750   node->right = right;
4751   if ((left = node->left))
4752     {
4753       node->left = 0;
4754       return case_tree2list (left, node);
4755     }
4756
4757   return node;
4758 }
4759
4760 /* Generate code to jump to LABEL if OP1 and OP2 are equal.  */
4761
4762 static void
4763 do_jump_if_equal (rtx op1, rtx op2, rtx label, int unsignedp)
4764 {
4765   if (GET_CODE (op1) == CONST_INT && GET_CODE (op2) == CONST_INT)
4766     {
4767       if (op1 == op2)
4768         emit_jump (label);
4769     }
4770   else
4771     emit_cmp_and_jump_insns (op1, op2, EQ, NULL_RTX,
4772                              (GET_MODE (op1) == VOIDmode
4773                              ? GET_MODE (op2) : GET_MODE (op1)),
4774                              unsignedp, label);
4775 }
4776 \f
4777 /* Not all case values are encountered equally.  This function
4778    uses a heuristic to weight case labels, in cases where that
4779    looks like a reasonable thing to do.
4780
4781    Right now, all we try to guess is text, and we establish the
4782    following weights:
4783
4784         chars above space:      16
4785         digits:                 16
4786         default:                12
4787         space, punct:           8
4788         tab:                    4
4789         newline:                2
4790         other "\" chars:        1
4791         remaining chars:        0
4792
4793    If we find any cases in the switch that are not either -1 or in the range
4794    of valid ASCII characters, or are control characters other than those
4795    commonly used with "\", don't treat this switch scanning text.
4796
4797    Return 1 if these nodes are suitable for cost estimation, otherwise
4798    return 0.  */
4799
4800 static int
4801 estimate_case_costs (case_node_ptr node)
4802 {
4803   tree min_ascii = integer_minus_one_node;
4804   tree max_ascii = convert (TREE_TYPE (node->high), build_int_2 (127, 0));
4805   case_node_ptr n;
4806   int i;
4807
4808   /* If we haven't already made the cost table, make it now.  Note that the
4809      lower bound of the table is -1, not zero.  */
4810
4811   if (! cost_table_initialized)
4812     {
4813       cost_table_initialized = 1;
4814
4815       for (i = 0; i < 128; i++)
4816         {
4817           if (ISALNUM (i))
4818             COST_TABLE (i) = 16;
4819           else if (ISPUNCT (i))
4820             COST_TABLE (i) = 8;
4821           else if (ISCNTRL (i))
4822             COST_TABLE (i) = -1;
4823         }
4824
4825       COST_TABLE (' ') = 8;
4826       COST_TABLE ('\t') = 4;
4827       COST_TABLE ('\0') = 4;
4828       COST_TABLE ('\n') = 2;
4829       COST_TABLE ('\f') = 1;
4830       COST_TABLE ('\v') = 1;
4831       COST_TABLE ('\b') = 1;
4832     }
4833
4834   /* See if all the case expressions look like text.  It is text if the
4835      constant is >= -1 and the highest constant is <= 127.  Do all comparisons
4836      as signed arithmetic since we don't want to ever access cost_table with a
4837      value less than -1.  Also check that none of the constants in a range
4838      are strange control characters.  */
4839
4840   for (n = node; n; n = n->right)
4841     {
4842       if ((INT_CST_LT (n->low, min_ascii)) || INT_CST_LT (max_ascii, n->high))
4843         return 0;
4844
4845       for (i = (HOST_WIDE_INT) TREE_INT_CST_LOW (n->low);
4846            i <= (HOST_WIDE_INT) TREE_INT_CST_LOW (n->high); i++)
4847         if (COST_TABLE (i) < 0)
4848           return 0;
4849     }
4850
4851   /* All interesting values are within the range of interesting
4852      ASCII characters.  */
4853   return 1;
4854 }
4855
4856 /* Determine whether two case labels branch to the same target.  */
4857
4858 static bool
4859 same_case_target_p (rtx l1, rtx l2)
4860 {
4861 #if 0
4862   rtx i1, i2;
4863
4864   if (l1 == l2)
4865     return true;
4866
4867   i1 = next_real_insn (l1);
4868   i2 = next_real_insn (l2);
4869   if (i1 == i2)
4870     return true;
4871
4872   if (i1 && simplejump_p (i1))
4873     {
4874       l1 = XEXP (SET_SRC (PATTERN (i1)), 0);
4875     }
4876
4877   if (i2 && simplejump_p (i2))
4878     {
4879       l2 = XEXP (SET_SRC (PATTERN (i2)), 0);
4880     }
4881 #endif
4882   /* When coming from gimple, we usually won't have emitted either
4883      the labels or the body of the switch statement.  The job being
4884      done here should be done via jump threading at the tree level.
4885      Cases that go the same place should have the same label.  */
4886   return l1 == l2;
4887 }
4888
4889 /* Delete nodes that branch to the default label from a list of
4890    case nodes.  Eg. case 5: default: becomes just default:  */
4891
4892 static void
4893 strip_default_case_nodes (case_node_ptr *prev, rtx deflab)
4894 {
4895   case_node_ptr ptr;
4896
4897   while (*prev)
4898     {
4899       ptr = *prev;
4900       if (same_case_target_p (label_rtx (ptr->code_label), deflab))
4901         *prev = ptr->right;
4902       else
4903         prev = &ptr->right;
4904     }
4905 }
4906
4907 /* Scan an ordered list of case nodes
4908    combining those with consecutive values or ranges.
4909
4910    Eg. three separate entries 1: 2: 3: become one entry 1..3:  */
4911
4912 static void
4913 group_case_nodes (case_node_ptr head)
4914 {
4915   case_node_ptr node = head;
4916
4917   while (node)
4918     {
4919       rtx lab;
4920       case_node_ptr np = node;
4921
4922       lab = label_rtx (node->code_label);
4923
4924       /* Try to group the successors of NODE with NODE.  */
4925       while (((np = np->right) != 0)
4926              /* Do they jump to the same place?  */
4927              && same_case_target_p (label_rtx (np->code_label), lab)
4928              /* Are their ranges consecutive?  */
4929              && tree_int_cst_equal (np->low,
4930                                     fold (build (PLUS_EXPR,
4931                                                  TREE_TYPE (node->high),
4932                                                  node->high,
4933                                                  integer_one_node)))
4934              /* An overflow is not consecutive.  */
4935              && tree_int_cst_lt (node->high,
4936                                  fold (build (PLUS_EXPR,
4937                                               TREE_TYPE (node->high),
4938                                               node->high,
4939                                               integer_one_node))))
4940         {
4941           node->high = np->high;
4942         }
4943       /* NP is the first node after NODE which can't be grouped with it.
4944          Delete the nodes in between, and move on to that node.  */
4945       node->right = np;
4946       node = np;
4947     }
4948 }
4949
4950 /* Take an ordered list of case nodes
4951    and transform them into a near optimal binary tree,
4952    on the assumption that any target code selection value is as
4953    likely as any other.
4954
4955    The transformation is performed by splitting the ordered
4956    list into two equal sections plus a pivot.  The parts are
4957    then attached to the pivot as left and right branches.  Each
4958    branch is then transformed recursively.  */
4959
4960 static void
4961 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
4962 {
4963   case_node_ptr np;
4964
4965   np = *head;
4966   if (np)
4967     {
4968       int cost = 0;
4969       int i = 0;
4970       int ranges = 0;
4971       case_node_ptr *npp;
4972       case_node_ptr left;
4973
4974       /* Count the number of entries on branch.  Also count the ranges.  */
4975
4976       while (np)
4977         {
4978           if (!tree_int_cst_equal (np->low, np->high))
4979             {
4980               ranges++;
4981               if (use_cost_table)
4982                 cost += COST_TABLE (TREE_INT_CST_LOW (np->high));
4983             }
4984
4985           if (use_cost_table)
4986             cost += COST_TABLE (TREE_INT_CST_LOW (np->low));
4987
4988           i++;
4989           np = np->right;
4990         }
4991
4992       if (i > 2)
4993         {
4994           /* Split this list if it is long enough for that to help.  */
4995           npp = head;
4996           left = *npp;
4997           if (use_cost_table)
4998             {
4999               /* Find the place in the list that bisects the list's total cost,
5000                  Here I gets half the total cost.  */
5001               int n_moved = 0;
5002               i = (cost + 1) / 2;
5003               while (1)
5004                 {
5005                   /* Skip nodes while their cost does not reach that amount.  */
5006                   if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
5007                     i -= COST_TABLE (TREE_INT_CST_LOW ((*npp)->high));
5008                   i -= COST_TABLE (TREE_INT_CST_LOW ((*npp)->low));
5009                   if (i <= 0)
5010                     break;
5011                   npp = &(*npp)->right;
5012                   n_moved += 1;
5013                 }
5014               if (n_moved == 0)
5015                 {
5016                   /* Leave this branch lopsided, but optimize left-hand
5017                      side and fill in `parent' fields for right-hand side.  */
5018                   np = *head;
5019                   np->parent = parent;
5020                   balance_case_nodes (&np->left, np);
5021                   for (; np->right; np = np->right)
5022                     np->right->parent = np;
5023                   return;
5024                 }
5025             }
5026           /* If there are just three nodes, split at the middle one.  */
5027           else if (i == 3)
5028             npp = &(*npp)->right;
5029           else
5030             {
5031               /* Find the place in the list that bisects the list's total cost,
5032                  where ranges count as 2.
5033                  Here I gets half the total cost.  */
5034               i = (i + ranges + 1) / 2;
5035               while (1)
5036                 {
5037                   /* Skip nodes while their cost does not reach that amount.  */
5038                   if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
5039                     i--;
5040                   i--;
5041                   if (i <= 0)
5042                     break;
5043                   npp = &(*npp)->right;
5044                 }
5045             }
5046           *head = np = *npp;
5047           *npp = 0;
5048           np->parent = parent;
5049           np->left = left;
5050
5051           /* Optimize each of the two split parts.  */
5052           balance_case_nodes (&np->left, np);
5053           balance_case_nodes (&np->right, np);
5054         }
5055       else
5056         {
5057           /* Else leave this branch as one level,
5058              but fill in `parent' fields.  */
5059           np = *head;
5060           np->parent = parent;
5061           for (; np->right; np = np->right)
5062             np->right->parent = np;
5063         }
5064     }
5065 }
5066 \f
5067 /* Search the parent sections of the case node tree
5068    to see if a test for the lower bound of NODE would be redundant.
5069    INDEX_TYPE is the type of the index expression.
5070
5071    The instructions to generate the case decision tree are
5072    output in the same order as nodes are processed so it is
5073    known that if a parent node checks the range of the current
5074    node minus one that the current node is bounded at its lower
5075    span.  Thus the test would be redundant.  */
5076
5077 static int
5078 node_has_low_bound (case_node_ptr node, tree index_type)
5079 {
5080   tree low_minus_one;
5081   case_node_ptr pnode;
5082
5083   /* If the lower bound of this node is the lowest value in the index type,
5084      we need not test it.  */
5085
5086   if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
5087     return 1;
5088
5089   /* If this node has a left branch, the value at the left must be less
5090      than that at this node, so it cannot be bounded at the bottom and
5091      we need not bother testing any further.  */
5092
5093   if (node->left)
5094     return 0;
5095
5096   low_minus_one = fold (build (MINUS_EXPR, TREE_TYPE (node->low),
5097                                node->low, integer_one_node));
5098
5099   /* If the subtraction above overflowed, we can't verify anything.
5100      Otherwise, look for a parent that tests our value - 1.  */
5101
5102   if (! tree_int_cst_lt (low_minus_one, node->low))
5103     return 0;
5104
5105   for (pnode = node->parent; pnode; pnode = pnode->parent)
5106     if (tree_int_cst_equal (low_minus_one, pnode->high))
5107       return 1;
5108
5109   return 0;
5110 }
5111
5112 /* Search the parent sections of the case node tree
5113    to see if a test for the upper bound of NODE would be redundant.
5114    INDEX_TYPE is the type of the index expression.
5115
5116    The instructions to generate the case decision tree are
5117    output in the same order as nodes are processed so it is
5118    known that if a parent node checks the range of the current
5119    node plus one that the current node is bounded at its upper
5120    span.  Thus the test would be redundant.  */
5121
5122 static int
5123 node_has_high_bound (case_node_ptr node, tree index_type)
5124 {
5125   tree high_plus_one;
5126   case_node_ptr pnode;
5127
5128   /* If there is no upper bound, obviously no test is needed.  */
5129
5130   if (TYPE_MAX_VALUE (index_type) == NULL)
5131     return 1;
5132
5133   /* If the upper bound of this node is the highest value in the type
5134      of the index expression, we need not test against it.  */
5135
5136   if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
5137     return 1;
5138
5139   /* If this node has a right branch, the value at the right must be greater
5140      than that at this node, so it cannot be bounded at the top and
5141      we need not bother testing any further.  */
5142
5143   if (node->right)
5144     return 0;
5145
5146   high_plus_one = fold (build (PLUS_EXPR, TREE_TYPE (node->high),
5147                                node->high, integer_one_node));
5148
5149   /* If the addition above overflowed, we can't verify anything.
5150      Otherwise, look for a parent that tests our value + 1.  */
5151
5152   if (! tree_int_cst_lt (node->high, high_plus_one))
5153     return 0;
5154
5155   for (pnode = node->parent; pnode; pnode = pnode->parent)
5156     if (tree_int_cst_equal (high_plus_one, pnode->low))
5157       return 1;
5158
5159   return 0;
5160 }
5161
5162 /* Search the parent sections of the
5163    case node tree to see if both tests for the upper and lower
5164    bounds of NODE would be redundant.  */
5165
5166 static int
5167 node_is_bounded (case_node_ptr node, tree index_type)
5168 {
5169   return (node_has_low_bound (node, index_type)
5170           && node_has_high_bound (node, index_type));
5171 }
5172
5173 /*  Emit an unconditional jump to LABEL unless it would be dead code.  */
5174
5175 static void
5176 emit_jump_if_reachable (rtx label)
5177 {
5178   if (GET_CODE (get_last_insn ()) != BARRIER)
5179     emit_jump (label);
5180 }
5181 \f
5182 /* Emit step-by-step code to select a case for the value of INDEX.
5183    The thus generated decision tree follows the form of the
5184    case-node binary tree NODE, whose nodes represent test conditions.
5185    INDEX_TYPE is the type of the index of the switch.
5186
5187    Care is taken to prune redundant tests from the decision tree
5188    by detecting any boundary conditions already checked by
5189    emitted rtx.  (See node_has_high_bound, node_has_low_bound
5190    and node_is_bounded, above.)
5191
5192    Where the test conditions can be shown to be redundant we emit
5193    an unconditional jump to the target code.  As a further
5194    optimization, the subordinates of a tree node are examined to
5195    check for bounded nodes.  In this case conditional and/or
5196    unconditional jumps as a result of the boundary check for the
5197    current node are arranged to target the subordinates associated
5198    code for out of bound conditions on the current node.
5199
5200    We can assume that when control reaches the code generated here,
5201    the index value has already been compared with the parents
5202    of this node, and determined to be on the same side of each parent
5203    as this node is.  Thus, if this node tests for the value 51,
5204    and a parent tested for 52, we don't need to consider
5205    the possibility of a value greater than 51.  If another parent
5206    tests for the value 50, then this node need not test anything.  */
5207
5208 static void
5209 emit_case_nodes (rtx index, case_node_ptr node, rtx default_label,
5210                  tree index_type)
5211 {
5212   /* If INDEX has an unsigned type, we must make unsigned branches.  */
5213   int unsignedp = TYPE_UNSIGNED (index_type);
5214   enum machine_mode mode = GET_MODE (index);
5215   enum machine_mode imode = TYPE_MODE (index_type);
5216
5217   /* See if our parents have already tested everything for us.
5218      If they have, emit an unconditional jump for this node.  */
5219   if (node_is_bounded (node, index_type))
5220     emit_jump (label_rtx (node->code_label));
5221
5222   else if (tree_int_cst_equal (node->low, node->high))
5223     {
5224       /* Node is single valued.  First see if the index expression matches
5225          this node and then check our children, if any.  */
5226
5227       do_jump_if_equal (index,
5228                         convert_modes (mode, imode,
5229                                        expand_expr (node->low, NULL_RTX,
5230                                                     VOIDmode, 0),
5231                                        unsignedp),
5232                         label_rtx (node->code_label), unsignedp);
5233
5234       if (node->right != 0 && node->left != 0)
5235         {
5236           /* This node has children on both sides.
5237              Dispatch to one side or the other
5238              by comparing the index value with this node's value.
5239              If one subtree is bounded, check that one first,
5240              so we can avoid real branches in the tree.  */
5241
5242           if (node_is_bounded (node->right, index_type))
5243             {
5244               emit_cmp_and_jump_insns (index,
5245                                        convert_modes
5246                                        (mode, imode,
5247                                         expand_expr (node->high, NULL_RTX,
5248                                                      VOIDmode, 0),
5249                                         unsignedp),
5250                                        GT, NULL_RTX, mode, unsignedp,
5251                                        label_rtx (node->right->code_label));
5252               emit_case_nodes (index, node->left, default_label, index_type);
5253             }
5254
5255           else if (node_is_bounded (node->left, index_type))
5256             {
5257               emit_cmp_and_jump_insns (index,
5258                                        convert_modes
5259                                        (mode, imode,
5260                                         expand_expr (node->high, NULL_RTX,
5261                                                      VOIDmode, 0),
5262                                         unsignedp),
5263                                        LT, NULL_RTX, mode, unsignedp,
5264                                        label_rtx (node->left->code_label));
5265               emit_case_nodes (index, node->right, default_label, index_type);
5266             }
5267
5268           /* If both children are single-valued cases with no
5269              children, finish up all the work.  This way, we can save
5270              one ordered comparison.  */
5271           else if (tree_int_cst_equal (node->right->low, node->right->high)
5272                    && node->right->left == 0
5273                    && node->right->right == 0
5274                    && tree_int_cst_equal (node->left->low, node->left->high)
5275                    && node->left->left == 0
5276                    && node->left->right == 0)
5277             {
5278               /* Neither node is bounded.  First distinguish the two sides;
5279                  then emit the code for one side at a time.  */
5280
5281               /* See if the value matches what the right hand side
5282                  wants.  */
5283               do_jump_if_equal (index,
5284                                 convert_modes (mode, imode,
5285                                                expand_expr (node->right->low,
5286                                                             NULL_RTX,
5287                                                             VOIDmode, 0),
5288                                                unsignedp),
5289                                 label_rtx (node->right->code_label),
5290                                 unsignedp);
5291
5292               /* See if the value matches what the left hand side
5293                  wants.  */
5294               do_jump_if_equal (index,
5295                                 convert_modes (mode, imode,
5296                                                expand_expr (node->left->low,
5297                                                             NULL_RTX,
5298                                                             VOIDmode, 0),
5299                                                unsignedp),
5300                                 label_rtx (node->left->code_label),
5301                                 unsignedp);
5302             }
5303
5304           else
5305             {
5306               /* Neither node is bounded.  First distinguish the two sides;
5307                  then emit the code for one side at a time.  */
5308
5309               tree test_label = build_decl (LABEL_DECL, NULL_TREE, NULL_TREE);
5310
5311               /* See if the value is on the right.  */
5312               emit_cmp_and_jump_insns (index,
5313                                        convert_modes
5314                                        (mode, imode,
5315                                         expand_expr (node->high, NULL_RTX,
5316                                                      VOIDmode, 0),
5317                                         unsignedp),
5318                                        GT, NULL_RTX, mode, unsignedp,
5319                                        label_rtx (test_label));
5320
5321               /* Value must be on the left.
5322                  Handle the left-hand subtree.  */
5323               emit_case_nodes (index, node->left, default_label, index_type);
5324               /* If left-hand subtree does nothing,
5325                  go to default.  */
5326               emit_jump_if_reachable (default_label);
5327
5328               /* Code branches here for the right-hand subtree.  */
5329               expand_label (test_label);
5330               emit_case_nodes (index, node->right, default_label, index_type);
5331             }
5332         }
5333
5334       else if (node->right != 0 && node->left == 0)
5335         {
5336           /* Here we have a right child but no left so we issue conditional
5337              branch to default and process the right child.
5338
5339              Omit the conditional branch to default if we it avoid only one
5340              right child; it costs too much space to save so little time.  */
5341
5342           if (node->right->right || node->right->left
5343               || !tree_int_cst_equal (node->right->low, node->right->high))
5344             {
5345               if (!node_has_low_bound (node, index_type))
5346                 {
5347                   emit_cmp_and_jump_insns (index,
5348                                            convert_modes
5349                                            (mode, imode,
5350                                             expand_expr (node->high, NULL_RTX,
5351                                                          VOIDmode, 0),
5352                                             unsignedp),
5353                                            LT, NULL_RTX, mode, unsignedp,
5354                                            default_label);
5355                 }
5356
5357               emit_case_nodes (index, node->right, default_label, index_type);
5358             }
5359           else
5360             /* We cannot process node->right normally
5361                since we haven't ruled out the numbers less than
5362                this node's value.  So handle node->right explicitly.  */
5363             do_jump_if_equal (index,
5364                               convert_modes
5365                               (mode, imode,
5366                                expand_expr (node->right->low, NULL_RTX,
5367                                             VOIDmode, 0),
5368                                unsignedp),
5369                               label_rtx (node->right->code_label), unsignedp);
5370         }
5371
5372       else if (node->right == 0 && node->left != 0)
5373         {
5374           /* Just one subtree, on the left.  */
5375           if (node->left->left || node->left->right
5376               || !tree_int_cst_equal (node->left->low, node->left->high))
5377             {
5378               if (!node_has_high_bound (node, index_type))
5379                 {
5380                   emit_cmp_and_jump_insns (index,
5381                                            convert_modes
5382                                            (mode, imode,
5383                                             expand_expr (node->high, NULL_RTX,
5384                                                          VOIDmode, 0),
5385                                             unsignedp),
5386                                            GT, NULL_RTX, mode, unsignedp,
5387                                            default_label);
5388                 }
5389
5390               emit_case_nodes (index, node->left, default_label, index_type);
5391             }
5392           else
5393             /* We cannot process node->left normally
5394                since we haven't ruled out the numbers less than
5395                this node's value.  So handle node->left explicitly.  */
5396             do_jump_if_equal (index,
5397                               convert_modes
5398                               (mode, imode,
5399                                expand_expr (node->left->low, NULL_RTX,
5400                                             VOIDmode, 0),
5401                                unsignedp),
5402                               label_rtx (node->left->code_label), unsignedp);
5403         }
5404     }
5405   else
5406     {
5407       /* Node is a range.  These cases are very similar to those for a single
5408          value, except that we do not start by testing whether this node
5409          is the one to branch to.  */
5410
5411       if (node->right != 0 && node->left != 0)
5412         {
5413           /* Node has subtrees on both sides.
5414              If the right-hand subtree is bounded,
5415              test for it first, since we can go straight there.
5416              Otherwise, we need to make a branch in the control structure,
5417              then handle the two subtrees.  */
5418           tree test_label = 0;
5419
5420           if (node_is_bounded (node->right, index_type))
5421             /* Right hand node is fully bounded so we can eliminate any
5422                testing and branch directly to the target code.  */
5423             emit_cmp_and_jump_insns (index,
5424                                      convert_modes
5425                                      (mode, imode,
5426                                       expand_expr (node->high, NULL_RTX,
5427                                                    VOIDmode, 0),
5428                                       unsignedp),
5429                                      GT, NULL_RTX, mode, unsignedp,
5430                                      label_rtx (node->right->code_label));
5431           else
5432             {
5433               /* Right hand node requires testing.
5434                  Branch to a label where we will handle it later.  */
5435
5436               test_label = build_decl (LABEL_DECL, NULL_TREE, NULL_TREE);
5437               emit_cmp_and_jump_insns (index,
5438                                        convert_modes
5439                                        (mode, imode,
5440                                         expand_expr (node->high, NULL_RTX,
5441                                                      VOIDmode, 0),
5442                                         unsignedp),
5443                                        GT, NULL_RTX, mode, unsignedp,
5444                                        label_rtx (test_label));
5445             }
5446
5447           /* Value belongs to this node or to the left-hand subtree.  */
5448
5449           emit_cmp_and_jump_insns (index,
5450                                    convert_modes
5451                                    (mode, imode,
5452                                     expand_expr (node->low, NULL_RTX,
5453                                                  VOIDmode, 0),
5454                                     unsignedp),
5455                                    GE, NULL_RTX, mode, unsignedp,
5456                                    label_rtx (node->code_label));
5457
5458           /* Handle the left-hand subtree.  */
5459           emit_case_nodes (index, node->left, default_label, index_type);
5460
5461           /* If right node had to be handled later, do that now.  */
5462
5463           if (test_label)
5464             {
5465               /* If the left-hand subtree fell through,
5466                  don't let it fall into the right-hand subtree.  */
5467               emit_jump_if_reachable (default_label);
5468
5469               expand_label (test_label);
5470               emit_case_nodes (index, node->right, default_label, index_type);
5471             }
5472         }
5473
5474       else if (node->right != 0 && node->left == 0)
5475         {
5476           /* Deal with values to the left of this node,
5477              if they are possible.  */
5478           if (!node_has_low_bound (node, index_type))
5479             {
5480               emit_cmp_and_jump_insns (index,
5481                                        convert_modes
5482                                        (mode, imode,
5483                                         expand_expr (node->low, NULL_RTX,
5484                                                      VOIDmode, 0),
5485                                         unsignedp),
5486                                        LT, NULL_RTX, mode, unsignedp,
5487                                        default_label);
5488             }
5489
5490           /* Value belongs to this node or to the right-hand subtree.  */
5491
5492           emit_cmp_and_jump_insns (index,
5493                                    convert_modes
5494                                    (mode, imode,
5495                                     expand_expr (node->high, NULL_RTX,
5496                                                  VOIDmode, 0),
5497                                     unsignedp),
5498                                    LE, NULL_RTX, mode, unsignedp,
5499                                    label_rtx (node->code_label));
5500
5501           emit_case_nodes (index, node->right, default_label, index_type);
5502         }
5503
5504       else if (node->right == 0 && node->left != 0)
5505         {
5506           /* Deal with values to the right of this node,
5507              if they are possible.  */
5508           if (!node_has_high_bound (node, index_type))
5509             {
5510               emit_cmp_and_jump_insns (index,
5511                                        convert_modes
5512                                        (mode, imode,
5513                                         expand_expr (node->high, NULL_RTX,
5514                                                      VOIDmode, 0),
5515                                         unsignedp),
5516                                        GT, NULL_RTX, mode, unsignedp,
5517                                        default_label);
5518             }
5519
5520           /* Value belongs to this node or to the left-hand subtree.  */
5521
5522           emit_cmp_and_jump_insns (index,
5523                                    convert_modes
5524                                    (mode, imode,
5525                                     expand_expr (node->low, NULL_RTX,
5526                                                  VOIDmode, 0),
5527                                     unsignedp),
5528                                    GE, NULL_RTX, mode, unsignedp,
5529                                    label_rtx (node->code_label));
5530
5531           emit_case_nodes (index, node->left, default_label, index_type);
5532         }
5533
5534       else
5535         {
5536           /* Node has no children so we check low and high bounds to remove
5537              redundant tests.  Only one of the bounds can exist,
5538              since otherwise this node is bounded--a case tested already.  */
5539           int high_bound = node_has_high_bound (node, index_type);
5540           int low_bound = node_has_low_bound (node, index_type);
5541
5542           if (!high_bound && low_bound)
5543             {
5544               emit_cmp_and_jump_insns (index,
5545                                        convert_modes
5546                                        (mode, imode,
5547                                         expand_expr (node->high, NULL_RTX,
5548                                                      VOIDmode, 0),
5549                                         unsignedp),
5550                                        GT, NULL_RTX, mode, unsignedp,
5551                                        default_label);
5552             }
5553
5554           else if (!low_bound && high_bound)
5555             {
5556               emit_cmp_and_jump_insns (index,
5557                                        convert_modes
5558                                        (mode, imode,
5559                                         expand_expr (node->low, NULL_RTX,
5560                                                      VOIDmode, 0),
5561                                         unsignedp),
5562                                        LT, NULL_RTX, mode, unsignedp,
5563                                        default_label);
5564             }
5565           else if (!low_bound && !high_bound)
5566             {
5567               /* Widen LOW and HIGH to the same width as INDEX.  */
5568               tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
5569               tree low = build1 (CONVERT_EXPR, type, node->low);
5570               tree high = build1 (CONVERT_EXPR, type, node->high);
5571               rtx low_rtx, new_index, new_bound;
5572
5573               /* Instead of doing two branches, emit one unsigned branch for
5574                  (index-low) > (high-low).  */
5575               low_rtx = expand_expr (low, NULL_RTX, mode, 0);
5576               new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
5577                                                NULL_RTX, unsignedp,
5578                                                OPTAB_WIDEN);
5579               new_bound = expand_expr (fold (build (MINUS_EXPR, type,
5580                                                     high, low)),
5581                                        NULL_RTX, mode, 0);
5582
5583               emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
5584                                        mode, 1, default_label);
5585             }
5586
5587           emit_jump (label_rtx (node->code_label));
5588         }
5589     }
5590 }
5591
5592 #include "gt-stmt.h"