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