OSDN Git Service

b84f6220a9e0645efe5d1ca95f0967b5a07f7fcc
[pf3gnuchains/gcc-fork.git] / gcc / config / sh / sh.c
1 /* Output routines for GCC for Hitachi / SuperH SH.
2    Copyright (C) 1993, 1994, 1995, 1997, 1997, 1998, 1999, 2000, 2001, 2002
3    Free Software Foundation, Inc.
4    Contributed by Steve Chamberlain (sac@cygnus.com).
5    Improved by Jim Wilson (wilson@cygnus.com). 
6
7 This file is part of GNU CC.
8
9 GNU CC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GNU CC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GNU CC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "insn-config.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "flags.h"
30 #include "expr.h"
31 #include "optabs.h"
32 #include "function.h"
33 #include "regs.h"
34 #include "hard-reg-set.h"
35 #include "output.h"
36 #include "insn-attr.h"
37 #include "toplev.h"
38 #include "recog.h"
39 #include "c-pragma.h"
40 #include "integrate.h"
41 #include "tm_p.h"
42 #include "target.h"
43 #include "target-def.h"
44
45 int code_for_indirect_jump_scratch = CODE_FOR_indirect_jump_scratch;
46
47 #define MSW (TARGET_LITTLE_ENDIAN ? 1 : 0)
48 #define LSW (TARGET_LITTLE_ENDIAN ? 0 : 1)
49
50 /* These are some macros to abstract register modes.  */
51 #define CONST_OK_FOR_ADD(size) \
52   (TARGET_SHMEDIA ? CONST_OK_FOR_P (size) : CONST_OK_FOR_I (size))
53 #define GEN_MOV (*(TARGET_SHMEDIA64 ? gen_movdi : gen_movsi))
54 #define GEN_ADD3 (*(TARGET_SHMEDIA64 ? gen_adddi3 : gen_addsi3))
55 #define GEN_SUB3 (*(TARGET_SHMEDIA64 ? gen_subdi3 : gen_subsi3))
56
57 /* Set to 1 by expand_prologue() when the function is an interrupt handler.  */
58 int current_function_interrupt;
59
60 /* ??? The pragma interrupt support will not work for SH3.  */
61 /* This is set by #pragma interrupt and #pragma trapa, and causes gcc to
62    output code for the next function appropriate for an interrupt handler.  */
63 int pragma_interrupt;
64
65 /* This is set by the trap_exit attribute for functions.   It specifies
66    a trap number to be used in a trapa instruction at function exit
67    (instead of an rte instruction).  */
68 int trap_exit;
69
70 /* This is used by the sp_switch attribute for functions.  It specifies
71    a variable holding the address of the stack the interrupt function
72    should switch to/from at entry/exit.  */
73 rtx sp_switch;
74
75 /* This is set by #pragma trapa, and is similar to the above, except that
76    the compiler doesn't emit code to preserve all registers.  */
77 static int pragma_trapa;
78
79 /* This is set by #pragma nosave_low_regs.  This is useful on the SH3,
80    which has a separate set of low regs for User and Supervisor modes.
81    This should only be used for the lowest level of interrupts.  Higher levels
82    of interrupts must save the registers in case they themselves are
83    interrupted.  */
84 int pragma_nosave_low_regs;
85
86 /* This is used for communication between SETUP_INCOMING_VARARGS and
87    sh_expand_prologue.  */
88 int current_function_anonymous_args;
89
90 /* Global variables for machine-dependent things.  */
91
92 /* Which cpu are we scheduling for.  */
93 enum processor_type sh_cpu;
94
95 /* Saved operands from the last compare to use when we generate an scc
96    or bcc insn.  */
97
98 rtx sh_compare_op0;
99 rtx sh_compare_op1;
100
101 /* Provides the class number of the smallest class containing
102    reg number.  */
103
104 int regno_reg_class[FIRST_PSEUDO_REGISTER] =
105 {
106   R0_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
107   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
108   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
109   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
110   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
111   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
112   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
113   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
114   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
115   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
116   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
117   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
118   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
119   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
120   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
121   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
122   FP0_REGS,FP_REGS, FP_REGS, FP_REGS,
123   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
124   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
125   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
126   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
127   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
128   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
129   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
130   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
131   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
132   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
133   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
134   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
135   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
136   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
137   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
138   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
139   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
140   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
141   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
142   NO_REGS, GENERAL_REGS, PR_REGS, T_REGS,
143   MAC_REGS, MAC_REGS, FPUL_REGS, FPSCR_REGS,
144   GENERAL_REGS,
145 };
146
147 char sh_register_names[FIRST_PSEUDO_REGISTER] \
148   [MAX_REGISTER_NAME_LENGTH + 1] = SH_REGISTER_NAMES_INITIALIZER;
149
150 char sh_additional_register_names[ADDREGNAMES_SIZE] \
151   [MAX_ADDITIONAL_REGISTER_NAME_LENGTH + 1]
152   = SH_ADDITIONAL_REGISTER_NAMES_INITIALIZER;
153
154 /* Provide reg_class from a letter such as appears in the machine
155    description.  */
156
157 const enum reg_class reg_class_from_letter[] =
158 {
159   /* a */ ALL_REGS, /* b */ TARGET_REGS, /* c */ FPSCR_REGS, /* d */ DF_REGS,
160   /* e */ NO_REGS, /* f */ FP_REGS, /* g */ NO_REGS, /* h */ NO_REGS,
161   /* i */ NO_REGS, /* j */ NO_REGS, /* k */ SIBCALL_REGS, /* l */ PR_REGS,
162   /* m */ NO_REGS, /* n */ NO_REGS, /* o */ NO_REGS, /* p */ NO_REGS,
163   /* q */ NO_REGS, /* r */ NO_REGS, /* s */ NO_REGS, /* t */ T_REGS,
164   /* u */ NO_REGS, /* v */ NO_REGS, /* w */ FP0_REGS, /* x */ MAC_REGS,
165   /* y */ FPUL_REGS, /* z */ R0_REGS
166 };
167
168 int assembler_dialect;
169
170 static void split_branches PARAMS ((rtx));
171 static int branch_dest PARAMS ((rtx));
172 static void force_into PARAMS ((rtx, rtx));
173 static void print_slot PARAMS ((rtx));
174 static rtx add_constant PARAMS ((rtx, enum machine_mode, rtx));
175 static void dump_table PARAMS ((rtx));
176 static int hi_const PARAMS ((rtx));
177 static int broken_move PARAMS ((rtx));
178 static int mova_p PARAMS ((rtx));
179 static rtx find_barrier PARAMS ((int, rtx, rtx));
180 static int noncall_uses_reg PARAMS ((rtx, rtx, rtx *));
181 static rtx gen_block_redirect PARAMS ((rtx, int, int));
182 static void output_stack_adjust PARAMS ((int, rtx, int));
183 static void push PARAMS ((int));
184 static void pop PARAMS ((int));
185 static void push_regs PARAMS ((HOST_WIDE_INT *));
186 static void calc_live_regs PARAMS ((int *, HOST_WIDE_INT *));
187 static void mark_use PARAMS ((rtx, rtx *));
188 static HOST_WIDE_INT rounded_frame_size PARAMS ((int));
189 static rtx mark_constant_pool_use PARAMS ((rtx));
190 const struct attribute_spec sh_attribute_table[];
191 static tree sh_handle_interrupt_handler_attribute PARAMS ((tree *, tree, tree, int, bool *));
192 static tree sh_handle_sp_switch_attribute PARAMS ((tree *, tree, tree, int, bool *));
193 static tree sh_handle_trap_exit_attribute PARAMS ((tree *, tree, tree, int, bool *));
194 static void sh_output_function_epilogue PARAMS ((FILE *, HOST_WIDE_INT));
195 static void sh_insert_attributes PARAMS ((tree, tree *));
196 #ifndef OBJECT_FORMAT_ELF
197 static void sh_asm_named_section PARAMS ((const char *, unsigned int));
198 #endif
199 static int sh_adjust_cost PARAMS ((rtx, rtx, rtx, int));
200 static int sh_use_dfa_interface PARAMS ((void));
201 static int sh_issue_rate PARAMS ((void));
202
203 static bool sh_cannot_modify_jumps_p PARAMS ((void));
204 static bool sh_ms_bitfield_layout_p PARAMS ((tree));
205
206 static void sh_encode_section_info PARAMS ((tree, int));
207 \f
208 /* Initialize the GCC target structure.  */
209 #undef TARGET_ATTRIBUTE_TABLE
210 #define TARGET_ATTRIBUTE_TABLE sh_attribute_table
211
212 /* The next two are used for debug info when compiling with -gdwarf.  */
213 #undef TARGET_ASM_UNALIGNED_HI_OP
214 #define TARGET_ASM_UNALIGNED_HI_OP "\t.uaword\t"
215 #undef TARGET_ASM_UNALIGNED_SI_OP
216 #define TARGET_ASM_UNALIGNED_SI_OP "\t.ualong\t"
217
218 /* These are NULLed out on non-SH5 in OVERRIDE_OPTIONS.  */
219 #undef TARGET_ASM_UNALIGNED_DI_OP
220 #define TARGET_ASM_UNALIGNED_DI_OP "\t.uaquad\t"
221 #undef TARGET_ASM_ALIGNED_DI_OP
222 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
223
224 #undef TARGET_ASM_FUNCTION_EPILOGUE
225 #define TARGET_ASM_FUNCTION_EPILOGUE sh_output_function_epilogue
226
227 #undef TARGET_INSERT_ATTRIBUTES
228 #define TARGET_INSERT_ATTRIBUTES sh_insert_attributes
229
230 #undef TARGET_SCHED_ADJUST_COST
231 #define TARGET_SCHED_ADJUST_COST sh_adjust_cost
232
233 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE 
234 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE \
235                                 sh_use_dfa_interface
236 #undef TARGET_SCHED_ISSUE_RATE
237 #define TARGET_SCHED_ISSUE_RATE sh_issue_rate
238
239 #undef TARGET_CANNOT_MODIFY_JUMPS_P
240 #define TARGET_CANNOT_MODIFY_JUMPS_P sh_cannot_modify_jumps_p
241
242 #undef TARGET_MS_BITFIELD_LAYOUT_P
243 #define TARGET_MS_BITFIELD_LAYOUT_P sh_ms_bitfield_layout_p
244
245 struct gcc_target targetm = TARGET_INITIALIZER;
246 \f
247 /* Print the operand address in x to the stream.  */
248
249 void
250 print_operand_address (stream, x)
251      FILE *stream;
252      rtx x;
253 {
254   switch (GET_CODE (x))
255     {
256     case REG:
257     case SUBREG:
258       fprintf (stream, "@%s", reg_names[true_regnum (x)]);
259       break;
260
261     case PLUS:
262       {
263         rtx base = XEXP (x, 0);
264         rtx index = XEXP (x, 1);
265
266         switch (GET_CODE (index))
267           {
268           case CONST_INT:
269             fprintf (stream, "@(%d,%s)", (int) INTVAL (index),
270                      reg_names[true_regnum (base)]);
271             break;
272
273           case REG:
274           case SUBREG:
275             {
276               int base_num = true_regnum (base);
277               int index_num = true_regnum (index);
278
279               fprintf (stream, "@(r0,%s)",
280                        reg_names[MAX (base_num, index_num)]);
281               break;
282             }
283
284           default:
285             debug_rtx (x);
286             abort ();
287           }
288       }
289       break;
290
291     case PRE_DEC:
292       fprintf (stream, "@-%s", reg_names[true_regnum (XEXP (x, 0))]);
293       break;
294
295     case POST_INC:
296       fprintf (stream, "@%s+", reg_names[true_regnum (XEXP (x, 0))]);
297       break;
298
299     default:
300       x = mark_constant_pool_use (x);
301       output_addr_const (stream, x);
302       break;
303     }
304 }
305
306 /* Print operand x (an rtx) in assembler syntax to file stream
307    according to modifier code.
308
309    '.'  print a .s if insn needs delay slot
310    ','  print LOCAL_LABEL_PREFIX
311    '@'  print trap, rte or rts depending upon pragma interruptness
312    '#'  output a nop if there is nothing to put in the delay slot
313    'O'  print a constant without the #
314    'R'  print the LSW of a dp value - changes if in little endian
315    'S'  print the MSW of a dp value - changes if in little endian
316    'T'  print the next word of a dp value - same as 'R' in big endian mode.
317    'M'  print an `x' if `m' will print `base,index'.
318    'm'  print a pair `base,offset' or `base,index', for LD and ST.
319    'u'  prints the lowest 16 bits of CONST_INT, as an unsigned value.
320    'o'  output an operator.  */
321
322 void
323 print_operand (stream, x, code)
324      FILE *stream;
325      rtx x;
326      int code;
327 {
328   switch (code)
329     {
330     case '.':
331       if (final_sequence
332           && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
333         fprintf (stream, ASSEMBLER_DIALECT ? "/s" : ".s");
334       break;
335     case ',':
336       fprintf (stream, "%s", LOCAL_LABEL_PREFIX);
337       break;
338     case '@':
339       {
340         int interrupt_handler;
341
342         if ((lookup_attribute
343              ("interrupt_handler",
344               DECL_ATTRIBUTES (current_function_decl)))
345             != NULL_TREE)
346           interrupt_handler = 1;
347         else
348           interrupt_handler = 0;
349         
350       if (trap_exit)
351         fprintf (stream, "trapa #%d", trap_exit);
352       else if (interrupt_handler)
353         fprintf (stream, "rte");
354       else
355         fprintf (stream, "rts");
356       break;
357       }
358     case '#':
359       /* Output a nop if there's nothing in the delay slot.  */
360       if (dbr_sequence_length () == 0)
361         fprintf (stream, "\n\tnop");
362       break;
363     case 'O':
364       x = mark_constant_pool_use (x);
365       output_addr_const (stream, x);
366       break;
367     case 'R':
368       fputs (reg_names[REGNO (x) + LSW], (stream));
369       break;
370     case 'S':
371       fputs (reg_names[REGNO (x) + MSW], (stream));
372       break;
373     case 'T':
374       /* Next word of a double.  */
375       switch (GET_CODE (x))
376         {
377         case REG:
378           fputs (reg_names[REGNO (x) + 1], (stream));
379           break;
380         case MEM:
381           if (GET_CODE (XEXP (x, 0)) != PRE_DEC
382               && GET_CODE (XEXP (x, 0)) != POST_INC)
383             x = adjust_address (x, SImode, 4);
384           print_operand_address (stream, XEXP (x, 0));
385           break;
386         default:
387           break;
388         }
389       break;
390     case 'o':
391       switch (GET_CODE (x))
392         {
393         case PLUS:  fputs ("add", stream); break;
394         case MINUS: fputs ("sub", stream); break;
395         case MULT:  fputs ("mul", stream); break;
396         case DIV:   fputs ("div", stream); break;
397         default:
398           break;
399         }
400       break;
401     case 'M':
402       if (GET_CODE (x) == MEM
403           && GET_CODE (XEXP (x, 0)) == PLUS
404           && (GET_CODE (XEXP (XEXP (x, 0), 1)) == REG
405               || GET_CODE (XEXP (XEXP (x, 0), 1)) == SUBREG))
406         fputc ('x', stream);
407       break;
408
409     case 'm':
410       if (GET_CODE (x) != MEM)
411         abort ();
412       x = XEXP (x, 0);
413       switch (GET_CODE (x))
414         {
415         case REG:
416         case SUBREG:
417           print_operand (stream, x, 0);
418           fputs (", 0", stream);
419           break;
420
421         case PLUS:
422           print_operand (stream, XEXP (x, 0), 0);
423           fputs (", ", stream);
424           print_operand (stream, XEXP (x, 1), 0);
425           break;
426
427         default:
428           abort ();
429         }
430       break;
431
432     case 'u':
433       if (GET_CODE (x) == CONST_INT)
434         {
435           fprintf ((stream), "%u", (unsigned) INTVAL (x) & (0x10000 - 1));
436           break;
437         }
438       /* Fall through.  */
439
440     default:
441       switch (GET_CODE (x))
442         {
443           /* FIXME: We need this on SHmedia32 because reload generates
444              some sign-extended HI or QI loads into DImode registers
445              but, because Pmode is SImode, the address ends up with a
446              subreg:SI of the DImode register.  Maybe reload should be
447              fixed so as to apply alter_subreg to such loads?  */
448         case SUBREG:
449           if (SUBREG_BYTE (x) != 0
450               || GET_CODE (SUBREG_REG (x)) != REG)
451             abort ();
452
453           x = SUBREG_REG (x);
454           /* Fall through.  */
455
456         case REG:
457           if (FP_REGISTER_P (REGNO (x))
458               && GET_MODE (x) == V16SFmode)
459             fprintf ((stream), "mtrx%s", reg_names[REGNO (x)] + 2);
460           else if (FP_REGISTER_P (REGNO (x))
461                    && GET_MODE (x) == V4SFmode)
462             fprintf ((stream), "fv%s", reg_names[REGNO (x)] + 2);
463           else if (GET_CODE (x) == REG
464                    && GET_MODE (x) == V2SFmode)
465             fprintf ((stream), "fp%s", reg_names[REGNO (x)] + 2);
466           else if (FP_REGISTER_P (REGNO (x))
467                    && GET_MODE_SIZE (GET_MODE (x)) > 4)
468             fprintf ((stream), "d%s", reg_names[REGNO (x)] + 1);
469           else
470             fputs (reg_names[REGNO (x)], (stream));
471           break;
472
473         case MEM:
474           output_address (XEXP (x, 0));
475           break;
476           
477         case CONST:
478           if (TARGET_SHMEDIA
479               && GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
480               && GET_MODE (XEXP (x, 0)) == DImode
481               && GET_CODE (XEXP (XEXP (x, 0), 0)) == TRUNCATE
482               && GET_MODE (XEXP (XEXP (x, 0), 0)) == HImode)
483             {
484               rtx val = XEXP (XEXP (XEXP (x, 0), 0), 0);
485
486               fputc ('(', stream);
487               if (GET_CODE (val) == ASHIFTRT)
488                 {
489                   fputc ('(', stream);
490                   if (GET_CODE (XEXP (val, 0)) == CONST)
491                     fputc ('(', stream);
492                   output_addr_const (stream, XEXP (val, 0));
493                   if (GET_CODE (XEXP (val, 0)) == CONST)
494                     fputc (')', stream);
495                   fputs (" >> ", stream);
496                   output_addr_const (stream, XEXP (val, 1));
497                   fputc (')', stream);
498                 }
499               else
500                 {
501                   if (GET_CODE (val) == CONST)
502                     fputc ('(', stream);
503                   output_addr_const (stream, val);
504                   if (GET_CODE (val) == CONST)
505                     fputc (')', stream);
506                 }
507               fputs (" & 65535)", stream);
508               break;
509             }
510
511           /* Fall through.  */
512         default:
513           if (TARGET_SH1)
514             fputc ('#', stream);
515           output_addr_const (stream, x);
516           break;
517         }
518       break;
519     }
520 }
521 \f
522 /* Like force_operand, but guarantees that VALUE ends up in TARGET.  */
523 static void
524 force_into (value, target)
525      rtx value, target;
526 {
527   value = force_operand (value, target);
528   if (! rtx_equal_p (value, target))
529     emit_insn (gen_move_insn (target, value));
530 }
531
532 /* Emit code to perform a block move.  Choose the best method.
533
534    OPERANDS[0] is the destination.
535    OPERANDS[1] is the source.
536    OPERANDS[2] is the size.
537    OPERANDS[3] is the alignment safe to use.  */
538
539 int
540 expand_block_move (operands)
541      rtx *operands;
542 {
543   int align = INTVAL (operands[3]);
544   int constp = (GET_CODE (operands[2]) == CONST_INT);
545   int bytes = (constp ? INTVAL (operands[2]) : 0);
546
547   /* If it isn't a constant number of bytes, or if it doesn't have 4 byte
548      alignment, or if it isn't a multiple of 4 bytes, then fail.  */
549   if (! constp || align < 4 || (bytes % 4 != 0))
550     return 0;
551
552   if (TARGET_HARD_SH4)
553     {
554       if (bytes < 12)
555         return 0;
556       else if (bytes == 12)
557         {
558           tree entry_name;
559           rtx sym;
560           rtx func_addr_rtx;
561           rtx r4 = gen_rtx (REG, SImode, 4);
562           rtx r5 = gen_rtx (REG, SImode, 5);
563
564           entry_name = get_identifier ("__movstrSI12_i4");
565
566           sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
567           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
568           force_into (XEXP (operands[0], 0), r4);
569           force_into (XEXP (operands[1], 0), r5);
570           emit_insn (gen_block_move_real_i4 (func_addr_rtx));
571           return 1;
572         }
573       else if (! TARGET_SMALLCODE)
574         {
575           tree entry_name;
576           rtx sym;
577           rtx func_addr_rtx;
578           int dwords;
579           rtx r4 = gen_rtx (REG, SImode, 4);
580           rtx r5 = gen_rtx (REG, SImode, 5);
581           rtx r6 = gen_rtx (REG, SImode, 6);
582
583           entry_name = get_identifier (bytes & 4
584                                        ? "__movstr_i4_odd"
585                                        : "__movstr_i4_even");
586           sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
587           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
588           force_into (XEXP (operands[0], 0), r4);
589           force_into (XEXP (operands[1], 0), r5);
590
591           dwords = bytes >> 3;
592           emit_insn (gen_move_insn (r6, GEN_INT (dwords - 1)));
593           emit_insn (gen_block_lump_real_i4 (func_addr_rtx));
594           return 1;
595         }
596       else
597         return 0;
598     }
599   if (bytes < 64)
600     {
601       char entry[30];
602       tree entry_name;
603       rtx sym;
604       rtx func_addr_rtx;
605       rtx r4 = gen_rtx_REG (SImode, 4);
606       rtx r5 = gen_rtx_REG (SImode, 5);
607
608       sprintf (entry, "__movstrSI%d", bytes);
609       entry_name = get_identifier (entry);
610       sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
611       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
612       force_into (XEXP (operands[0], 0), r4);
613       force_into (XEXP (operands[1], 0), r5);
614       emit_insn (gen_block_move_real (func_addr_rtx));
615       return 1;
616     }
617
618   /* This is the same number of bytes as a memcpy call, but to a different
619      less common function name, so this will occasionally use more space.  */
620   if (! TARGET_SMALLCODE)
621     {
622       tree entry_name;
623       rtx sym;
624       rtx func_addr_rtx;
625       int final_switch, while_loop;
626       rtx r4 = gen_rtx_REG (SImode, 4);
627       rtx r5 = gen_rtx_REG (SImode, 5);
628       rtx r6 = gen_rtx_REG (SImode, 6);
629
630       entry_name = get_identifier ("__movstr");
631       sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (entry_name));
632       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
633       force_into (XEXP (operands[0], 0), r4);
634       force_into (XEXP (operands[1], 0), r5);
635
636       /* r6 controls the size of the move.  16 is decremented from it
637          for each 64 bytes moved.  Then the negative bit left over is used
638          as an index into a list of move instructions.  e.g., a 72 byte move
639          would be set up with size(r6) = 14, for one iteration through the
640          big while loop, and a switch of -2 for the last part.  */
641
642       final_switch = 16 - ((bytes / 4) % 16);
643       while_loop = ((bytes / 4) / 16 - 1) * 16;
644       emit_insn (gen_move_insn (r6, GEN_INT (while_loop + final_switch)));
645       emit_insn (gen_block_lump_real (func_addr_rtx));
646       return 1;
647     }
648
649   return 0;
650 }
651
652 /* Prepare operands for a move define_expand; specifically, one of the
653    operands must be in a register.  */
654
655 int
656 prepare_move_operands (operands, mode)
657      rtx operands[];
658      enum machine_mode mode;
659 {
660   if ((mode == SImode || mode == DImode) && flag_pic)
661     {
662       rtx temp;
663       if (SYMBOLIC_CONST_P (operands[1]))
664         {
665           if (GET_CODE (operands[0]) == MEM)
666             operands[1] = force_reg (Pmode, operands[1]);
667           else if (GET_CODE (operands[1]) == LABEL_REF
668                    && target_reg_operand (operands[0], mode))
669             /* It's ok.  */;
670           else
671             {
672               temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
673               operands[1] = legitimize_pic_address (operands[1], mode, temp);
674             }
675         }
676       else if (GET_CODE (operands[1]) == CONST
677                && GET_CODE (XEXP (operands[1], 0)) == PLUS
678                && SYMBOLIC_CONST_P (XEXP (XEXP (operands[1], 0), 0)))
679         {
680           temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
681           temp = legitimize_pic_address (XEXP (XEXP (operands[1], 0), 0),
682                                          mode, temp);
683           operands[1] = expand_binop (mode, add_optab, temp,
684                                       XEXP (XEXP (operands[1], 0), 1),
685                                       no_new_pseudos ? temp
686                                       : gen_reg_rtx (Pmode),
687                                       0, OPTAB_LIB_WIDEN);
688         }
689     }
690
691   if (! reload_in_progress && ! reload_completed)
692     {
693       /* Copy the source to a register if both operands aren't registers.  */
694       if (! register_operand (operands[0], mode)
695           && ! register_operand (operands[1], mode))
696         operands[1] = copy_to_mode_reg (mode, operands[1]);
697
698       /* This case can happen while generating code to move the result
699          of a library call to the target.  Reject `st r0,@(rX,rY)' because
700          reload will fail to find a spill register for rX, since r0 is already
701          being used for the source.  */
702       else if (GET_CODE (operands[1]) == REG && REGNO (operands[1]) == 0
703                && GET_CODE (operands[0]) == MEM
704                && GET_CODE (XEXP (operands[0], 0)) == PLUS
705                && GET_CODE (XEXP (XEXP (operands[0], 0), 1)) == REG)
706         operands[1] = copy_to_mode_reg (mode, operands[1]);
707     }
708
709   return 0;
710 }
711
712 /* Prepare the operands for an scc instruction; make sure that the
713    compare has been done.  */
714 rtx
715 prepare_scc_operands (code)
716      enum rtx_code code;
717 {
718   rtx t_reg = gen_rtx_REG (SImode, T_REG);
719   enum rtx_code oldcode = code;
720   enum machine_mode mode;
721
722   /* First need a compare insn.  */
723   switch (code)
724     {
725     case NE:
726       /* It isn't possible to handle this case.  */
727       abort ();
728     case LT:
729       code = GT;
730       break;
731     case LE:
732       code = GE;
733       break;
734     case LTU:
735       code = GTU;
736       break;
737     case LEU:
738       code = GEU;
739       break;
740     default:
741       break;
742     }
743   if (code != oldcode)
744     {
745       rtx tmp = sh_compare_op0;
746       sh_compare_op0 = sh_compare_op1;
747       sh_compare_op1 = tmp;
748     }
749
750   mode = GET_MODE (sh_compare_op0);
751   if (mode == VOIDmode)
752     mode = GET_MODE (sh_compare_op1);
753
754   sh_compare_op0 = force_reg (mode, sh_compare_op0);
755   if ((code != EQ && code != NE
756        && (sh_compare_op1 != const0_rtx
757            || code == GTU  || code == GEU || code == LTU || code == LEU))
758       || (mode == DImode && sh_compare_op1 != const0_rtx)
759       || (TARGET_SH3E && GET_MODE_CLASS (mode) == MODE_FLOAT))
760     sh_compare_op1 = force_reg (mode, sh_compare_op1);
761
762   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
763     (mode == SFmode ? emit_sf_insn : emit_df_insn)
764      (gen_rtx (PARALLEL, VOIDmode, gen_rtvec (2,
765                 gen_rtx (SET, VOIDmode, t_reg,
766                          gen_rtx (code, SImode,
767                                   sh_compare_op0, sh_compare_op1)),
768                 gen_rtx (USE, VOIDmode, get_fpscr_rtx ()))));
769   else
770     emit_insn (gen_rtx (SET, VOIDmode, t_reg,
771                         gen_rtx (code, SImode, sh_compare_op0,
772                                  sh_compare_op1)));
773
774   return t_reg;
775 }
776
777 /* Called from the md file, set up the operands of a compare instruction.  */
778
779 void
780 from_compare (operands, code)
781      rtx *operands;
782      int code;
783 {
784   enum machine_mode mode = GET_MODE (sh_compare_op0);
785   rtx insn;
786   if (mode == VOIDmode)
787     mode = GET_MODE (sh_compare_op1);
788   if (code != EQ
789       || mode == DImode
790       || (TARGET_SH3E && GET_MODE_CLASS (mode) == MODE_FLOAT))
791     {
792       /* Force args into regs, since we can't use constants here.  */
793       sh_compare_op0 = force_reg (mode, sh_compare_op0);
794       if (sh_compare_op1 != const0_rtx
795           || code == GTU  || code == GEU
796           || (TARGET_SH3E && GET_MODE_CLASS (mode) == MODE_FLOAT))
797         sh_compare_op1 = force_reg (mode, sh_compare_op1);
798     }
799   if (TARGET_SH3E && GET_MODE_CLASS (mode) == MODE_FLOAT && code == GE)
800     {
801       from_compare (operands, GT);
802       insn = gen_ieee_ccmpeqsf_t (sh_compare_op0, sh_compare_op1);
803     }
804   else
805     insn = gen_rtx_SET (VOIDmode,
806                         gen_rtx_REG (SImode, T_REG),
807                         gen_rtx (code, SImode, sh_compare_op0,
808                                  sh_compare_op1));
809   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
810     {
811       insn = gen_rtx (PARALLEL, VOIDmode,
812                       gen_rtvec (2, insn,
813                                  gen_rtx (USE, VOIDmode, get_fpscr_rtx ())));
814       (mode == SFmode ? emit_sf_insn : emit_df_insn) (insn);
815     }
816   else
817     emit_insn (insn);
818 }
819 \f
820 /* Functions to output assembly code.  */
821
822 /* Return a sequence of instructions to perform DI or DF move.
823
824    Since the SH cannot move a DI or DF in one instruction, we have
825    to take care when we see overlapping source and dest registers.  */
826
827 const char *
828 output_movedouble (insn, operands, mode)
829      rtx insn ATTRIBUTE_UNUSED;
830      rtx operands[];
831      enum machine_mode mode;
832 {
833   rtx dst = operands[0];
834   rtx src = operands[1];
835
836   if (GET_CODE (dst) == MEM
837       && GET_CODE (XEXP (dst, 0)) == PRE_DEC)
838     return "mov.l       %T1,%0\n\tmov.l %1,%0";
839
840   if (register_operand (dst, mode)
841       && register_operand (src, mode))
842     {
843       if (REGNO (src) == MACH_REG)
844         return "sts     mach,%S0\n\tsts macl,%R0";
845
846       /* When mov.d r1,r2 do r2->r3 then r1->r2;
847          when mov.d r1,r0 do r1->r0 then r2->r1.  */
848
849       if (REGNO (src) + 1 == REGNO (dst))
850         return "mov     %T1,%T0\n\tmov  %1,%0";
851       else
852         return "mov     %1,%0\n\tmov    %T1,%T0";
853     }
854   else if (GET_CODE (src) == CONST_INT)
855     {
856       if (INTVAL (src) < 0)
857         output_asm_insn ("mov   #-1,%S0", operands);
858       else
859         output_asm_insn ("mov   #0,%S0", operands);
860
861       return "mov       %1,%R0";
862     }
863   else if (GET_CODE (src) == MEM)
864     {
865       int ptrreg = -1;
866       int dreg = REGNO (dst);
867       rtx inside = XEXP (src, 0);
868
869       if (GET_CODE (inside) == REG)
870         ptrreg = REGNO (inside);
871       else if (GET_CODE (inside) == SUBREG)
872         ptrreg = subreg_regno (inside);
873       else if (GET_CODE (inside) == PLUS)
874         {
875           ptrreg = REGNO (XEXP (inside, 0));
876           /* ??? A r0+REG address shouldn't be possible here, because it isn't
877              an offsettable address.  Unfortunately, offsettable addresses use
878              QImode to check the offset, and a QImode offsettable address
879              requires r0 for the other operand, which is not currently
880              supported, so we can't use the 'o' constraint.
881              Thus we must check for and handle r0+REG addresses here.
882              We punt for now, since this is likely very rare.  */
883           if (GET_CODE (XEXP (inside, 1)) == REG)
884             abort ();
885         }
886       else if (GET_CODE (inside) == LABEL_REF)
887         return "mov.l   %1,%0\n\tmov.l  %1+4,%T0";
888       else if (GET_CODE (inside) == POST_INC)
889         return "mov.l   %1,%0\n\tmov.l  %1,%T0";
890       else
891         abort ();
892
893       /* Work out the safe way to copy.  Copy into the second half first.  */
894       if (dreg == ptrreg)
895         return "mov.l   %T1,%T0\n\tmov.l        %1,%0";
896     }
897
898   return "mov.l %1,%0\n\tmov.l  %T1,%T0";
899 }
900
901 /* Print an instruction which would have gone into a delay slot after
902    another instruction, but couldn't because the other instruction expanded
903    into a sequence where putting the slot insn at the end wouldn't work.  */
904
905 static void
906 print_slot (insn)
907      rtx insn;
908 {
909   final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file, optimize, 0, 1);
910
911   INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
912 }
913
914 const char *
915 output_far_jump (insn, op)
916      rtx insn;
917      rtx op;
918 {
919   struct { rtx lab, reg, op; } this;
920   rtx braf_base_lab = NULL_RTX;
921   const char *jump;
922   int far;
923   int offset = branch_dest (insn) - INSN_ADDRESSES (INSN_UID (insn));
924
925   this.lab = gen_label_rtx ();
926
927   if (TARGET_SH2
928       && offset >= -32764
929       && offset - get_attr_length (insn) <= 32766)
930     {
931       far = 0;
932       jump = "mov.w     %O0,%1; braf    %1";
933     }
934   else
935     {
936       far = 1;
937       if (flag_pic)
938         {
939           if (TARGET_SH2)
940             jump = "mov.l       %O0,%1; braf    %1";
941           else
942             jump = "mov.l       r0,@-r15; mova  %O0,r0; mov.l   @r0,%1; add     r0,%1; mov.l    @r15+,r0; jmp   @%1";
943         }
944       else
945         jump = "mov.l   %O0,%1; jmp     @%1";
946     }
947   /* If we have a scratch register available, use it.  */
948   if (GET_CODE (PREV_INSN (insn)) == INSN
949       && INSN_CODE (PREV_INSN (insn)) == CODE_FOR_indirect_jump_scratch)
950     {
951       this.reg = SET_DEST (PATTERN (PREV_INSN (insn)));
952       if (REGNO (this.reg) == R0_REG && flag_pic && ! TARGET_SH2)
953         jump = "mov.l   r1,@-r15; mova  %O0,r0; mov.l   @r0,r1; add     r1,r0; mov.l    @r15+,r1; jmp   @%1";
954       output_asm_insn (jump, &this.lab);
955       if (dbr_sequence_length ())
956         print_slot (final_sequence);
957       else
958         output_asm_insn ("nop", 0);
959     }
960   else
961     {
962       /* Output the delay slot insn first if any.  */
963       if (dbr_sequence_length ())
964         print_slot (final_sequence);
965
966       this.reg = gen_rtx_REG (SImode, 13);
967       /* We must keep the stack aligned to 8-byte boundaries on SH5.
968          Fortunately, MACL is fixed and call-clobbered, and we never
969          need its value across jumps, so save r13 in it instead of in
970          the stack.  */
971       if (TARGET_SH5)
972         output_asm_insn ("lds   r13, macl", 0);
973       else
974         output_asm_insn ("mov.l r13,@-r15", 0);
975       output_asm_insn (jump, &this.lab);
976       if (TARGET_SH5)
977         output_asm_insn ("sts   macl, r13", 0);
978       else
979         output_asm_insn ("mov.l @r15+,r13", 0);
980     }
981   if (far && flag_pic && TARGET_SH2)
982     {
983       braf_base_lab = gen_label_rtx ();
984       ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, "L",
985                                  CODE_LABEL_NUMBER (braf_base_lab));
986     }
987   if (far)
988     output_asm_insn (".align    2", 0);
989   ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, "L", CODE_LABEL_NUMBER (this.lab));
990   this.op = op;
991   if (far && flag_pic)
992     {
993       if (TARGET_SH2)
994         this.lab = braf_base_lab;
995       output_asm_insn (".long   %O2-%O0", &this.lab);
996     }
997   else
998     output_asm_insn (far ? ".long       %O2" : ".word %O2-%O0", &this.lab);
999   return "";
1000 }
1001
1002 /* Local label counter, used for constants in the pool and inside
1003    pattern branches.  */
1004
1005 static int lf = 100;
1006
1007 /* Output code for ordinary branches.  */
1008
1009 const char *
1010 output_branch (logic, insn, operands)
1011      int logic;
1012      rtx insn;
1013      rtx *operands;
1014 {
1015   switch (get_attr_length (insn))
1016     {
1017     case 6:
1018       /* This can happen if filling the delay slot has caused a forward
1019          branch to exceed its range (we could reverse it, but only
1020          when we know we won't overextend other branches; this should
1021          best be handled by relaxation).
1022          It can also happen when other condbranches hoist delay slot insn
1023          from their destination, thus leading to code size increase.
1024          But the branch will still be in the range -4092..+4098 bytes.  */
1025
1026       if (! TARGET_RELAX)
1027         {
1028           int label = lf++;
1029           /* The call to print_slot will clobber the operands.  */
1030           rtx op0 = operands[0];
1031     
1032           /* If the instruction in the delay slot is annulled (true), then
1033              there is no delay slot where we can put it now.  The only safe
1034              place for it is after the label.  final will do that by default.  */
1035     
1036           if (final_sequence
1037               && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
1038             {
1039               asm_fprintf (asm_out_file, "\tb%s%ss\t%LLF%d\n", logic ? "f" : "t",
1040                            ASSEMBLER_DIALECT ? "/" : ".", label);
1041               print_slot (final_sequence);
1042             }
1043           else
1044             asm_fprintf (asm_out_file, "\tb%s\t%LLF%d\n", logic ? "f" : "t", label);
1045     
1046           output_asm_insn ("bra\t%l0", &op0);
1047           fprintf (asm_out_file, "\tnop\n");
1048           ASM_OUTPUT_INTERNAL_LABEL(asm_out_file, "LF", label);
1049     
1050           return "";
1051         }
1052       /* When relaxing, handle this like a short branch.  The linker
1053          will fix it up if it still doesn't fit after relaxation.  */
1054     case 2:
1055       return logic ? "bt%.\t%l0" : "bf%.\t%l0";
1056     default:
1057       /* There should be no longer branches now - that would
1058          indicate that something has destroyed the branches set
1059          up in machine_dependent_reorg.  */
1060       abort ();
1061     }
1062 }
1063
1064 const char *
1065 output_branchy_insn (code, template, insn, operands)
1066      enum rtx_code code;
1067      const char *template;
1068      rtx insn;
1069      rtx *operands;
1070 {
1071   rtx next_insn = NEXT_INSN (insn);
1072
1073   if (next_insn && GET_CODE (next_insn) == JUMP_INSN && condjump_p (next_insn))
1074     {
1075       rtx src = SET_SRC (PATTERN (next_insn));
1076       if (GET_CODE (src) == IF_THEN_ELSE && GET_CODE (XEXP (src, 0)) != code)
1077         {
1078           /* Following branch not taken */
1079           operands[9] = gen_label_rtx ();
1080           emit_label_after (operands[9], next_insn);
1081           INSN_ADDRESSES_NEW (operands[9],
1082                               INSN_ADDRESSES (INSN_UID (next_insn))
1083                               + get_attr_length (next_insn));
1084           return template;
1085         }
1086       else
1087         {
1088           int offset = (branch_dest (next_insn)
1089                         - INSN_ADDRESSES (INSN_UID (next_insn)) + 4);
1090           if (offset >= -252 && offset <= 258)
1091             {
1092               if (GET_CODE (src) == IF_THEN_ELSE)
1093                 /* branch_true */
1094                 src = XEXP (src, 1);
1095               operands[9] = src;
1096               return template;
1097             }
1098         }
1099     }
1100   operands[9] = gen_label_rtx ();
1101   emit_label_after (operands[9], insn);
1102   INSN_ADDRESSES_NEW (operands[9],
1103                       INSN_ADDRESSES (INSN_UID (insn))
1104                       + get_attr_length (insn));
1105   return template;
1106 }
1107
1108 const char *
1109 output_ieee_ccmpeq (insn, operands)
1110      rtx insn, *operands;
1111 {
1112   return output_branchy_insn (NE, "bt\t%l9\\;fcmp/eq\t%1,%0", insn, operands);
1113 }
1114 \f
1115 /* Output to FILE the start of the assembler file.  */
1116
1117 void
1118 output_file_start (file)
1119      FILE *file;
1120 {
1121   output_file_directive (file, main_input_filename);
1122
1123   /* Switch to the data section so that the coffsem symbol
1124      isn't in the text section.  */
1125   data_section ();
1126
1127   if (TARGET_LITTLE_ENDIAN)
1128     fprintf (file, "\t.little\n");
1129
1130   if (TARGET_SHCOMPACT)
1131     fprintf (file, "\t.mode\tSHcompact\n");
1132   else if (TARGET_SHMEDIA)
1133     fprintf (file, "\t.mode\tSHmedia\n\t.abi\t%i\n",
1134              TARGET_SHMEDIA64 ? 64 : 32);
1135 }
1136 \f
1137 /* Actual number of instructions used to make a shift by N.  */
1138 static const char ashiftrt_insns[] =
1139   { 0,1,2,3,4,5,8,8,8,8,8,8,8,8,8,8,2,3,4,5,8,8,8,8,8,8,8,8,8,8,8,2};
1140
1141 /* Left shift and logical right shift are the same.  */
1142 static const char shift_insns[]    =
1143   { 0,1,1,2,2,3,3,4,1,2,2,3,3,4,3,3,1,2,2,3,3,4,3,3,2,3,3,4,4,4,3,3};
1144
1145 /* Individual shift amounts needed to get the above length sequences.
1146    One bit right shifts clobber the T bit, so when possible, put one bit
1147    shifts in the middle of the sequence, so the ends are eligible for
1148    branch delay slots.  */
1149 static const short shift_amounts[32][5] = {
1150   {0}, {1}, {2}, {2, 1},
1151   {2, 2}, {2, 1, 2}, {2, 2, 2}, {2, 2, 1, 2},
1152   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1153   {8, 2, 2}, {8, 2, 1, 2}, {8, -2, 8}, {8, -1, 8},
1154   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1155   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1156   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1157   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1158
1159 /* Likewise, but for shift amounts < 16, up to three highmost bits
1160    might be clobbered.  This is typically used when combined with some
1161    kind of sign or zero extension.  */
1162    
1163 static const char ext_shift_insns[]    =
1164   { 0,1,1,2,2,3,2,2,1,2,2,3,3,3,2,2,1,2,2,3,3,4,3,3,2,3,3,4,4,4,3,3};
1165
1166 static const short ext_shift_amounts[32][4] = {
1167   {0}, {1}, {2}, {2, 1},
1168   {2, 2}, {2, 1, 2}, {8, -2}, {8, -1},
1169   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1170   {8, 2, 2}, {16, -2, -1}, {16, -2}, {16, -1},
1171   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1172   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1173   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1174   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1175
1176 /* Assuming we have a value that has been sign-extended by at least one bit,
1177    can we use the ext_shift_amounts with the last shift turned to an arithmetic shift
1178    to shift it by N without data loss, and quicker than by other means?  */
1179 #define EXT_SHIFT_SIGNED(n) (((n) | 8) == 15)
1180
1181 /* This is used in length attributes in sh.md to help compute the length
1182    of arbitrary constant shift instructions.  */
1183
1184 int
1185 shift_insns_rtx (insn)
1186      rtx insn;
1187 {
1188   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
1189   int shift_count = INTVAL (XEXP (set_src, 1));
1190   enum rtx_code shift_code = GET_CODE (set_src);
1191
1192   switch (shift_code)
1193     {
1194     case ASHIFTRT:
1195       return ashiftrt_insns[shift_count];
1196     case LSHIFTRT:
1197     case ASHIFT:
1198       return shift_insns[shift_count];
1199     default:
1200       abort();
1201     }
1202 }
1203
1204 /* Return the cost of a shift.  */
1205
1206 int
1207 shiftcosts (x)
1208      rtx x;
1209 {
1210   int value;
1211
1212   if (TARGET_SHMEDIA)
1213     return 1;
1214
1215   if (GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
1216     {
1217       if (GET_MODE (x) == DImode
1218           && GET_CODE (XEXP (x, 1)) == CONST_INT
1219           && INTVAL (XEXP (x, 1)) == 1)
1220         return 2;
1221
1222       /* Everything else is invalid, because there is no pattern for it.  */
1223       return 10000;
1224     }
1225   /* If shift by a non constant, then this will be expensive.  */
1226   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1227     return SH_DYNAMIC_SHIFT_COST;
1228
1229   value = INTVAL (XEXP (x, 1));
1230
1231   /* Otherwise, return the true cost in instructions.  */
1232   if (GET_CODE (x) == ASHIFTRT)
1233     {
1234       int cost = ashiftrt_insns[value];
1235       /* If SH3, then we put the constant in a reg and use shad.  */
1236       if (cost > 1 + SH_DYNAMIC_SHIFT_COST)
1237         cost = 1 + SH_DYNAMIC_SHIFT_COST;
1238       return cost;
1239     }
1240   else
1241     return shift_insns[value];
1242 }
1243
1244 /* Return the cost of an AND operation.  */
1245
1246 int
1247 andcosts (x)
1248      rtx x;
1249 {
1250   int i;
1251
1252   /* Anding with a register is a single cycle and instruction.  */
1253   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1254     return 1;
1255
1256   i = INTVAL (XEXP (x, 1));
1257
1258   if (TARGET_SHMEDIA)
1259     {
1260       if ((GET_CODE (XEXP (x, 1)) == CONST_INT
1261            && CONST_OK_FOR_J (INTVAL (XEXP (x, 1))))
1262           || EXTRA_CONSTRAINT_S (XEXP (x, 1)))
1263         return 1;
1264       else
1265         return 2;
1266     }
1267
1268   /* These constants are single cycle extu.[bw] instructions.  */
1269   if (i == 0xff || i == 0xffff)
1270     return 1;
1271   /* Constants that can be used in an and immediate instruction is a single
1272      cycle, but this requires r0, so make it a little more expensive.  */
1273   if (CONST_OK_FOR_L (i))
1274     return 2;
1275   /* Constants that can be loaded with a mov immediate and an and.
1276      This case is probably unnecessary.  */
1277   if (CONST_OK_FOR_I (i))
1278     return 2;
1279   /* Any other constants requires a 2 cycle pc-relative load plus an and.
1280      This case is probably unnecessary.  */
1281   return 3;
1282 }
1283
1284 /* Return the cost of an addition or a subtraction.  */
1285
1286 int
1287 addsubcosts (x)
1288      rtx x;
1289 {
1290   /* Adding a register is a single cycle insn.  */
1291   if (GET_CODE (XEXP (x, 1)) == REG
1292       || GET_CODE (XEXP (x, 1)) == SUBREG)
1293     return 1;
1294
1295   /* Likewise for small constants.  */
1296   if (GET_CODE (XEXP (x, 1)) == CONST_INT
1297       && CONST_OK_FOR_ADD (INTVAL (XEXP (x, 1))))
1298     return 1;
1299
1300   if (TARGET_SHMEDIA)
1301     switch (GET_CODE (XEXP (x, 1)))
1302       {
1303       case CONST:
1304       case LABEL_REF:
1305       case SYMBOL_REF:
1306         return TARGET_SHMEDIA64 ? 5 : 3;
1307
1308       case CONST_INT:
1309         if (CONST_OK_FOR_J (INTVAL (XEXP (x, 1))))
1310           return 2;
1311         else if (CONST_OK_FOR_J (INTVAL (XEXP (x, 1)) >> 16))
1312           return 3;
1313         else if (CONST_OK_FOR_J ((INTVAL (XEXP (x, 1)) >> 16) >> 16))
1314           return 4;
1315
1316         /* Fall through.  */
1317       default:
1318           return 5;
1319       }
1320
1321   /* Any other constant requires a 2 cycle pc-relative load plus an
1322      addition.  */
1323   return 3;
1324 }
1325
1326 /* Return the cost of a multiply.  */
1327 int
1328 multcosts (x)
1329      rtx x ATTRIBUTE_UNUSED;
1330 {
1331   if (TARGET_SHMEDIA)
1332     return 3;
1333
1334   if (TARGET_SH2)
1335     {
1336       /* We have a mul insn, so we can never take more than the mul and the
1337          read of the mac reg, but count more because of the latency and extra
1338          reg usage.  */
1339       if (TARGET_SMALLCODE)
1340         return 2;
1341       return 3;
1342     }
1343
1344   /* If we're aiming at small code, then just count the number of
1345      insns in a multiply call sequence.  */
1346   if (TARGET_SMALLCODE)
1347     return 5;
1348
1349   /* Otherwise count all the insns in the routine we'd be calling too.  */
1350   return 20;
1351 }
1352
1353 /* Code to expand a shift.  */
1354
1355 void
1356 gen_ashift (type, n, reg)
1357      int type;
1358      int n;
1359      rtx reg;
1360 {
1361   /* Negative values here come from the shift_amounts array.  */
1362   if (n < 0)
1363     {
1364       if (type == ASHIFT)
1365         type = LSHIFTRT;
1366       else
1367         type = ASHIFT;
1368       n = -n;
1369     }
1370
1371   switch (type)
1372     {
1373     case ASHIFTRT:
1374       emit_insn (gen_ashrsi3_k (reg, reg, GEN_INT (n)));
1375       break;
1376     case LSHIFTRT:
1377       if (n == 1)
1378         emit_insn (gen_lshrsi3_m (reg, reg, GEN_INT (n)));
1379       else
1380         emit_insn (gen_lshrsi3_k (reg, reg, GEN_INT (n)));
1381       break;
1382     case ASHIFT:
1383       emit_insn (gen_ashlsi3_std (reg, reg, GEN_INT (n)));
1384       break;
1385     }
1386 }
1387
1388 /* Same for HImode */
1389
1390 void
1391 gen_ashift_hi (type, n, reg)
1392      int type;
1393      int n;
1394      rtx reg;
1395 {
1396   /* Negative values here come from the shift_amounts array.  */
1397   if (n < 0)
1398     {
1399       if (type == ASHIFT)
1400         type = LSHIFTRT;
1401       else
1402         type = ASHIFT;
1403       n = -n;
1404     }
1405
1406   switch (type)
1407     {
1408     case ASHIFTRT:
1409     case LSHIFTRT:
1410       /* We don't have HImode right shift operations because using the
1411          ordinary 32 bit shift instructions for that doesn't generate proper
1412          zero/sign extension.
1413          gen_ashift_hi is only called in contexts where we know that the
1414          sign extension works out correctly.  */
1415       {
1416         int offset = 0;
1417         if (GET_CODE (reg) == SUBREG)
1418           {
1419             offset = SUBREG_BYTE (reg);
1420             reg = SUBREG_REG (reg);
1421           }
1422         gen_ashift (type, n, gen_rtx_SUBREG (SImode, reg, offset));
1423         break;
1424       }
1425     case ASHIFT:
1426       emit_insn (gen_ashlhi3_k (reg, reg, GEN_INT (n)));
1427       break;
1428     }
1429 }
1430
1431 /* Output RTL to split a constant shift into its component SH constant
1432    shift instructions.  */
1433    
1434 void
1435 gen_shifty_op (code, operands)
1436      int code;
1437      rtx *operands;
1438 {
1439   int value = INTVAL (operands[2]);
1440   int max, i;
1441
1442   /* Truncate the shift count in case it is out of bounds.  */
1443   value = value & 0x1f;
1444  
1445   if (value == 31)
1446     {
1447       if (code == LSHIFTRT)
1448         {
1449           emit_insn (gen_rotlsi3_1 (operands[0], operands[0]));
1450           emit_insn (gen_movt (operands[0]));
1451           return;
1452         }
1453       else if (code == ASHIFT)
1454         {
1455           /* There is a two instruction sequence for 31 bit left shifts,
1456              but it requires r0.  */
1457           if (GET_CODE (operands[0]) == REG && REGNO (operands[0]) == 0)
1458             {
1459               emit_insn (gen_andsi3 (operands[0], operands[0], const1_rtx));
1460               emit_insn (gen_rotlsi3_31 (operands[0], operands[0]));
1461               return;
1462             }
1463         }
1464     }
1465   else if (value == 0)
1466     {
1467       /* This can happen when not optimizing.  We must output something here
1468          to prevent the compiler from aborting in final.c after the try_split
1469          call.  */
1470       emit_insn (gen_nop ());
1471       return;
1472     }
1473
1474   max = shift_insns[value];
1475   for (i = 0; i < max; i++)
1476     gen_ashift (code, shift_amounts[value][i], operands[0]);
1477 }
1478    
1479 /* Same as above, but optimized for values where the topmost bits don't
1480    matter.  */
1481
1482 void
1483 gen_shifty_hi_op (code, operands)
1484      int code;
1485      rtx *operands;
1486 {
1487   int value = INTVAL (operands[2]);
1488   int max, i;
1489   void (*gen_fun) PARAMS ((int, int, rtx));
1490
1491   /* This operation is used by and_shl for SImode values with a few
1492      high bits known to be cleared.  */
1493   value &= 31;
1494   if (value == 0)
1495     {
1496       emit_insn (gen_nop ());
1497       return;
1498     }
1499
1500   gen_fun = GET_MODE (operands[0]) == HImode ? gen_ashift_hi : gen_ashift;
1501   if (code == ASHIFT)
1502     {
1503       max = ext_shift_insns[value];
1504       for (i = 0; i < max; i++)
1505         gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1506     }
1507   else
1508     /* When shifting right, emit the shifts in reverse order, so that
1509        solitary negative values come first.  */
1510     for (i = ext_shift_insns[value] - 1; i >= 0; i--)
1511       gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1512 }
1513
1514 /* Output RTL for an arithmetic right shift.  */
1515
1516 /* ??? Rewrite to use super-optimizer sequences.  */
1517
1518 int
1519 expand_ashiftrt (operands)
1520      rtx *operands;
1521 {
1522   rtx sym;
1523   rtx wrk;
1524   char func[18];
1525   tree func_name;
1526   int value;
1527
1528   if (TARGET_SH3)
1529     {
1530       if (GET_CODE (operands[2]) != CONST_INT)
1531         {
1532           rtx count = copy_to_mode_reg (SImode, operands[2]);
1533           emit_insn (gen_negsi2 (count, count));
1534           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1535           return 1;
1536         }
1537       else if (ashiftrt_insns[INTVAL (operands[2]) & 31]
1538                > 1 + SH_DYNAMIC_SHIFT_COST)
1539         {
1540           rtx count
1541             = force_reg (SImode, GEN_INT (- (INTVAL (operands[2]) & 31)));
1542           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1543           return 1;
1544         }
1545     }
1546   if (GET_CODE (operands[2]) != CONST_INT)
1547     return 0;
1548
1549   value = INTVAL (operands[2]) & 31;
1550
1551   if (value == 31)
1552     {
1553       emit_insn (gen_ashrsi2_31 (operands[0], operands[1]));
1554       return 1;
1555     }
1556   else if (value >= 16 && value <= 19)
1557     {
1558       wrk = gen_reg_rtx (SImode);
1559       emit_insn (gen_ashrsi2_16 (wrk, operands[1]));
1560       value -= 16;
1561       while (value--)
1562         gen_ashift (ASHIFTRT, 1, wrk);
1563       emit_move_insn (operands[0], wrk);
1564       return 1;
1565     }
1566   /* Expand a short sequence inline, longer call a magic routine.  */
1567   else if (value <= 5)
1568     {
1569       wrk = gen_reg_rtx (SImode);
1570       emit_move_insn (wrk, operands[1]);
1571       while (value--)
1572         gen_ashift (ASHIFTRT, 1, wrk);
1573       emit_move_insn (operands[0], wrk);
1574       return 1;
1575     }
1576
1577   wrk = gen_reg_rtx (Pmode);
1578
1579   /* Load the value into an arg reg and call a helper.  */
1580   emit_move_insn (gen_rtx_REG (SImode, 4), operands[1]);
1581   sprintf (func, "__ashiftrt_r4_%d", value);
1582   func_name = get_identifier (func);
1583   sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (func_name));
1584   emit_move_insn (wrk, sym);
1585   emit_insn (gen_ashrsi3_n (GEN_INT (value), wrk));
1586   emit_move_insn (operands[0], gen_rtx_REG (SImode, 4));
1587   return 1;
1588 }
1589
1590 int
1591 sh_dynamicalize_shift_p (count)
1592      rtx count;
1593 {
1594   return shift_insns[INTVAL (count)] > 1 + SH_DYNAMIC_SHIFT_COST;
1595 }
1596
1597 /* Try to find a good way to implement the combiner pattern
1598   [(set (match_operand:SI 0 "register_operand" "r")
1599         (and:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
1600                            (match_operand:SI 2 "const_int_operand" "n"))
1601                 (match_operand:SI 3 "const_int_operand" "n"))) .
1602   LEFT_RTX is operand 2 in the above pattern, and MASK_RTX is operand 3.
1603   return 0 for simple right / left or left/right shift combination.
1604   return 1 for a combination of shifts with zero_extend.
1605   return 2 for a combination of shifts with an AND that needs r0.
1606   return 3 for a combination of shifts with an AND that needs an extra
1607     scratch register, when the three highmost bits of the AND mask are clear.
1608   return 4 for a combination of shifts with an AND that needs an extra
1609     scratch register, when any of the three highmost bits of the AND mask
1610     is set.
1611   If ATTRP is set, store an initial right shift width in ATTRP[0],
1612   and the instruction length in ATTRP[1] .  These values are not valid
1613   when returning 0.
1614   When ATTRP is set and returning 1, ATTRP[2] gets set to the index into
1615   shift_amounts for the last shift value that is to be used before the
1616   sign extend.  */
1617 int
1618 shl_and_kind (left_rtx, mask_rtx, attrp)
1619      rtx left_rtx, mask_rtx;
1620      int *attrp;
1621 {
1622   unsigned HOST_WIDE_INT mask, lsb, mask2, lsb2;
1623   int left = INTVAL (left_rtx), right;
1624   int best = 0;
1625   int cost, best_cost = 10000;
1626   int best_right = 0, best_len = 0;
1627   int i;
1628   int can_ext;
1629
1630   if (left < 0 || left > 31)
1631     return 0;
1632   if (GET_CODE (mask_rtx) == CONST_INT)
1633     mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> left;
1634   else
1635     mask = (unsigned HOST_WIDE_INT) GET_MODE_MASK (SImode) >> left;
1636   /* Can this be expressed as a right shift / left shift pair ? */
1637   lsb = ((mask ^ (mask - 1)) >> 1) + 1;
1638   right = exact_log2 (lsb);
1639   mask2 = ~(mask + lsb - 1);
1640   lsb2 = ((mask2 ^ (mask2 - 1)) >> 1) + 1;
1641   /* mask has no zeroes but trailing zeroes <==> ! mask2 */
1642   if (! mask2)
1643     best_cost = shift_insns[right] + shift_insns[right + left];
1644   /* mask has no trailing zeroes <==> ! right */
1645   else if (! right && mask2 == ~(lsb2 - 1))
1646     {
1647       int late_right = exact_log2 (lsb2);
1648       best_cost = shift_insns[left + late_right] + shift_insns[late_right];
1649     }
1650   /* Try to use zero extend */
1651   if (mask2 == ~(lsb2 - 1))
1652     {
1653       int width, first;
1654
1655       for (width = 8; width <= 16; width += 8)
1656         {
1657           /* Can we zero-extend right away? */
1658           if (lsb2 == (unsigned HOST_WIDE_INT)1 << width)
1659             {
1660               cost
1661                 = 1 + ext_shift_insns[right] + ext_shift_insns[left + right];
1662               if (cost < best_cost)
1663                 {
1664                   best = 1;
1665                   best_cost = cost;
1666                   best_right = right;
1667                   best_len = cost;
1668                   if (attrp)
1669                     attrp[2] = -1;
1670                 }
1671               continue;
1672             }
1673           /* ??? Could try to put zero extend into initial right shift,
1674              or even shift a bit left before the right shift.  */
1675           /* Determine value of first part of left shift, to get to the
1676              zero extend cut-off point.  */
1677           first = width - exact_log2 (lsb2) + right;
1678           if (first >= 0 && right + left - first >= 0)
1679             {
1680               cost = ext_shift_insns[right] + ext_shift_insns[first] + 1
1681                 + ext_shift_insns[right + left - first];
1682               if (cost < best_cost)
1683                 {
1684                   best = 1;
1685                   best_cost = cost;
1686                   best_right = right;
1687                   best_len = cost;
1688                   if (attrp)
1689                     attrp[2] = first;
1690                   }
1691             }
1692         }
1693     }
1694   /* Try to use r0 AND pattern */
1695   for (i = 0; i <= 2; i++)
1696     {
1697       if (i > right)
1698         break;
1699       if (! CONST_OK_FOR_L (mask >> i))
1700         continue;
1701       cost = (i != 0) + 2 + ext_shift_insns[left + i];
1702       if (cost < best_cost)
1703         {
1704           best = 2;
1705           best_cost = cost;
1706           best_right = i;
1707           best_len = cost - 1;
1708         }
1709     }
1710   /* Try to use a scratch register to hold the AND operand.  */
1711   can_ext = ((mask << left) & ((unsigned HOST_WIDE_INT)3 << 30)) == 0;
1712   for (i = 0; i <= 2; i++)
1713     {
1714       if (i > right)
1715         break;
1716       cost = (i != 0) + (CONST_OK_FOR_I (mask >> i) ? 2 : 3)
1717         + (can_ext ? ext_shift_insns : shift_insns)[left + i];
1718       if (cost < best_cost)
1719         {
1720           best = 4 - can_ext;
1721           best_cost = cost;
1722           best_right = i;
1723           best_len = cost - 1 - ! CONST_OK_FOR_I (mask >> i);
1724         }
1725     }
1726
1727   if (attrp)
1728     {
1729       attrp[0] = best_right;
1730       attrp[1] = best_len;
1731     }
1732   return best;
1733 }
1734
1735 /* This is used in length attributes of the unnamed instructions
1736    corresponding to shl_and_kind return values of 1 and 2.  */
1737 int
1738 shl_and_length (insn)
1739      rtx insn;
1740 {
1741   rtx set_src, left_rtx, mask_rtx;
1742   int attributes[3];
1743
1744   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
1745   left_rtx = XEXP (XEXP (set_src, 0), 1);
1746   mask_rtx = XEXP (set_src, 1);
1747   shl_and_kind (left_rtx, mask_rtx, attributes);
1748   return attributes[1];
1749 }
1750
1751 /* This is used in length attribute of the and_shl_scratch instruction.  */
1752
1753 int
1754 shl_and_scr_length (insn)
1755      rtx insn;
1756 {
1757   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
1758   int len = shift_insns[INTVAL (XEXP (set_src, 1))];
1759   rtx op = XEXP (set_src, 0);
1760   len += shift_insns[INTVAL (XEXP (op, 1))] + 1;
1761   op = XEXP (XEXP (op, 0), 0);
1762   return len + shift_insns[INTVAL (XEXP (op, 1))];
1763 }
1764
1765 /* Generating rtl? */
1766 extern int rtx_equal_function_value_matters;
1767
1768 /* Generate rtl for instructions for which shl_and_kind advised a particular
1769    method of generating them, i.e. returned zero.  */
1770
1771 int
1772 gen_shl_and (dest, left_rtx, mask_rtx, source)
1773      rtx dest, left_rtx, mask_rtx, source;
1774 {
1775   int attributes[3];
1776   unsigned HOST_WIDE_INT mask;
1777   int kind = shl_and_kind (left_rtx, mask_rtx, attributes);
1778   int right, total_shift;
1779   void (*shift_gen_fun) PARAMS ((int, rtx*)) = gen_shifty_hi_op;
1780
1781   right = attributes[0];
1782   total_shift = INTVAL (left_rtx) + right;
1783   mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> total_shift;
1784   switch (kind)
1785     {
1786     default:
1787       return -1;
1788     case 1:
1789       {
1790         int first = attributes[2];
1791         rtx operands[3];
1792
1793         if (first < 0)
1794           {
1795             emit_insn ((mask << right) <= 0xff
1796                        ? gen_zero_extendqisi2(dest,
1797                                               gen_lowpart (QImode, source))
1798                        : gen_zero_extendhisi2(dest,
1799                                               gen_lowpart (HImode, source)));
1800             source = dest;
1801           }
1802         if (source != dest)
1803           emit_insn (gen_movsi (dest, source));
1804         operands[0] = dest;
1805         if (right)
1806           {
1807             operands[2] = GEN_INT (right);
1808             gen_shifty_hi_op (LSHIFTRT, operands);
1809           }
1810         if (first > 0)
1811           {
1812             operands[2] = GEN_INT (first);
1813             gen_shifty_hi_op (ASHIFT, operands);
1814             total_shift -= first;
1815             mask <<= first;
1816           }
1817         if (first >= 0)
1818           emit_insn (mask <= 0xff
1819                      ? gen_zero_extendqisi2(dest, gen_lowpart (QImode, dest))
1820                      : gen_zero_extendhisi2(dest, gen_lowpart (HImode, dest)));
1821         if (total_shift > 0)
1822           {
1823             operands[2] = GEN_INT (total_shift);
1824             gen_shifty_hi_op (ASHIFT, operands);
1825           }
1826         break;
1827       }
1828     case 4:
1829       shift_gen_fun = gen_shifty_op;
1830     case 3:
1831       /* If the topmost bit that matters is set, set the topmost bits
1832          that don't matter.  This way, we might be able to get a shorter
1833          signed constant.  */
1834       if (mask & ((HOST_WIDE_INT)1 << (31 - total_shift)))
1835         mask |= (HOST_WIDE_INT)~0 << (31 - total_shift);
1836     case 2:
1837       /* Don't expand fine-grained when combining, because that will
1838          make the pattern fail.  */
1839       if (rtx_equal_function_value_matters
1840           || reload_in_progress || reload_completed)
1841         {
1842           rtx operands[3];
1843   
1844           /* Cases 3 and 4 should be handled by this split
1845              only while combining  */
1846           if (kind > 2)
1847             abort ();
1848           if (right)
1849             {
1850               emit_insn (gen_lshrsi3 (dest, source, GEN_INT (right)));
1851               source = dest;
1852             }
1853           emit_insn (gen_andsi3 (dest, source, GEN_INT (mask)));
1854           if (total_shift)
1855             {
1856               operands[0] = dest;
1857               operands[1] = dest;
1858               operands[2] = GEN_INT (total_shift);
1859               shift_gen_fun (ASHIFT, operands);
1860             }
1861           break;
1862         }
1863       else
1864         {
1865           int neg = 0;
1866           if (kind != 4 && total_shift < 16)
1867             {
1868               neg = -ext_shift_amounts[total_shift][1];
1869               if (neg > 0)
1870                 neg -= ext_shift_amounts[total_shift][2];
1871               else
1872                 neg = 0;
1873             }
1874           emit_insn (gen_and_shl_scratch (dest, source,
1875                                           GEN_INT (right),
1876                                           GEN_INT (mask),
1877                                           GEN_INT (total_shift + neg),
1878                                           GEN_INT (neg)));
1879           emit_insn (gen_movsi (dest, dest));
1880           break;
1881         }
1882     }
1883   return 0;
1884 }
1885
1886 /* Try to find a good way to implement the combiner pattern
1887   [(set (match_operand:SI 0 "register_operand" "=r")
1888         (sign_extract:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
1889                                     (match_operand:SI 2 "const_int_operand" "n")
1890                          (match_operand:SI 3 "const_int_operand" "n")
1891                          (const_int 0)))
1892    (clobber (reg:SI T_REG))]
1893   LEFT_RTX is operand 2 in the above pattern, and SIZE_RTX is operand 3.
1894   return 0 for simple left / right shift combination.
1895   return 1 for left shift / 8 bit sign extend / left shift.
1896   return 2 for left shift / 16 bit sign extend / left shift.
1897   return 3 for left shift / 8 bit sign extend / shift / sign extend.
1898   return 4 for left shift / 16 bit sign extend / shift / sign extend.
1899   return 5 for left shift / 16 bit sign extend / right shift
1900   return 6 for < 8 bit sign extend / left shift.
1901   return 7 for < 8 bit sign extend / left shift / single right shift.
1902   If COSTP is nonzero, assign the calculated cost to *COSTP.  */
1903
1904 int
1905 shl_sext_kind (left_rtx, size_rtx, costp)
1906      rtx left_rtx, size_rtx;
1907      int *costp;
1908 {
1909   int left, size, insize, ext;
1910   int cost, best_cost;
1911   int kind;
1912
1913   left = INTVAL (left_rtx);
1914   size = INTVAL (size_rtx);
1915   insize = size - left;
1916   if (insize <= 0)
1917     abort ();
1918   /* Default to left / right shift.  */
1919   kind = 0;
1920   best_cost = shift_insns[32 - insize] + ashiftrt_insns[32 - size];
1921   if (size <= 16)
1922     {
1923       /* 16 bit shift / sign extend / 16 bit shift */
1924       cost = shift_insns[16 - insize] + 1 + ashiftrt_insns[16 - size];
1925       /* If ashiftrt_insns[16 - size] is 8, this choice will be overridden
1926          below, by alternative 3 or something even better.  */
1927       if (cost < best_cost)
1928         {
1929           kind = 5;
1930           best_cost = cost;
1931         }
1932     }
1933   /* Try a plain sign extend between two shifts.  */
1934   for (ext = 16; ext >= insize; ext -= 8)
1935     {
1936       if (ext <= size)
1937         {
1938           cost = ext_shift_insns[ext - insize] + 1 + shift_insns[size - ext];
1939           if (cost < best_cost)
1940             {
1941               kind = ext / (unsigned) 8;
1942               best_cost = cost;
1943             }
1944         }
1945       /* Check if we can do a sloppy shift with a final signed shift
1946          restoring the sign.  */
1947       if (EXT_SHIFT_SIGNED (size - ext))
1948         cost = ext_shift_insns[ext - insize] + ext_shift_insns[size - ext] + 1;
1949       /* If not, maybe it's still cheaper to do the second shift sloppy,
1950          and do a final sign extend?  */
1951       else if (size <= 16)
1952         cost = ext_shift_insns[ext - insize] + 1
1953           + ext_shift_insns[size > ext ? size - ext : ext - size] + 1;
1954       else
1955         continue;
1956       if (cost < best_cost)
1957         {
1958           kind = ext / (unsigned) 8 + 2;
1959           best_cost = cost;
1960         }
1961     }
1962   /* Check if we can sign extend in r0 */
1963   if (insize < 8)
1964     {
1965       cost = 3 + shift_insns[left];
1966       if (cost < best_cost)
1967         {
1968           kind = 6;
1969           best_cost = cost;
1970         }
1971       /* Try the same with a final signed shift.  */
1972       if (left < 31)
1973         {
1974           cost = 3 + ext_shift_insns[left + 1] + 1;
1975           if (cost < best_cost)
1976             {
1977               kind = 7;
1978               best_cost = cost;
1979             }
1980         }
1981     }
1982   if (TARGET_SH3)
1983     {
1984       /* Try to use a dynamic shift.  */
1985       cost = shift_insns[32 - insize] + 1 + SH_DYNAMIC_SHIFT_COST;
1986       if (cost < best_cost)
1987         {
1988           kind = 0;
1989           best_cost = cost;
1990         }
1991     }
1992   if (costp)
1993     *costp = cost;
1994   return kind;
1995 }
1996
1997 /* Function to be used in the length attribute of the instructions
1998    implementing this pattern.  */
1999
2000 int
2001 shl_sext_length (insn)
2002      rtx insn;
2003 {
2004   rtx set_src, left_rtx, size_rtx;
2005   int cost;
2006
2007   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2008   left_rtx = XEXP (XEXP (set_src, 0), 1);
2009   size_rtx = XEXP (set_src, 1);
2010   shl_sext_kind (left_rtx, size_rtx, &cost);
2011   return cost;
2012 }
2013
2014 /* Generate rtl for this pattern */
2015
2016 int
2017 gen_shl_sext (dest, left_rtx, size_rtx, source)
2018      rtx dest, left_rtx, size_rtx, source;
2019 {
2020   int kind;
2021   int left, size, insize, cost;
2022   rtx operands[3];
2023
2024   kind = shl_sext_kind (left_rtx, size_rtx, &cost);
2025   left = INTVAL (left_rtx);
2026   size = INTVAL (size_rtx);
2027   insize = size - left;
2028   switch (kind)
2029     {
2030     case 1:
2031     case 2:
2032     case 3:
2033     case 4:
2034       {
2035         int ext = kind & 1 ? 8 : 16;
2036         int shift2 = size - ext;
2037
2038         /* Don't expand fine-grained when combining, because that will
2039            make the pattern fail.  */
2040         if (! rtx_equal_function_value_matters
2041             && ! reload_in_progress && ! reload_completed)
2042           {
2043             emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2044             emit_insn (gen_movsi (dest, source));
2045             break;
2046           }
2047         if (dest != source)
2048           emit_insn (gen_movsi (dest, source));
2049         operands[0] = dest;
2050         if (ext - insize)
2051           {
2052             operands[2] = GEN_INT (ext - insize);
2053             gen_shifty_hi_op (ASHIFT, operands);
2054           }
2055         emit_insn (kind & 1
2056                    ? gen_extendqisi2(dest, gen_lowpart (QImode, dest))
2057                    : gen_extendhisi2(dest, gen_lowpart (HImode, dest)));
2058         if (kind <= 2)
2059           {
2060             if (shift2)
2061               {
2062                 operands[2] = GEN_INT (shift2);
2063                 gen_shifty_op (ASHIFT, operands);
2064               }
2065           }
2066         else
2067           {
2068             if (shift2 > 0)
2069               {
2070                 if (EXT_SHIFT_SIGNED (shift2))
2071                   {
2072                     operands[2] = GEN_INT (shift2 + 1);
2073                     gen_shifty_op (ASHIFT, operands);
2074                     operands[2] = GEN_INT (1);
2075                     gen_shifty_op (ASHIFTRT, operands);
2076                     break;
2077                   }
2078                 operands[2] = GEN_INT (shift2);
2079                 gen_shifty_hi_op (ASHIFT, operands);
2080               }
2081             else if (shift2)
2082               {
2083                 operands[2] = GEN_INT (-shift2);
2084                 gen_shifty_hi_op (LSHIFTRT, operands);
2085               }
2086             emit_insn (size <= 8
2087                        ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
2088                        : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2089           }
2090         break;
2091       }
2092     case 5:
2093       {
2094         int i = 16 - size;
2095         if (! rtx_equal_function_value_matters
2096             && ! reload_in_progress && ! reload_completed)
2097           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2098         else
2099           {
2100             operands[0] = dest;
2101             operands[2] = GEN_INT (16 - insize);
2102             gen_shifty_hi_op (ASHIFT, operands);
2103             emit_insn (gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2104           }
2105         /* Don't use gen_ashrsi3 because it generates new pseudos.  */
2106         while (--i >= 0)
2107           gen_ashift (ASHIFTRT, 1, dest);
2108         break;
2109       }
2110     case 6:
2111     case 7:
2112       /* Don't expand fine-grained when combining, because that will
2113          make the pattern fail.  */
2114       if (! rtx_equal_function_value_matters
2115           && ! reload_in_progress && ! reload_completed)
2116         {
2117           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2118           emit_insn (gen_movsi (dest, source));
2119           break;
2120         }
2121       emit_insn (gen_andsi3 (dest, source, GEN_INT ((1 << insize) - 1)));
2122       emit_insn (gen_xorsi3 (dest, dest, GEN_INT (1 << (insize - 1))));
2123       emit_insn (gen_addsi3 (dest, dest, GEN_INT (-1 << (insize - 1))));
2124       operands[0] = dest;
2125       operands[2] = kind == 7 ? GEN_INT (left + 1) : left_rtx;
2126       gen_shifty_op (ASHIFT, operands);
2127       if (kind == 7)
2128         emit_insn (gen_ashrsi3_k (dest, dest, GEN_INT (1)));
2129       break;
2130     default:
2131       return -1;
2132     }
2133   return 0;
2134 }
2135
2136 /* Prefix a symbol_ref name with "datalabel".  */
2137
2138 rtx
2139 gen_datalabel_ref (sym)
2140      rtx sym;
2141 {
2142   if (GET_CODE (sym) == LABEL_REF)
2143     return gen_rtx_CONST (GET_MODE (sym),
2144                           gen_rtx_UNSPEC (GET_MODE (sym),
2145                                           gen_rtvec (1, sym),
2146                                           UNSPEC_DATALABEL));
2147     
2148   if (GET_CODE (sym) != SYMBOL_REF)
2149     abort ();
2150
2151   XSTR (sym, 0) = concat (SH_DATALABEL_ENCODING, XSTR (sym, 0), NULL);
2152
2153   return sym;
2154 }
2155
2156 \f
2157 /* The SH cannot load a large constant into a register, constants have to
2158    come from a pc relative load.  The reference of a pc relative load
2159    instruction must be less than 1k infront of the instruction.  This
2160    means that we often have to dump a constant inside a function, and
2161    generate code to branch around it.
2162
2163    It is important to minimize this, since the branches will slow things
2164    down and make things bigger.
2165
2166    Worst case code looks like:
2167
2168    mov.l L1,rn
2169    bra   L2
2170    nop
2171    align
2172    L1:   .long value
2173    L2:
2174    ..
2175
2176    mov.l L3,rn
2177    bra   L4
2178    nop
2179    align
2180    L3:   .long value
2181    L4:
2182    ..
2183
2184    We fix this by performing a scan before scheduling, which notices which
2185    instructions need to have their operands fetched from the constant table
2186    and builds the table.
2187
2188    The algorithm is:
2189
2190    scan, find an instruction which needs a pcrel move.  Look forward, find the
2191    last barrier which is within MAX_COUNT bytes of the requirement.
2192    If there isn't one, make one.  Process all the instructions between
2193    the find and the barrier.
2194
2195    In the above example, we can tell that L3 is within 1k of L1, so
2196    the first move can be shrunk from the 3 insn+constant sequence into
2197    just 1 insn, and the constant moved to L3 to make:
2198
2199    mov.l        L1,rn
2200    ..
2201    mov.l        L3,rn
2202    bra          L4
2203    nop
2204    align
2205    L3:.long value
2206    L4:.long value
2207
2208    Then the second move becomes the target for the shortening process.  */
2209
2210 typedef struct
2211 {
2212   rtx value;                    /* Value in table.  */
2213   rtx label;                    /* Label of value.  */
2214   rtx wend;                     /* End of window.  */
2215   enum machine_mode mode;       /* Mode of value.  */
2216 } pool_node;
2217
2218 /* The maximum number of constants that can fit into one pool, since
2219    the pc relative range is 0...1020 bytes and constants are at least 4
2220    bytes long.  */
2221
2222 #define MAX_POOL_SIZE (1020/4)
2223 static pool_node pool_vector[MAX_POOL_SIZE];
2224 static int pool_size;
2225 static rtx pool_window_label;
2226 static int pool_window_last;
2227
2228 /* ??? If we need a constant in HImode which is the truncated value of a
2229    constant we need in SImode, we could combine the two entries thus saving
2230    two bytes.  Is this common enough to be worth the effort of implementing
2231    it?  */
2232
2233 /* ??? This stuff should be done at the same time that we shorten branches.
2234    As it is now, we must assume that all branches are the maximum size, and
2235    this causes us to almost always output constant pools sooner than
2236    necessary.  */
2237
2238 /* Add a constant to the pool and return its label.  */
2239
2240 static rtx
2241 add_constant (x, mode, last_value)
2242      rtx x;
2243      enum machine_mode mode;
2244      rtx last_value;
2245 {
2246   int i;
2247   rtx lab, new, ref, newref;
2248
2249   /* First see if we've already got it.  */
2250   for (i = 0; i < pool_size; i++)
2251     {
2252       if (x->code == pool_vector[i].value->code
2253           && mode == pool_vector[i].mode)
2254         {
2255           if (x->code == CODE_LABEL)
2256             {
2257               if (XINT (x, 3) != XINT (pool_vector[i].value, 3))
2258                 continue;
2259             }
2260           if (rtx_equal_p (x, pool_vector[i].value))
2261             {
2262               lab = new = 0;
2263               if (! last_value
2264                   || ! i
2265                   || ! rtx_equal_p (last_value, pool_vector[i-1].value))
2266                 {
2267                   new = gen_label_rtx ();
2268                   LABEL_REFS (new) = pool_vector[i].label;
2269                   pool_vector[i].label = lab = new;
2270                 }
2271               if (lab && pool_window_label)
2272                 {
2273                   newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2274                   ref = pool_vector[pool_window_last].wend;
2275                   LABEL_NEXTREF (newref) = ref;
2276                   pool_vector[pool_window_last].wend = newref;
2277                 }
2278               if (new)
2279                 pool_window_label = new;
2280               pool_window_last = i;
2281               return lab;
2282             }
2283         }
2284     }
2285
2286   /* Need a new one.  */
2287   pool_vector[pool_size].value = x;
2288   if (last_value && rtx_equal_p (last_value, pool_vector[pool_size - 1].value))
2289     lab = 0;
2290   else
2291     lab = gen_label_rtx ();
2292   pool_vector[pool_size].mode = mode;
2293   pool_vector[pool_size].label = lab;
2294   pool_vector[pool_size].wend = NULL_RTX;
2295   if (lab && pool_window_label)
2296     {
2297       newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2298       ref = pool_vector[pool_window_last].wend;
2299       LABEL_NEXTREF (newref) = ref;
2300       pool_vector[pool_window_last].wend = newref;
2301     }
2302   if (lab)
2303     pool_window_label = lab;
2304   pool_window_last = pool_size;
2305   pool_size++;
2306   return lab;
2307 }
2308
2309 /* Output the literal table.  */
2310
2311 static void
2312 dump_table (scan)
2313      rtx scan;
2314 {
2315   int i;
2316   int need_align = 1;
2317   rtx lab, ref;
2318   int have_di = 0;
2319
2320   /* Do two passes, first time dump out the HI sized constants.  */
2321
2322   for (i = 0; i < pool_size; i++)
2323     {
2324       pool_node *p = &pool_vector[i];
2325
2326       if (p->mode == HImode)
2327         {
2328           if (need_align)
2329             {
2330               scan = emit_insn_after (gen_align_2 (), scan);
2331               need_align = 0;
2332             }
2333           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2334             scan = emit_label_after (lab, scan);
2335           scan = emit_insn_after (gen_consttable_2 (p->value, const0_rtx),
2336                                   scan);
2337           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2338             {
2339               lab = XEXP (ref, 0);
2340               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2341             }
2342         }
2343       else if (p->mode == DImode || p->mode == DFmode)
2344         have_di = 1;
2345     }
2346
2347   need_align = 1;
2348
2349   if (TARGET_SHCOMPACT && have_di)
2350     {
2351       rtx align_insn = NULL_RTX;
2352
2353       scan = emit_label_after (gen_label_rtx (), scan);
2354       scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2355       need_align = 0;
2356
2357       for (i = 0; i < pool_size; i++)
2358         {
2359           pool_node *p = &pool_vector[i];
2360
2361           switch (p->mode)
2362             {
2363             case HImode:
2364               break;
2365             case SImode:
2366             case SFmode:
2367               if (align_insn)
2368                 {
2369                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2370                     emit_label_before (lab, align_insn);
2371                   emit_insn_before (gen_consttable_4 (p->value, const0_rtx),
2372                                     align_insn);
2373                   for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2374                     {
2375                       lab = XEXP (ref, 0);
2376                       emit_insn_before (gen_consttable_window_end (lab),
2377                                        align_insn);
2378                     }
2379                   delete_insn (align_insn);
2380                   align_insn = NULL_RTX;
2381                   continue;
2382                 }
2383               else
2384                 {
2385                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2386                     scan = emit_label_after (lab, scan);
2387                   scan = emit_insn_after (gen_consttable_4 (p->value,
2388                                                             const0_rtx), scan);
2389                   need_align = ! need_align;
2390                 }
2391               break;
2392             case DFmode:
2393             case DImode:
2394               if (need_align)
2395                 {
2396                   scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2397                   align_insn = scan;
2398                   need_align = 0;
2399                 }
2400               for (lab = p->label; lab; lab = LABEL_REFS (lab))
2401                 scan = emit_label_after (lab, scan);
2402               scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2403                                       scan);
2404               break;
2405             default:
2406               abort ();
2407               break;
2408             }
2409
2410           if (p->mode != HImode)
2411             {
2412               for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2413                 {
2414                   lab = XEXP (ref, 0);
2415                   scan = emit_insn_after (gen_consttable_window_end (lab),
2416                                           scan);
2417                 }
2418             }
2419         }
2420
2421       pool_size = 0;
2422     }
2423   
2424   for (i = 0; i < pool_size; i++)
2425     {
2426       pool_node *p = &pool_vector[i];
2427
2428       switch (p->mode)
2429         {
2430         case HImode:
2431           break;
2432         case SImode:
2433         case SFmode:
2434           if (need_align)
2435             {
2436               need_align = 0;
2437               scan = emit_label_after (gen_label_rtx (), scan);
2438               scan = emit_insn_after (gen_align_4 (), scan);
2439             }
2440           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2441             scan = emit_label_after (lab, scan);
2442           scan = emit_insn_after (gen_consttable_4 (p->value, const0_rtx),
2443                                   scan);
2444           break;
2445         case DFmode:
2446         case DImode:
2447           if (need_align)
2448             {
2449               need_align = 0;
2450               scan = emit_label_after (gen_label_rtx (), scan);
2451               scan = emit_insn_after (gen_align_4 (), scan);
2452             }
2453           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2454             scan = emit_label_after (lab, scan);
2455           scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2456                                   scan);
2457           break;
2458         default:
2459           abort ();
2460           break;
2461         }
2462
2463       if (p->mode != HImode)
2464         {
2465           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2466             {
2467               lab = XEXP (ref, 0);
2468               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2469             }
2470         }
2471     }
2472
2473   scan = emit_insn_after (gen_consttable_end (), scan);
2474   scan = emit_barrier_after (scan);
2475   pool_size = 0;
2476   pool_window_label = NULL_RTX;
2477   pool_window_last = 0;
2478 }
2479
2480 /* Return non-zero if constant would be an ok source for a
2481    mov.w instead of a mov.l.  */
2482
2483 static int
2484 hi_const (src)
2485      rtx src;
2486 {
2487   return (GET_CODE (src) == CONST_INT
2488           && INTVAL (src) >= -32768
2489           && INTVAL (src) <= 32767);
2490 }
2491
2492 /* Non-zero if the insn is a move instruction which needs to be fixed.  */
2493
2494 /* ??? For a DImode/DFmode moves, we don't need to fix it if each half of the
2495    CONST_DOUBLE input value is CONST_OK_FOR_I.  For a SFmode move, we don't
2496    need to fix it if the input value is CONST_OK_FOR_I.  */
2497
2498 static int
2499 broken_move (insn)
2500      rtx insn;
2501 {
2502   if (GET_CODE (insn) == INSN)
2503     {
2504       rtx pat = PATTERN (insn);
2505       if (GET_CODE (pat) == PARALLEL)
2506         pat = XVECEXP (pat, 0, 0);
2507       if (GET_CODE (pat) == SET
2508           /* We can load any 8 bit value if we don't care what the high
2509              order bits end up as.  */
2510           && GET_MODE (SET_DEST (pat)) != QImode
2511           && (CONSTANT_P (SET_SRC (pat))
2512               /* Match mova_const.  */
2513               || (GET_CODE (SET_SRC (pat)) == UNSPEC
2514                   && XINT (SET_SRC (pat), 1) == UNSPEC_MOVA
2515                   && GET_CODE (XVECEXP (SET_SRC (pat), 0, 0)) == CONST))
2516           && ! (TARGET_SH3E
2517                 && GET_CODE (SET_SRC (pat)) == CONST_DOUBLE
2518                 && (fp_zero_operand (SET_SRC (pat))
2519                     || fp_one_operand (SET_SRC (pat)))
2520                 /* ??? If this is a -m4 or -m4-single compilation, in general
2521                    we don't know the current setting of fpscr, so disable fldi.
2522                    There is an exception if this was a register-register move
2523                    before reload - and hence it was ascertained that we have
2524                    single precision setting - and in a post-reload optimization
2525                    we changed this to do a constant load.  In that case
2526                    we don't have an r0 clobber, hence we must use fldi.  */
2527                 && (! TARGET_SH4 || TARGET_FMOVD
2528                     || (GET_CODE (XEXP (XVECEXP (PATTERN (insn), 0, 2), 0))
2529                         == SCRATCH))
2530                 && GET_CODE (SET_DEST (pat)) == REG
2531                 && FP_REGISTER_P (REGNO (SET_DEST (pat))))
2532           && (GET_CODE (SET_SRC (pat)) != CONST_INT
2533               || ! CONST_OK_FOR_I (INTVAL (SET_SRC (pat)))))
2534         return 1;
2535     }
2536
2537   return 0;
2538 }
2539
2540 static int
2541 mova_p (insn)
2542      rtx insn;
2543 {
2544   return (GET_CODE (insn) == INSN
2545           && GET_CODE (PATTERN (insn)) == SET
2546           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
2547           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_MOVA
2548           /* Don't match mova_const.  */
2549           && GET_CODE (XVECEXP (SET_SRC (PATTERN (insn)), 0, 0)) == LABEL_REF);
2550 }
2551
2552 /* Find the last barrier from insn FROM which is close enough to hold the
2553    constant pool.  If we can't find one, then create one near the end of
2554    the range.  */
2555
2556 static rtx
2557 find_barrier (num_mova, mova, from)
2558      int num_mova;
2559      rtx mova, from;
2560 {
2561   int count_si = 0;
2562   int count_hi = 0;
2563   int found_hi = 0;
2564   int found_si = 0;
2565   int found_di = 0;
2566   int hi_align = 2;
2567   int si_align = 2;
2568   int leading_mova = num_mova;
2569   rtx barrier_before_mova, found_barrier = 0, good_barrier = 0;
2570   int si_limit;
2571   int hi_limit;
2572
2573   /* For HImode: range is 510, add 4 because pc counts from address of
2574      second instruction after this one, subtract 2 for the jump instruction
2575      that we may need to emit before the table, subtract 2 for the instruction
2576      that fills the jump delay slot (in very rare cases, reorg will take an
2577      instruction from after the constant pool or will leave the delay slot
2578      empty).  This gives 510.
2579      For SImode: range is 1020, add 4 because pc counts from address of
2580      second instruction after this one, subtract 2 in case pc is 2 byte
2581      aligned, subtract 2 for the jump instruction that we may need to emit
2582      before the table, subtract 2 for the instruction that fills the jump
2583      delay slot.  This gives 1018.  */
2584
2585   /* The branch will always be shortened now that the reference address for
2586      forward branches is the successor address, thus we need no longer make
2587      adjustments to the [sh]i_limit for -O0.  */
2588
2589   si_limit = 1018;
2590   hi_limit = 510;
2591
2592   while (from && count_si < si_limit && count_hi < hi_limit)
2593     {
2594       int inc = get_attr_length (from);
2595       int new_align = 1;
2596
2597       if (GET_CODE (from) == CODE_LABEL)
2598         {
2599           if (optimize)
2600             new_align = 1 << label_to_alignment (from);
2601           else if (GET_CODE (prev_nonnote_insn (from)) == BARRIER)
2602             new_align = 1 << barrier_align (from);
2603           else
2604             new_align = 1;
2605           inc = 0;
2606         }
2607
2608       if (GET_CODE (from) == BARRIER)
2609         {
2610
2611           found_barrier = from;
2612
2613           /* If we are at the end of the function, or in front of an alignment
2614              instruction, we need not insert an extra alignment.  We prefer
2615              this kind of barrier.  */
2616           if (barrier_align (from) > 2)
2617             good_barrier = from;
2618         }
2619
2620       if (broken_move (from))
2621         {
2622           rtx pat, src, dst;
2623           enum machine_mode mode;
2624
2625           pat = PATTERN (from);
2626           if (GET_CODE (pat) == PARALLEL)
2627             pat = XVECEXP (pat, 0, 0);
2628           src = SET_SRC (pat);
2629           dst = SET_DEST (pat);
2630           mode = GET_MODE (dst);
2631
2632           /* We must explicitly check the mode, because sometimes the
2633              front end will generate code to load unsigned constants into
2634              HImode targets without properly sign extending them.  */
2635           if (mode == HImode
2636               || (mode == SImode && hi_const (src) && REGNO (dst) != FPUL_REG))
2637             {
2638               found_hi += 2;
2639               /* We put the short constants before the long constants, so
2640                  we must count the length of short constants in the range
2641                  for the long constants.  */
2642               /* ??? This isn't optimal, but is easy to do.  */
2643               si_limit -= 2;
2644             }
2645           else
2646             {
2647               /* We dump DF/DI constants before SF/SI ones, because
2648                  the limit is the same, but the alignment requirements
2649                  are higher.  We may waste up to 4 additional bytes
2650                  for alignment, and the DF/DI constant may have
2651                  another SF/SI constant placed before it. */
2652               if (TARGET_SHCOMPACT
2653                   && ! found_di
2654                   && (mode == DFmode || mode == DImode))
2655                 {
2656                   found_di = 1;
2657                   si_limit -= 8;
2658                 }
2659               while (si_align > 2 && found_si + si_align - 2 > count_si)
2660                 si_align >>= 1;
2661               if (found_si > count_si)
2662                 count_si = found_si;
2663               found_si += GET_MODE_SIZE (mode);
2664               if (num_mova)
2665                 si_limit -= GET_MODE_SIZE (mode);
2666             }
2667
2668           /* See the code in machine_dependent_reorg, which has a similar if
2669              statement that generates a new mova insn in many cases.  */
2670           if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
2671             inc += 2;
2672         }
2673
2674       if (mova_p (from))
2675         {
2676           if (! num_mova++)
2677             {
2678               leading_mova = 0;
2679               mova = from;
2680               barrier_before_mova = good_barrier ? good_barrier : found_barrier;
2681             }
2682           if (found_si > count_si)
2683             count_si = found_si;
2684         }
2685       else if (GET_CODE (from) == JUMP_INSN
2686                && (GET_CODE (PATTERN (from)) == ADDR_VEC
2687                    || GET_CODE (PATTERN (from)) == ADDR_DIFF_VEC))
2688         {
2689           if (num_mova)
2690             num_mova--;
2691           if (barrier_align (next_real_insn (from)) == CACHE_LOG)
2692             {
2693               /* We have just passed the barrier in front of the
2694                  ADDR_DIFF_VEC, which is stored in found_barrier.  Since
2695                  the ADDR_DIFF_VEC is accessed as data, just like our pool
2696                  constants, this is a good opportunity to accommodate what
2697                  we have gathered so far.
2698                  If we waited any longer, we could end up at a barrier in
2699                  front of code, which gives worse cache usage for separated
2700                  instruction / data caches.  */
2701               good_barrier = found_barrier;
2702               break;
2703             }
2704           else
2705             {
2706               rtx body = PATTERN (from);
2707               inc = XVECLEN (body, 1) * GET_MODE_SIZE (GET_MODE (body));
2708             }
2709         }
2710       /* For the SH1, we generate alignments even after jumps-around-jumps.  */
2711       else if (GET_CODE (from) == JUMP_INSN
2712                && ! TARGET_SH2
2713                && ! TARGET_SMALLCODE)
2714         new_align = 4;
2715
2716       if (found_si)
2717         {
2718           count_si += inc;
2719           if (new_align > si_align)
2720             {
2721               si_limit -= (count_si - 1) & (new_align - si_align);
2722               si_align = new_align;
2723             }
2724           count_si = (count_si + new_align - 1) & -new_align;
2725         }
2726       if (found_hi)
2727         {
2728           count_hi += inc;
2729           if (new_align > hi_align)
2730             {
2731               hi_limit -= (count_hi - 1) & (new_align - hi_align);
2732               hi_align = new_align;
2733             }
2734           count_hi = (count_hi + new_align - 1) & -new_align;
2735         }
2736       from = NEXT_INSN (from);
2737     }
2738
2739   if (num_mova)
2740     {
2741       if (leading_mova)
2742         {
2743           /* Try as we might, the leading mova is out of range.  Change
2744              it into a load (which will become a pcload) and retry.  */
2745           SET_SRC (PATTERN (mova)) = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
2746           INSN_CODE (mova) = -1;
2747           return find_barrier (0, 0, mova);
2748         }
2749       else
2750         {
2751           /* Insert the constant pool table before the mova instruction,
2752              to prevent the mova label reference from going out of range.  */
2753           from = mova;
2754           good_barrier = found_barrier = barrier_before_mova;
2755         }
2756     }
2757
2758   if (found_barrier)
2759     {
2760       if (good_barrier && next_real_insn (found_barrier))
2761         found_barrier = good_barrier;
2762     }
2763   else
2764     {
2765       /* We didn't find a barrier in time to dump our stuff,
2766          so we'll make one.  */
2767       rtx label = gen_label_rtx ();
2768
2769       /* If we exceeded the range, then we must back up over the last
2770          instruction we looked at.  Otherwise, we just need to undo the
2771          NEXT_INSN at the end of the loop.  */
2772       if (count_hi > hi_limit || count_si > si_limit)
2773         from = PREV_INSN (PREV_INSN (from));
2774       else
2775         from = PREV_INSN (from);
2776
2777       /* Walk back to be just before any jump or label.
2778          Putting it before a label reduces the number of times the branch
2779          around the constant pool table will be hit.  Putting it before
2780          a jump makes it more likely that the bra delay slot will be
2781          filled.  */
2782       while (GET_CODE (from) == JUMP_INSN || GET_CODE (from) == NOTE
2783              || GET_CODE (from) == CODE_LABEL)
2784         from = PREV_INSN (from);
2785
2786       from = emit_jump_insn_after (gen_jump (label), from);
2787       JUMP_LABEL (from) = label;
2788       LABEL_NUSES (label) = 1;
2789       found_barrier = emit_barrier_after (from);
2790       emit_label_after (label, found_barrier);
2791     }
2792
2793   return found_barrier;
2794 }
2795
2796 /* If the instruction INSN is implemented by a special function, and we can
2797    positively find the register that is used to call the sfunc, and this
2798    register is not used anywhere else in this instruction - except as the
2799    destination of a set, return this register; else, return 0.  */
2800 rtx
2801 sfunc_uses_reg (insn)
2802      rtx insn;
2803 {
2804   int i;
2805   rtx pattern, part, reg_part, reg;
2806
2807   if (GET_CODE (insn) != INSN)
2808     return 0;
2809   pattern = PATTERN (insn);
2810   if (GET_CODE (pattern) != PARALLEL || get_attr_type (insn) != TYPE_SFUNC)
2811     return 0;
2812
2813   for (reg_part = 0, i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
2814     {
2815       part = XVECEXP (pattern, 0, i);
2816       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == SImode)
2817         reg_part = part;
2818     }
2819   if (! reg_part)
2820     return 0;
2821   reg = XEXP (reg_part, 0);
2822   for (i = XVECLEN (pattern, 0) - 1; i >= 0; i--)
2823     {
2824       part = XVECEXP (pattern, 0, i);
2825       if (part == reg_part || GET_CODE (part) == CLOBBER)
2826         continue;
2827       if (reg_mentioned_p (reg, ((GET_CODE (part) == SET
2828                                   && GET_CODE (SET_DEST (part)) == REG)
2829                                  ? SET_SRC (part) : part)))
2830         return 0;
2831     }
2832   return reg;
2833 }
2834
2835 /* See if the only way in which INSN uses REG is by calling it, or by
2836    setting it while calling it.  Set *SET to a SET rtx if the register
2837    is set by INSN.  */
2838
2839 static int
2840 noncall_uses_reg (reg, insn, set)
2841      rtx reg;
2842      rtx insn;
2843      rtx *set;
2844 {
2845   rtx pattern, reg2;
2846
2847   *set = NULL_RTX;
2848
2849   reg2 = sfunc_uses_reg (insn);
2850   if (reg2 && REGNO (reg2) == REGNO (reg))
2851     {
2852       pattern = single_set (insn);
2853       if (pattern
2854           && GET_CODE (SET_DEST (pattern)) == REG
2855           && REGNO (reg) == REGNO (SET_DEST (pattern)))
2856         *set = pattern;
2857       return 0;
2858     }
2859   if (GET_CODE (insn) != CALL_INSN)
2860     {
2861       /* We don't use rtx_equal_p because we don't care if the mode is
2862          different.  */
2863       pattern = single_set (insn);
2864       if (pattern
2865           && GET_CODE (SET_DEST (pattern)) == REG
2866           && REGNO (reg) == REGNO (SET_DEST (pattern)))
2867         {
2868           rtx par, part;
2869           int i;
2870
2871           *set = pattern;
2872           par = PATTERN (insn);
2873           if (GET_CODE (par) == PARALLEL)
2874             for (i = XVECLEN (par, 0) - 1; i >= 0; i--)
2875               {
2876                 part = XVECEXP (par, 0, i);
2877                 if (GET_CODE (part) != SET && reg_mentioned_p (reg, part))
2878                   return 1;
2879               }
2880           return reg_mentioned_p (reg, SET_SRC (pattern));
2881         }
2882
2883       return 1;
2884     }
2885
2886   pattern = PATTERN (insn);
2887
2888   if (GET_CODE (pattern) == PARALLEL)
2889     {
2890       int i;
2891
2892       for (i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
2893         if (reg_mentioned_p (reg, XVECEXP (pattern, 0, i)))
2894           return 1;
2895       pattern = XVECEXP (pattern, 0, 0);
2896     }
2897
2898   if (GET_CODE (pattern) == SET)
2899     {
2900       if (reg_mentioned_p (reg, SET_DEST (pattern)))
2901         {
2902           /* We don't use rtx_equal_p, because we don't care if the
2903              mode is different.  */
2904           if (GET_CODE (SET_DEST (pattern)) != REG
2905               || REGNO (reg) != REGNO (SET_DEST (pattern)))
2906             return 1;
2907
2908           *set = pattern;
2909         }
2910
2911       pattern = SET_SRC (pattern);
2912     }
2913
2914   if (GET_CODE (pattern) != CALL
2915       || GET_CODE (XEXP (pattern, 0)) != MEM
2916       || ! rtx_equal_p (reg, XEXP (XEXP (pattern, 0), 0)))
2917     return 1;
2918
2919   return 0;
2920 }
2921
2922 /* Given a X, a pattern of an insn or a part of it, return a mask of used
2923    general registers.  Bits 0..15 mean that the respective registers
2924    are used as inputs in the instruction.  Bits 16..31 mean that the
2925    registers 0..15, respectively, are used as outputs, or are clobbered.
2926    IS_DEST should be set to 16 if X is the destination of a SET, else to 0.  */
2927 int
2928 regs_used (x, is_dest)
2929      rtx x; int is_dest;
2930 {
2931   enum rtx_code code;
2932   const char *fmt;
2933   int i, used = 0;
2934
2935   if (! x)
2936     return used;
2937   code = GET_CODE (x);
2938   switch (code)
2939     {
2940     case REG:
2941       if (REGNO (x) < 16)
2942         return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
2943                 << (REGNO (x) + is_dest));
2944       return 0;
2945     case SUBREG:
2946       {
2947         rtx y = SUBREG_REG (x);
2948      
2949         if (GET_CODE (y) != REG)
2950           break;
2951         if (REGNO (y) < 16)
2952           return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
2953                   << (REGNO (y) +
2954                       subreg_regno_offset (REGNO (y),
2955                                            GET_MODE (y),
2956                                            SUBREG_BYTE (x),
2957                                            GET_MODE (x)) + is_dest));
2958         return 0;
2959       }
2960     case SET:
2961       return regs_used (SET_SRC (x), 0) | regs_used (SET_DEST (x), 16);
2962     case RETURN:
2963       /* If there was a return value, it must have been indicated with USE.  */
2964       return 0x00ffff00;
2965     case CLOBBER:
2966       is_dest = 1;
2967       break;
2968     case MEM:
2969       is_dest = 0;
2970       break;
2971     case CALL:
2972       used |= 0x00ff00f0;
2973       break;
2974     default:
2975       break;
2976     }
2977
2978   fmt = GET_RTX_FORMAT (code);
2979
2980   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2981     {
2982       if (fmt[i] == 'E')
2983         {
2984           register int j;
2985           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
2986             used |= regs_used (XVECEXP (x, i, j), is_dest);
2987         }
2988       else if (fmt[i] == 'e')
2989         used |= regs_used (XEXP (x, i), is_dest);
2990     }
2991   return used;
2992 }
2993
2994 /* Create an instruction that prevents redirection of a conditional branch
2995    to the destination of the JUMP with address ADDR.
2996    If the branch needs to be implemented as an indirect jump, try to find
2997    a scratch register for it.
2998    If NEED_BLOCK is 0, don't do anything unless we need a scratch register.
2999    If any preceding insn that doesn't fit into a delay slot is good enough,
3000    pass 1.  Pass 2 if a definite blocking insn is needed.
3001    -1 is used internally to avoid deep recursion.
3002    If a blocking instruction is made or recognized, return it.  */
3003    
3004 static rtx
3005 gen_block_redirect (jump, addr, need_block)
3006      rtx jump;
3007      int addr, need_block;
3008 {
3009   int dead = 0;
3010   rtx prev = prev_nonnote_insn (jump);
3011   rtx dest;
3012
3013   /* First, check if we already have an instruction that satisfies our need.  */
3014   if (prev && GET_CODE (prev) == INSN && ! INSN_DELETED_P (prev))
3015     {
3016       if (INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
3017         return prev;
3018       if (GET_CODE (PATTERN (prev)) == USE
3019           || GET_CODE (PATTERN (prev)) == CLOBBER
3020           || get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3021         prev = jump;
3022       else if ((need_block &= ~1) < 0)
3023         return prev;
3024       else if (recog_memoized (prev) == CODE_FOR_block_branch_redirect)
3025         need_block = 0;
3026     }
3027   /* We can't use JUMP_LABEL here because it might be undefined
3028      when not optimizing.  */
3029   dest = XEXP (SET_SRC (PATTERN (jump)), 0);
3030   /* If the branch is out of range, try to find a scratch register for it.  */
3031   if (optimize
3032       && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3033           > 4092 + 4098))
3034     {
3035       rtx scan;
3036       /* Don't look for the stack pointer as a scratch register,
3037          it would cause trouble if an interrupt occurred.  */
3038       unsigned try = 0x7fff, used;
3039       int jump_left = flag_expensive_optimizations + 1;
3040     
3041       /* It is likely that the most recent eligible instruction is wanted for
3042          the delay slot.  Therefore, find out which registers it uses, and
3043          try to avoid using them.  */
3044          
3045       for (scan = jump; (scan = PREV_INSN (scan)); )
3046         {
3047           enum rtx_code code;
3048
3049           if (INSN_DELETED_P (scan))
3050             continue;
3051           code = GET_CODE (scan);
3052           if (code == CODE_LABEL || code == JUMP_INSN)
3053             break;
3054           if (code == INSN
3055               && GET_CODE (PATTERN (scan)) != USE
3056               && GET_CODE (PATTERN (scan)) != CLOBBER
3057               && get_attr_in_delay_slot (scan) == IN_DELAY_SLOT_YES)
3058             {
3059               try &= ~regs_used (PATTERN (scan), 0);
3060               break;
3061             }
3062         }
3063       for (used = dead = 0, scan = JUMP_LABEL (jump);
3064            (scan = NEXT_INSN (scan)); )
3065         {
3066           enum rtx_code code;
3067
3068           if (INSN_DELETED_P (scan))
3069             continue;
3070           code = GET_CODE (scan);
3071           if (GET_RTX_CLASS (code) == 'i')
3072             {
3073               used |= regs_used (PATTERN (scan), 0);
3074               if (code == CALL_INSN)
3075                 used |= regs_used (CALL_INSN_FUNCTION_USAGE (scan), 0);
3076               dead |= (used >> 16) & ~used;
3077               if (dead & try)
3078                 {
3079                   dead &= try;
3080                   break;
3081                 }
3082               if (code == JUMP_INSN)
3083                 {
3084                   if (jump_left-- && simplejump_p (scan))
3085                     scan = JUMP_LABEL (scan);
3086                   else
3087                     break;
3088                 }
3089             }
3090         }
3091       /* Mask out the stack pointer again, in case it was
3092          the only 'free' register we have found.  */
3093       dead &= 0x7fff;
3094     }
3095   /* If the immediate destination is still in range, check for possible
3096      threading with a jump beyond the delay slot insn.
3097      Don't check if we are called recursively; the jump has been or will be
3098      checked in a different invocation then.  */
3099         
3100   else if (optimize && need_block >= 0)
3101     {
3102       rtx next = next_active_insn (next_active_insn (dest));
3103       if (next && GET_CODE (next) == JUMP_INSN
3104           && GET_CODE (PATTERN (next)) == SET
3105           && recog_memoized (next) == CODE_FOR_jump)
3106         {
3107           dest = JUMP_LABEL (next);
3108           if (dest
3109               && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3110                   > 4092 + 4098))
3111             gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), -1);
3112         }
3113     }
3114
3115   if (dead)
3116     {
3117       rtx reg = gen_rtx_REG (SImode, exact_log2 (dead & -dead));
3118
3119       /* It would be nice if we could convert the jump into an indirect
3120          jump / far branch right now, and thus exposing all constituent
3121          instructions to further optimization.  However, reorg uses
3122          simplejump_p to determine if there is an unconditional jump where
3123          it should try to schedule instructions from the target of the
3124          branch; simplejump_p fails for indirect jumps even if they have
3125          a JUMP_LABEL.  */
3126       rtx insn = emit_insn_before (gen_indirect_jump_scratch
3127                                    (reg, GEN_INT (INSN_UID (JUMP_LABEL (jump))))
3128                                    , jump);
3129       INSN_CODE (insn) = CODE_FOR_indirect_jump_scratch;
3130       return insn;
3131     }
3132   else if (need_block)
3133     /* We can't use JUMP_LABEL here because it might be undefined
3134        when not optimizing.  */
3135     return emit_insn_before (gen_block_branch_redirect
3136                       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))))
3137                       , jump);
3138   return prev;
3139 }
3140
3141 #define CONDJUMP_MIN -252
3142 #define CONDJUMP_MAX 262
3143 struct far_branch
3144 {
3145   /* A label (to be placed) in front of the jump
3146      that jumps to our ultimate destination.  */
3147   rtx near_label;
3148   /* Where we are going to insert it if we cannot move the jump any farther,
3149      or the jump itself if we have picked up an existing jump.  */
3150   rtx insert_place;
3151   /* The ultimate destination.  */
3152   rtx far_label;
3153   struct far_branch *prev;
3154   /* If the branch has already been created, its address;
3155      else the address of its first prospective user.  */
3156   int address;
3157 };
3158
3159 static void gen_far_branch PARAMS ((struct far_branch *));
3160 enum mdep_reorg_phase_e mdep_reorg_phase;
3161 static void
3162 gen_far_branch (bp)
3163      struct far_branch *bp;
3164 {
3165   rtx insn = bp->insert_place;
3166   rtx jump;
3167   rtx label = gen_label_rtx ();
3168
3169   emit_label_after (label, insn);
3170   if (bp->far_label)
3171     {
3172       jump = emit_jump_insn_after (gen_jump (bp->far_label), insn);
3173       LABEL_NUSES (bp->far_label)++;
3174     }
3175   else
3176     jump = emit_jump_insn_after (gen_return (), insn);
3177   /* Emit a barrier so that reorg knows that any following instructions
3178      are not reachable via a fall-through path.
3179      But don't do this when not optimizing, since we wouldn't supress the
3180      alignment for the barrier then, and could end up with out-of-range
3181      pc-relative loads.  */
3182   if (optimize)
3183     emit_barrier_after (jump);
3184   emit_label_after (bp->near_label, insn);
3185   JUMP_LABEL (jump) = bp->far_label;
3186   if (! invert_jump (insn, label, 1))
3187     abort ();
3188   /* Prevent reorg from undoing our splits.  */
3189   gen_block_redirect (jump, bp->address += 2, 2);
3190 }
3191
3192 /* Fix up ADDR_DIFF_VECs.  */
3193 void
3194 fixup_addr_diff_vecs (first)
3195      rtx first;
3196 {
3197   rtx insn;
3198
3199   for (insn = first; insn; insn = NEXT_INSN (insn))
3200     {
3201       rtx vec_lab, pat, prev, prevpat, x, braf_label;
3202
3203       if (GET_CODE (insn) != JUMP_INSN
3204           || GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
3205         continue;
3206       pat = PATTERN (insn);
3207       vec_lab = XEXP (XEXP (pat, 0), 0);
3208
3209       /* Search the matching casesi_jump_2.  */
3210       for (prev = vec_lab; ; prev = PREV_INSN (prev))
3211         {
3212           if (GET_CODE (prev) != JUMP_INSN)
3213             continue;
3214           prevpat = PATTERN (prev);
3215           if (GET_CODE (prevpat) != PARALLEL || XVECLEN (prevpat, 0) != 2)
3216             continue;
3217           x = XVECEXP (prevpat, 0, 1);
3218           if (GET_CODE (x) != USE)
3219             continue;
3220           x = XEXP (x, 0);
3221           if (GET_CODE (x) == LABEL_REF && XEXP (x, 0) == vec_lab)
3222             break;
3223         }
3224
3225       /* Emit the reference label of the braf where it belongs, right after
3226          the casesi_jump_2 (i.e. braf).  */
3227       braf_label = XEXP (XEXP (SET_SRC (XVECEXP (prevpat, 0, 0)), 1), 0);
3228       emit_label_after (braf_label, prev);
3229
3230       /* Fix up the ADDR_DIF_VEC to be relative
3231          to the reference address of the braf.  */
3232       XEXP (XEXP (pat, 0), 0) = braf_label;
3233     }
3234 }
3235
3236 /* BARRIER_OR_LABEL is either a BARRIER or a CODE_LABEL immediately following
3237    a barrier.  Return the base 2 logarithm of the desired alignment.  */
3238 int
3239 barrier_align (barrier_or_label)
3240      rtx barrier_or_label;
3241 {
3242   rtx next = next_real_insn (barrier_or_label), pat, prev;
3243   int slot, credit, jump_to_next;
3244  
3245   if (! next)
3246     return 0;
3247
3248   pat = PATTERN (next);
3249
3250   if (GET_CODE (pat) == ADDR_DIFF_VEC)
3251     return 2;
3252
3253   if (GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_ALIGN)
3254     /* This is a barrier in front of a constant table.  */
3255     return 0;
3256
3257   prev = prev_real_insn (barrier_or_label);
3258   if (GET_CODE (PATTERN (prev)) == ADDR_DIFF_VEC)
3259     {
3260       pat = PATTERN (prev);
3261       /* If this is a very small table, we want to keep the alignment after
3262          the table to the minimum for proper code alignment.  */
3263       return ((TARGET_SMALLCODE
3264                || (XVECLEN (pat, 1) * GET_MODE_SIZE (GET_MODE (pat))
3265                    <= (unsigned)1 << (CACHE_LOG - 2)))
3266               ? 1 << TARGET_SHMEDIA : CACHE_LOG);
3267     }
3268
3269   if (TARGET_SMALLCODE)
3270     return 0;
3271
3272   if (! TARGET_SH2 || ! optimize)
3273     return CACHE_LOG;
3274
3275   /* When fixing up pcloads, a constant table might be inserted just before
3276      the basic block that ends with the barrier.  Thus, we can't trust the
3277      instruction lengths before that.  */
3278   if (mdep_reorg_phase > SH_FIXUP_PCLOAD)
3279     {
3280       /* Check if there is an immediately preceding branch to the insn beyond
3281          the barrier.  We must weight the cost of discarding useful information
3282          from the current cache line when executing this branch and there is
3283          an alignment, against that of fetching unneeded insn in front of the
3284          branch target when there is no alignment.  */
3285
3286       /* There are two delay_slot cases to consider.  One is the simple case 
3287          where the preceding branch is to the insn beyond the barrier (simple 
3288          delay slot filling), and the other is where the preceding branch has 
3289          a delay slot that is a duplicate of the insn after the barrier 
3290          (fill_eager_delay_slots) and the branch is to the insn after the insn 
3291          after the barrier.  */
3292
3293       /* PREV is presumed to be the JUMP_INSN for the barrier under
3294          investigation.  Skip to the insn before it.  */
3295       prev = prev_real_insn (prev);
3296
3297       for (slot = 2, credit = (1 << (CACHE_LOG - 2)) + 2;
3298            credit >= 0 && prev && GET_CODE (prev) == INSN;
3299            prev = prev_real_insn (prev))
3300         {
3301           jump_to_next = 0;
3302           if (GET_CODE (PATTERN (prev)) == USE
3303               || GET_CODE (PATTERN (prev)) == CLOBBER)
3304             continue;
3305           if (GET_CODE (PATTERN (prev)) == SEQUENCE)
3306             {
3307               prev = XVECEXP (PATTERN (prev), 0, 1);
3308               if (INSN_UID (prev) == INSN_UID (next)) 
3309                 {
3310                   /* Delay slot was filled with insn at jump target.  */
3311                   jump_to_next = 1;
3312                   continue;
3313                 }
3314             }
3315
3316           if (slot &&
3317               get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3318             slot = 0;
3319           credit -= get_attr_length (prev);
3320         }
3321       if (prev
3322           && GET_CODE (prev) == JUMP_INSN
3323           && JUMP_LABEL (prev))
3324         {
3325           rtx x;
3326           if (jump_to_next
3327               || next_real_insn (JUMP_LABEL (prev)) == next
3328               /* If relax_delay_slots() decides NEXT was redundant
3329                  with some previous instruction, it will have
3330                  redirected PREV's jump to the following insn.  */
3331               || JUMP_LABEL (prev) == next_nonnote_insn (next)
3332               /* There is no upper bound on redundant instructions
3333                  that might have been skipped, but we must not put an
3334                  alignment where none had been before.  */
3335               || (x = (NEXT_INSN (NEXT_INSN (PREV_INSN (prev)))),           
3336                   (INSN_P (x) 
3337                    && (INSN_CODE (x) == CODE_FOR_block_branch_redirect
3338                        || INSN_CODE (x) == CODE_FOR_indirect_jump_scratch))))
3339             {
3340               rtx pat = PATTERN (prev);
3341               if (GET_CODE (pat) == PARALLEL)
3342                 pat = XVECEXP (pat, 0, 0);
3343               if (credit - slot >= (GET_CODE (SET_SRC (pat)) == PC ? 2 : 0))
3344                 return 0;
3345             }
3346         }
3347     }
3348   
3349   return CACHE_LOG;
3350 }
3351
3352 /* If we are inside a phony loop, almost any kind of label can turn up as the
3353    first one in the loop.  Aligning a braf label causes incorrect switch
3354    destination addresses; we can detect braf labels because they are
3355    followed by a BARRIER.
3356    Applying loop alignment to small constant or switch tables is a waste
3357    of space, so we suppress this too.  */
3358 int
3359 sh_loop_align (label)
3360      rtx label;
3361 {
3362   rtx next = label;
3363
3364   do
3365     next = next_nonnote_insn (next);
3366   while (next && GET_CODE (next) == CODE_LABEL);
3367
3368   if (! next
3369       || ! INSN_P (next)
3370       || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC
3371       || recog_memoized (next) == CODE_FOR_consttable_2)
3372     return 0;
3373
3374   if (TARGET_SH5)
3375     return 3;
3376
3377   return 2;
3378 }
3379
3380 /* Exported to toplev.c.
3381
3382    Do a final pass over the function, just before delayed branch
3383    scheduling.  */
3384
3385 void
3386 machine_dependent_reorg (first)
3387      rtx first;
3388 {
3389   rtx insn, mova;
3390   int num_mova;
3391   rtx r0_rtx = gen_rtx_REG (Pmode, 0);
3392   rtx r0_inc_rtx = gen_rtx_POST_INC (Pmode, r0_rtx);
3393
3394   /* We must split call insns before introducing `mova's.  If we're
3395      optimizing, they'll have already been split.  Otherwise, make
3396      sure we don't split them too late.  */
3397   if (! optimize)
3398     split_all_insns_noflow ();
3399
3400   if (TARGET_SHMEDIA)
3401     return;
3402
3403   /* If relaxing, generate pseudo-ops to associate function calls with
3404      the symbols they call.  It does no harm to not generate these
3405      pseudo-ops.  However, when we can generate them, it enables to
3406      linker to potentially relax the jsr to a bsr, and eliminate the
3407      register load and, possibly, the constant pool entry.  */
3408
3409   mdep_reorg_phase = SH_INSERT_USES_LABELS;
3410   if (TARGET_RELAX)
3411     {
3412       /* Remove all REG_LABEL notes.  We want to use them for our own
3413          purposes.  This works because none of the remaining passes
3414          need to look at them.
3415
3416          ??? But it may break in the future.  We should use a machine
3417          dependent REG_NOTE, or some other approach entirely.  */
3418       for (insn = first; insn; insn = NEXT_INSN (insn))
3419         {
3420           if (INSN_P (insn))
3421             {
3422               rtx note;
3423
3424               while ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)) != 0)
3425                 remove_note (insn, note);
3426             }
3427         }
3428
3429       for (insn = first; insn; insn = NEXT_INSN (insn))
3430         {
3431           rtx pattern, reg, link, set, scan, dies, label;
3432           int rescan = 0, foundinsn = 0;
3433
3434           if (GET_CODE (insn) == CALL_INSN)
3435             {
3436               pattern = PATTERN (insn);
3437
3438               if (GET_CODE (pattern) == PARALLEL)
3439                 pattern = XVECEXP (pattern, 0, 0);
3440               if (GET_CODE (pattern) == SET)
3441                 pattern = SET_SRC (pattern);
3442
3443               if (GET_CODE (pattern) != CALL
3444                   || GET_CODE (XEXP (pattern, 0)) != MEM)
3445                 continue;
3446
3447               reg = XEXP (XEXP (pattern, 0), 0);
3448             }
3449           else
3450             {
3451               reg = sfunc_uses_reg (insn);
3452               if (! reg)
3453                 continue;
3454             }
3455
3456           if (GET_CODE (reg) != REG)
3457             continue;
3458
3459           /* This is a function call via REG.  If the only uses of REG
3460              between the time that it is set and the time that it dies
3461              are in function calls, then we can associate all the
3462              function calls with the setting of REG.  */
3463
3464           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
3465             {
3466               if (REG_NOTE_KIND (link) != 0)
3467                 continue;
3468               set = single_set (XEXP (link, 0));
3469               if (set && rtx_equal_p (reg, SET_DEST (set)))
3470                 {
3471                   link = XEXP (link, 0);
3472                   break;
3473                 }
3474             }
3475
3476           if (! link)
3477             {
3478               /* ??? Sometimes global register allocation will have
3479                  deleted the insn pointed to by LOG_LINKS.  Try
3480                  scanning backward to find where the register is set.  */
3481               for (scan = PREV_INSN (insn);
3482                    scan && GET_CODE (scan) != CODE_LABEL;
3483                    scan = PREV_INSN (scan))
3484                 {
3485                   if (! INSN_P (scan))
3486                     continue;
3487
3488                   if (! reg_mentioned_p (reg, scan))
3489                     continue;
3490
3491                   if (noncall_uses_reg (reg, scan, &set))
3492                     break;
3493
3494                   if (set)
3495                     {
3496                       link = scan;
3497                       break;
3498                     }
3499                 }
3500             }
3501
3502           if (! link)
3503             continue;
3504
3505           /* The register is set at LINK.  */
3506
3507           /* We can only optimize the function call if the register is
3508              being set to a symbol.  In theory, we could sometimes
3509              optimize calls to a constant location, but the assembler
3510              and linker do not support that at present.  */
3511           if (GET_CODE (SET_SRC (set)) != SYMBOL_REF
3512               && GET_CODE (SET_SRC (set)) != LABEL_REF)
3513             continue;
3514
3515           /* Scan forward from LINK to the place where REG dies, and
3516              make sure that the only insns which use REG are
3517              themselves function calls.  */
3518
3519           /* ??? This doesn't work for call targets that were allocated
3520              by reload, since there may not be a REG_DEAD note for the
3521              register.  */
3522
3523           dies = NULL_RTX;
3524           for (scan = NEXT_INSN (link); scan; scan = NEXT_INSN (scan))
3525             {
3526               rtx scanset;
3527
3528               /* Don't try to trace forward past a CODE_LABEL if we haven't
3529                  seen INSN yet.  Ordinarily, we will only find the setting insn
3530                  in LOG_LINKS if it is in the same basic block.  However,
3531                  cross-jumping can insert code labels in between the load and
3532                  the call, and can result in situations where a single call
3533                  insn may have two targets depending on where we came from.  */
3534
3535               if (GET_CODE (scan) == CODE_LABEL && ! foundinsn)
3536                 break;
3537
3538               if (! INSN_P (scan))
3539                 continue;
3540
3541               /* Don't try to trace forward past a JUMP.  To optimize
3542                  safely, we would have to check that all the
3543                  instructions at the jump destination did not use REG.  */
3544
3545               if (GET_CODE (scan) == JUMP_INSN)
3546                 break;
3547
3548               if (! reg_mentioned_p (reg, scan))
3549                 continue;
3550
3551               if (noncall_uses_reg (reg, scan, &scanset))
3552                 break;
3553
3554               if (scan == insn)
3555                 foundinsn = 1;
3556
3557               if (scan != insn
3558                   && (GET_CODE (scan) == CALL_INSN || sfunc_uses_reg (scan)))
3559                 {
3560                   /* There is a function call to this register other
3561                      than the one we are checking.  If we optimize
3562                      this call, we need to rescan again below.  */
3563                   rescan = 1;
3564                 }
3565
3566               /* ??? We shouldn't have to worry about SCANSET here.
3567                  We should just be able to check for a REG_DEAD note
3568                  on a function call.  However, the REG_DEAD notes are
3569                  apparently not dependable around libcalls; c-torture
3570                  execute/920501-2 is a test case.  If SCANSET is set,
3571                  then this insn sets the register, so it must have
3572                  died earlier.  Unfortunately, this will only handle
3573                  the cases in which the register is, in fact, set in a
3574                  later insn.  */
3575
3576               /* ??? We shouldn't have to use FOUNDINSN here.
3577                  However, the LOG_LINKS fields are apparently not
3578                  entirely reliable around libcalls;
3579                  newlib/libm/math/e_pow.c is a test case.  Sometimes
3580                  an insn will appear in LOG_LINKS even though it is
3581                  not the most recent insn which sets the register.  */
3582
3583               if (foundinsn
3584                   && (scanset
3585                       || find_reg_note (scan, REG_DEAD, reg)))
3586                 {
3587                   dies = scan;
3588                   break;
3589                 }
3590             }
3591
3592           if (! dies)
3593             {
3594               /* Either there was a branch, or some insn used REG
3595                  other than as a function call address.  */
3596               continue;
3597             }
3598
3599           /* Create a code label, and put it in a REG_LABEL note on
3600              the insn which sets the register, and on each call insn
3601              which uses the register.  In final_prescan_insn we look
3602              for the REG_LABEL notes, and output the appropriate label
3603              or pseudo-op.  */
3604
3605           label = gen_label_rtx ();
3606           REG_NOTES (link) = gen_rtx_INSN_LIST (REG_LABEL, label,
3607                                                 REG_NOTES (link));
3608           REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, label,
3609                                                 REG_NOTES (insn));
3610           if (rescan)
3611             {
3612               scan = link;
3613               do
3614                 {
3615                   rtx reg2;
3616
3617                   scan = NEXT_INSN (scan);
3618                   if (scan != insn
3619                       && ((GET_CODE (scan) == CALL_INSN
3620                            && reg_mentioned_p (reg, scan))
3621                           || ((reg2 = sfunc_uses_reg (scan))
3622                               && REGNO (reg2) == REGNO (reg))))
3623                     REG_NOTES (scan)
3624                       = gen_rtx_INSN_LIST (REG_LABEL, label, REG_NOTES (scan));
3625                 }
3626               while (scan != dies);
3627             }
3628         }
3629     }
3630
3631   if (TARGET_SH2)
3632     fixup_addr_diff_vecs (first);
3633
3634   if (optimize)
3635     {
3636       mdep_reorg_phase = SH_SHORTEN_BRANCHES0;
3637       shorten_branches (first);
3638     }
3639   /* Scan the function looking for move instructions which have to be
3640      changed to pc-relative loads and insert the literal tables.  */
3641
3642   mdep_reorg_phase = SH_FIXUP_PCLOAD;
3643   for (insn = first, num_mova = 0; insn; insn = NEXT_INSN (insn))
3644     {
3645       if (mova_p (insn))
3646         {
3647           if (! num_mova++)
3648             mova = insn;
3649         }
3650       else if (GET_CODE (insn) == JUMP_INSN
3651                && GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
3652                && num_mova)
3653         {
3654           rtx scan;
3655           int total;
3656
3657           num_mova--;
3658
3659           /* Some code might have been inserted between the mova and
3660              its ADDR_DIFF_VEC.  Check if the mova is still in range.  */
3661           for (scan = mova, total = 0; scan != insn; scan = NEXT_INSN (scan))
3662             total += get_attr_length (scan);
3663
3664           /* range of mova is 1020, add 4 because pc counts from address of
3665              second instruction after this one, subtract 2 in case pc is 2
3666              byte aligned.  Possible alignment needed for the ADDR_DIFF_VEC
3667              cancels out with alignment effects of the mova itself.  */
3668           if (total > 1022)
3669             {
3670               /* Change the mova into a load, and restart scanning
3671                  there.  broken_move will then return true for mova.  */
3672               SET_SRC (PATTERN (mova))
3673                 = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
3674               INSN_CODE (mova) = -1;
3675               insn = mova;
3676             }
3677         }
3678       if (broken_move (insn))
3679         {
3680           rtx scan;
3681           /* Scan ahead looking for a barrier to stick the constant table
3682              behind.  */
3683           rtx barrier = find_barrier (num_mova, mova, insn);
3684           rtx last_float_move, last_float = 0, *last_float_addr;
3685           int may_need_align = 1;
3686
3687           if (num_mova && ! mova_p (mova))
3688             {
3689               /* find_barrier had to change the first mova into a
3690                  pcload; thus, we have to start with this new pcload.  */
3691               insn = mova;
3692               num_mova = 0;
3693             }
3694           /* Now find all the moves between the points and modify them.  */
3695           for (scan = insn; scan != barrier; scan = NEXT_INSN (scan))
3696             {
3697               if (GET_CODE (scan) == CODE_LABEL)
3698                 last_float = 0;
3699               if (broken_move (scan))
3700                 {
3701                   rtx *patp = &PATTERN (scan), pat = *patp;
3702                   rtx src, dst;
3703                   rtx lab;
3704                   rtx newsrc;
3705                   enum machine_mode mode;
3706
3707                   if (GET_CODE (pat) == PARALLEL)
3708                     patp = &XVECEXP (pat, 0, 0), pat = *patp;
3709                   src = SET_SRC (pat);
3710                   dst = SET_DEST (pat);
3711                   mode = GET_MODE (dst);
3712
3713                   if (mode == SImode && hi_const (src)
3714                       && REGNO (dst) != FPUL_REG)
3715                     {
3716                       int offset = 0;
3717
3718                       mode = HImode;
3719                       while (GET_CODE (dst) == SUBREG)
3720                         {
3721                           offset += subreg_regno_offset (REGNO (SUBREG_REG (dst)),
3722                                                          GET_MODE (SUBREG_REG (dst)),
3723                                                          SUBREG_BYTE (dst),
3724                                                          GET_MODE (dst));
3725                           dst = SUBREG_REG (dst);
3726                         }
3727                       dst = gen_rtx_REG (HImode, REGNO (dst) + offset);
3728                     }
3729
3730                   if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
3731                     {
3732                       /* This must be an insn that clobbers r0.  */
3733                       rtx clobber = XVECEXP (PATTERN (scan), 0,
3734                                              XVECLEN (PATTERN (scan), 0) - 1);
3735
3736                       if (GET_CODE (clobber) != CLOBBER
3737                           || ! rtx_equal_p (XEXP (clobber, 0), r0_rtx))
3738                         abort ();
3739
3740                       if (last_float
3741                           && reg_set_between_p (r0_rtx, last_float_move, scan))
3742                         last_float = 0;
3743                       if (TARGET_SHCOMPACT)
3744                         {
3745                           /* The first SFmode constant after a DFmode
3746                              constant may be pulled before a sequence
3747                              of DFmode constants, so the second SFmode
3748                              needs a label, just in case.  */
3749                           if (GET_MODE_SIZE (mode) == 4)
3750                             {
3751                               if (last_float && may_need_align)
3752                                 last_float = 0;
3753                               may_need_align = 0;
3754                             }
3755                           if (last_float
3756                               && (GET_MODE_SIZE (GET_MODE (last_float))
3757                                   != GET_MODE_SIZE (mode)))
3758                             {
3759                               last_float = 0;
3760                               if (GET_MODE_SIZE (mode) == 4)
3761                                 may_need_align = 1;
3762                             }
3763                         }
3764                       lab = add_constant (src, mode, last_float);
3765                       if (lab)
3766                         emit_insn_before (gen_mova (lab), scan);
3767                       else
3768                         {
3769                           /* There will be a REG_UNUSED note for r0 on
3770                              LAST_FLOAT_MOVE; we have to change it to REG_INC,
3771                              lest reorg:mark_target_live_regs will not
3772                              consider r0 to be used, and we end up with delay
3773                              slot insn in front of SCAN that clobbers r0.  */
3774                           rtx note
3775                             = find_regno_note (last_float_move, REG_UNUSED, 0);
3776
3777                           /* If we are not optimizing, then there may not be
3778                              a note.  */
3779                           if (note)
3780                             PUT_MODE (note, REG_INC);
3781
3782                           *last_float_addr = r0_inc_rtx;
3783                         }
3784                       last_float_move = scan;
3785                       last_float = src;
3786                       newsrc = gen_rtx (MEM, mode,
3787                                         (((TARGET_SH4 && ! TARGET_FMOVD)
3788                                           || REGNO (dst) == FPUL_REG)
3789                                          ? r0_inc_rtx
3790                                          : r0_rtx));
3791                       last_float_addr = &XEXP (newsrc, 0);
3792
3793                       /* Remove the clobber of r0.  */
3794                       XEXP (clobber, 0) = gen_rtx_SCRATCH (Pmode);
3795                     }
3796                   /* This is a mova needing a label.  Create it.  */
3797                   else if (GET_CODE (src) == UNSPEC
3798                            && XINT (src, 1) == UNSPEC_MOVA
3799                            && GET_CODE (XVECEXP (src, 0, 0)) == CONST)
3800                     {
3801                       lab = add_constant (XVECEXP (src, 0, 0), mode, 0);
3802                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
3803                       newsrc = gen_rtx_UNSPEC (VOIDmode,
3804                                                gen_rtvec (1, newsrc),
3805                                                UNSPEC_MOVA);
3806                     }
3807                   else
3808                     {
3809                       lab = add_constant (src, mode, 0);
3810                       newsrc = gen_rtx_MEM (mode,
3811                                             gen_rtx_LABEL_REF (VOIDmode, lab));
3812                     }
3813                   RTX_UNCHANGING_P (newsrc) = 1;
3814                   *patp = gen_rtx_SET (VOIDmode, dst, newsrc);
3815                   INSN_CODE (scan) = -1;
3816                 }
3817             }
3818           dump_table (barrier);
3819           insn = barrier;
3820         }
3821     }
3822
3823   mdep_reorg_phase = SH_SHORTEN_BRANCHES1;
3824   INSN_ADDRESSES_FREE ();
3825   split_branches (first);
3826
3827   /* The INSN_REFERENCES_ARE_DELAYED in sh.h is problematic because it
3828      also has an effect on the register that holds the addres of the sfunc.
3829      Insert an extra dummy insn in front of each sfunc that pretends to
3830      use this register.  */
3831   if (flag_delayed_branch)
3832     {
3833       for (insn = first; insn; insn = NEXT_INSN (insn))
3834         {
3835           rtx reg = sfunc_uses_reg (insn);
3836
3837           if (! reg)
3838             continue;
3839           emit_insn_before (gen_use_sfunc_addr (reg), insn);
3840         }
3841     }
3842 #if 0
3843   /* fpscr is not actually a user variable, but we pretend it is for the
3844      sake of the previous optimization passes, since we want it handled like
3845      one.  However, we don't have any debugging information for it, so turn
3846      it into a non-user variable now.  */
3847   if (TARGET_SH4)
3848     REG_USERVAR_P (get_fpscr_rtx ()) = 0;
3849 #endif
3850   mdep_reorg_phase = SH_AFTER_MDEP_REORG;
3851 }
3852
3853 int
3854 get_dest_uid (label, max_uid)
3855      rtx label;
3856      int max_uid;
3857 {
3858   rtx dest = next_real_insn (label);
3859   int dest_uid;
3860   if (! dest)
3861     /* This can happen for an undefined label.  */
3862     return 0;
3863   dest_uid = INSN_UID (dest);
3864   /* If this is a newly created branch redirection blocking instruction,
3865      we cannot index the branch_uid or insn_addresses arrays with its
3866      uid.  But then, we won't need to, because the actual destination is
3867      the following branch.  */
3868   while (dest_uid >= max_uid)
3869     {
3870       dest = NEXT_INSN (dest);
3871       dest_uid = INSN_UID (dest);
3872     }
3873   if (GET_CODE (dest) == JUMP_INSN && GET_CODE (PATTERN (dest)) == RETURN)
3874     return 0;
3875   return dest_uid;
3876 }
3877
3878 /* Split condbranches that are out of range.  Also add clobbers for
3879    scratch registers that are needed in far jumps.
3880    We do this before delay slot scheduling, so that it can take our
3881    newly created instructions into account.  It also allows us to
3882    find branches with common targets more easily.  */
3883
3884 static void
3885 split_branches (first)
3886      rtx first;
3887 {
3888   rtx insn;
3889   struct far_branch **uid_branch, *far_branch_list = 0;
3890   int max_uid = get_max_uid ();
3891
3892   /* Find out which branches are out of range.  */
3893   shorten_branches (first);
3894
3895   uid_branch = (struct far_branch **) alloca (max_uid * sizeof *uid_branch);
3896   memset ((char *) uid_branch, 0, max_uid * sizeof *uid_branch);
3897
3898   for (insn = first; insn; insn = NEXT_INSN (insn))
3899     if (! INSN_P (insn))
3900       continue;
3901     else if (INSN_DELETED_P (insn))
3902       {
3903         /* Shorten_branches would split this instruction again,
3904            so transform it into a note.  */
3905         PUT_CODE (insn, NOTE);
3906         NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
3907         NOTE_SOURCE_FILE (insn) = 0;
3908       }
3909     else if (GET_CODE (insn) == JUMP_INSN
3910              /* Don't mess with ADDR_DIFF_VEC */
3911              && (GET_CODE (PATTERN (insn)) == SET
3912                  || GET_CODE (PATTERN (insn)) == RETURN))
3913       {
3914         enum attr_type type = get_attr_type (insn);
3915         if (type == TYPE_CBRANCH)
3916           {
3917             rtx next, beyond;
3918     
3919             if (get_attr_length (insn) > 4)
3920               {
3921                 rtx src = SET_SRC (PATTERN (insn));
3922                 rtx olabel = XEXP (XEXP (src, 1), 0);
3923                 int addr = INSN_ADDRESSES (INSN_UID (insn));
3924                 rtx label = 0;
3925                 int dest_uid = get_dest_uid (olabel, max_uid);
3926                 struct far_branch *bp = uid_branch[dest_uid];
3927     
3928                 /* redirect_jump needs a valid JUMP_LABEL, and it might delete
3929                    the label if the LABEL_NUSES count drops to zero.  There is
3930                    always a jump_optimize pass that sets these values, but it
3931                    proceeds to delete unreferenced code, and then if not
3932                    optimizing, to un-delete the deleted instructions, thus
3933                    leaving labels with too low uses counts.  */
3934                 if (! optimize)
3935                   {
3936                     JUMP_LABEL (insn) = olabel;
3937                     LABEL_NUSES (olabel)++;
3938                   }
3939                 if (! bp)
3940                   {
3941                     bp = (struct far_branch *) alloca (sizeof *bp);
3942                     uid_branch[dest_uid] = bp;
3943                     bp->prev = far_branch_list;
3944                     far_branch_list = bp;
3945                     bp->far_label
3946                       = XEXP (XEXP (SET_SRC (PATTERN (insn)), 1), 0);
3947                     LABEL_NUSES (bp->far_label)++;
3948                   }
3949                 else
3950                   {
3951                     label = bp->near_label;
3952                     if (! label && bp->address - addr >= CONDJUMP_MIN)
3953                       {
3954                         rtx block = bp->insert_place;
3955
3956                         if (GET_CODE (PATTERN (block)) == RETURN)
3957                           block = PREV_INSN (block);
3958                         else
3959                           block = gen_block_redirect (block,
3960                                                       bp->address, 2);
3961                         label = emit_label_after (gen_label_rtx (),
3962                                                   PREV_INSN (block));
3963                         bp->near_label = label;
3964                       }
3965                     else if (label && ! NEXT_INSN (label))
3966                       {
3967                         if (addr + 2 - bp->address <= CONDJUMP_MAX)
3968                           bp->insert_place = insn;
3969                         else
3970                           gen_far_branch (bp);
3971                       }
3972                   }
3973                 if (! label
3974                     || (NEXT_INSN (label) && bp->address - addr < CONDJUMP_MIN))
3975                   {
3976                     bp->near_label = label = gen_label_rtx ();
3977                     bp->insert_place = insn;
3978                     bp->address = addr;
3979                   }
3980                 if (! redirect_jump (insn, label, 1))
3981                   abort ();
3982               }
3983             else
3984               {
3985                 /* get_attr_length (insn) == 2 */
3986                 /* Check if we have a pattern where reorg wants to redirect
3987                    the branch to a label from an unconditional branch that
3988                    is too far away.  */
3989                 /* We can't use JUMP_LABEL here because it might be undefined
3990                    when not optimizing.  */
3991                 /* A syntax error might cause beyond to be NULL_RTX.  */
3992                 beyond
3993                   = next_active_insn (XEXP (XEXP (SET_SRC (PATTERN (insn)), 1),
3994                                             0));
3995         
3996                 if (beyond
3997                     && (GET_CODE (beyond) == JUMP_INSN
3998                         || ((beyond = next_active_insn (beyond))
3999                             && GET_CODE (beyond) == JUMP_INSN))
4000                     && GET_CODE (PATTERN (beyond)) == SET
4001                     && recog_memoized (beyond) == CODE_FOR_jump
4002                     && ((INSN_ADDRESSES
4003                          (INSN_UID (XEXP (SET_SRC (PATTERN (beyond)), 0)))
4004                          - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4005                         > 252 + 258 + 2))
4006                   gen_block_redirect (beyond,
4007                                       INSN_ADDRESSES (INSN_UID (beyond)), 1);
4008               }
4009     
4010             next = next_active_insn (insn);
4011
4012             if ((GET_CODE (next) == JUMP_INSN
4013                  || GET_CODE (next = next_active_insn (next)) == JUMP_INSN)
4014                 && GET_CODE (PATTERN (next)) == SET
4015                 && recog_memoized (next) == CODE_FOR_jump
4016                 && ((INSN_ADDRESSES
4017                      (INSN_UID (XEXP (SET_SRC (PATTERN (next)), 0)))
4018                      - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4019                     > 252 + 258 + 2))
4020               gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), 1);
4021           }
4022         else if (type == TYPE_JUMP || type == TYPE_RETURN)
4023           {
4024             int addr = INSN_ADDRESSES (INSN_UID (insn));
4025             rtx far_label = 0;
4026             int dest_uid = 0;
4027             struct far_branch *bp;
4028
4029             if (type == TYPE_JUMP)
4030               {
4031                 far_label = XEXP (SET_SRC (PATTERN (insn)), 0);
4032                 dest_uid = get_dest_uid (far_label, max_uid);
4033                 if (! dest_uid)
4034                   {
4035                     /* Parse errors can lead to labels outside
4036                       the insn stream.  */
4037                     if (! NEXT_INSN (far_label))
4038                       continue;
4039
4040                     if (! optimize)
4041                       {
4042                         JUMP_LABEL (insn) = far_label;
4043                         LABEL_NUSES (far_label)++;
4044                       }
4045                     redirect_jump (insn, NULL_RTX, 1);
4046                     far_label = 0;
4047                   }
4048               }
4049             bp = uid_branch[dest_uid];
4050             if (! bp)
4051               {
4052                 bp = (struct far_branch *) alloca (sizeof *bp);
4053                 uid_branch[dest_uid] = bp;
4054                 bp->prev = far_branch_list;
4055                 far_branch_list = bp;
4056                 bp->near_label = 0;
4057                 bp->far_label = far_label;
4058                 if (far_label)
4059                   LABEL_NUSES (far_label)++;
4060               }
4061             else if (bp->near_label && ! NEXT_INSN (bp->near_label))
4062               if (addr - bp->address <= CONDJUMP_MAX)
4063                 emit_label_after (bp->near_label, PREV_INSN (insn));
4064               else
4065                 {
4066                   gen_far_branch (bp);
4067                   bp->near_label = 0;
4068                 }
4069             else
4070               bp->near_label = 0;
4071             bp->address = addr;
4072             bp->insert_place = insn;
4073             if (! far_label)
4074               emit_insn_before (gen_block_branch_redirect (const0_rtx), insn);
4075             else
4076               gen_block_redirect (insn, addr, bp->near_label ? 2 : 0);
4077           }
4078       }
4079   /* Generate all pending far branches,
4080      and free our references to the far labels.  */
4081   while (far_branch_list)
4082     {
4083       if (far_branch_list->near_label
4084           && ! NEXT_INSN (far_branch_list->near_label))
4085         gen_far_branch (far_branch_list);
4086       if (optimize
4087           && far_branch_list->far_label
4088           && ! --LABEL_NUSES (far_branch_list->far_label))
4089         delete_insn (far_branch_list->far_label);
4090       far_branch_list = far_branch_list->prev;
4091     }
4092
4093   /* Instruction length information is no longer valid due to the new
4094      instructions that have been generated.  */
4095   init_insn_lengths ();
4096 }
4097
4098 /* Dump out instruction addresses, which is useful for debugging the
4099    constant pool table stuff.
4100
4101    If relaxing, output the label and pseudo-ops used to link together
4102    calls and the instruction which set the registers.  */
4103
4104 /* ??? This is unnecessary, and probably should be deleted.  This makes
4105    the insn_addresses declaration above unnecessary.  */
4106
4107 /* ??? The addresses printed by this routine for insns are nonsense for
4108    insns which are inside of a sequence where none of the inner insns have
4109    variable length.  This is because the second pass of shorten_branches
4110    does not bother to update them.  */
4111
4112 void
4113 final_prescan_insn (insn, opvec, noperands)
4114      rtx insn;
4115      rtx *opvec ATTRIBUTE_UNUSED;
4116      int noperands ATTRIBUTE_UNUSED;
4117 {
4118   if (TARGET_DUMPISIZE)
4119     fprintf (asm_out_file, "\n! at %04x\n", INSN_ADDRESSES (INSN_UID (insn)));
4120
4121   if (TARGET_RELAX)
4122     {
4123       rtx note;
4124
4125       note = find_reg_note (insn, REG_LABEL, NULL_RTX);
4126       if (note)
4127         {
4128           rtx pattern;
4129
4130           pattern = PATTERN (insn);
4131           if (GET_CODE (pattern) == PARALLEL)
4132             pattern = XVECEXP (pattern, 0, 0);
4133           if (GET_CODE (pattern) == CALL
4134               || (GET_CODE (pattern) == SET
4135                   && (GET_CODE (SET_SRC (pattern)) == CALL
4136                       || get_attr_type (insn) == TYPE_SFUNC)))
4137             asm_fprintf (asm_out_file, "\t.uses %LL%d\n",
4138                          CODE_LABEL_NUMBER (XEXP (note, 0)));
4139           else if (GET_CODE (pattern) == SET)
4140             ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, "L",
4141                                        CODE_LABEL_NUMBER (XEXP (note, 0)));
4142           else
4143             abort ();
4144         }
4145     }
4146 }
4147
4148 /* Dump out any constants accumulated in the final pass.  These will
4149    only be labels.  */
4150
4151 const char *
4152 output_jump_label_table ()
4153 {
4154   int i;
4155
4156   if (pool_size)
4157     {
4158       fprintf (asm_out_file, "\t.align 2\n");
4159       for (i = 0; i < pool_size; i++)
4160         {
4161           pool_node *p = &pool_vector[i];
4162
4163           ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, "L",
4164                                      CODE_LABEL_NUMBER (p->label));
4165           output_asm_insn (".long       %O0", &p->value);
4166         }
4167       pool_size = 0;
4168     }
4169
4170   return "";
4171 }
4172 \f
4173 /* A full frame looks like:
4174
4175    arg-5
4176    arg-4
4177    [ if current_function_anonymous_args
4178    arg-3
4179    arg-2
4180    arg-1
4181    arg-0 ]
4182    saved-fp
4183    saved-r10
4184    saved-r11
4185    saved-r12
4186    saved-pr
4187    local-n
4188    ..
4189    local-1
4190    local-0        <- fp points here.  */
4191
4192 /* Number of bytes pushed for anonymous args, used to pass information
4193    between expand_prologue and expand_epilogue.  */
4194
4195 static int extra_push;
4196
4197 /* Adjust the stack by SIZE bytes.  REG holds the rtl of the register
4198   to be adjusted, and TEMP, if nonnegative, holds the register number
4199   of a general register that we may clobber.  */
4200
4201 static void
4202 output_stack_adjust (size, reg, temp)
4203      int size;
4204      rtx reg;
4205      int temp;
4206 {
4207   if (size)
4208     {
4209       HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4210
4211       if (size % align)
4212         abort ();
4213
4214       if (CONST_OK_FOR_ADD (size))
4215         emit_insn (GEN_ADD3 (reg, reg, GEN_INT (size)));
4216       /* Try to do it with two partial adjustments; however, we must make
4217          sure that the stack is properly aligned at all times, in case
4218          an interrupt occurs between the two partial adjustments.  */
4219       else if (CONST_OK_FOR_ADD (size / 2 & -align)
4220                && CONST_OK_FOR_ADD (size - (size / 2 & -align)))
4221         {
4222           emit_insn (GEN_ADD3 (reg, reg, GEN_INT (size / 2 & -align)));
4223           emit_insn (GEN_ADD3 (reg, reg, GEN_INT (size - (size / 2 & -align))));
4224         }
4225       else
4226         {
4227           rtx const_reg;
4228
4229           /* If TEMP is invalid, we could temporarily save a general
4230              register to MACL.  However, there is currently no need
4231              to handle this case, so just abort when we see it.  */
4232           if (temp < 0)
4233             abort ();
4234           const_reg = gen_rtx_REG (GET_MODE (reg), temp);
4235
4236           /* If SIZE is negative, subtract the positive value.
4237              This sometimes allows a constant pool entry to be shared
4238              between prologue and epilogue code.  */
4239           if (size < 0)
4240             {
4241               emit_insn (GEN_MOV (const_reg, GEN_INT (-size)));
4242               emit_insn (GEN_SUB3 (reg, reg, const_reg));
4243             }
4244           else
4245             {
4246               emit_insn (GEN_MOV (const_reg, GEN_INT (size)));
4247               emit_insn (GEN_ADD3 (reg, reg, const_reg));
4248             }
4249         }
4250     }
4251 }
4252
4253 /* Output RTL to push register RN onto the stack.  */
4254
4255 static void
4256 push (rn)
4257      int rn;
4258 {
4259   rtx x;
4260   if (rn == FPUL_REG)
4261     x = gen_push_fpul ();
4262   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4263            && FP_OR_XD_REGISTER_P (rn))
4264     {
4265       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4266         return;
4267       x = gen_push_4 (gen_rtx_REG (DFmode, rn));
4268     }
4269   else if (TARGET_SH3E && FP_REGISTER_P (rn))
4270     x = gen_push_e (gen_rtx_REG (SFmode, rn));
4271   else
4272     x = gen_push (gen_rtx_REG (SImode, rn));
4273
4274   x = emit_insn (x);
4275   REG_NOTES (x)
4276     = gen_rtx_EXPR_LIST (REG_INC,
4277                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4278 }
4279
4280 /* Output RTL to pop register RN from the stack.  */
4281
4282 static void
4283 pop (rn)
4284      int rn;
4285 {
4286   rtx x;
4287   if (rn == FPUL_REG)
4288     x = gen_pop_fpul ();
4289   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4290            && FP_OR_XD_REGISTER_P (rn))
4291     {
4292       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4293         return;
4294       x = gen_pop_4 (gen_rtx_REG (DFmode, rn));
4295     }
4296   else if (TARGET_SH3E && FP_REGISTER_P (rn))
4297     x = gen_pop_e (gen_rtx_REG (SFmode, rn));
4298   else
4299     x = gen_pop (gen_rtx_REG (SImode, rn));
4300     
4301   x = emit_insn (x);
4302   REG_NOTES (x)
4303     = gen_rtx_EXPR_LIST (REG_INC,
4304                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4305 }
4306
4307 /* Generate code to push the regs specified in the mask.  */
4308
4309 static void
4310 push_regs (mask)
4311      HOST_WIDE_INT *mask;
4312 {
4313   int i;
4314
4315   /* Push PR last; this gives better latencies after the prologue, and
4316      candidates for the return delay slot when there are no general
4317      registers pushed.  */
4318   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4319     if (i != PR_REG && mask[i / 32] & (1 << (i % 32)))
4320       push (i);
4321   if (mask[PR_REG / 32] & (1 << (PR_REG % 32)))
4322     push (PR_REG);
4323 }
4324
4325 /* Work out the registers which need to be saved, both as a mask and a
4326    count of saved words.
4327
4328    If doing a pragma interrupt function, then push all regs used by the
4329    function, and if we call another function (we can tell by looking at PR),
4330    make sure that all the regs it clobbers are safe too.  */
4331
4332 static void
4333 calc_live_regs (count_ptr, live_regs_mask)
4334      int *count_ptr;
4335      HOST_WIDE_INT *live_regs_mask;
4336 {
4337   int reg;
4338   int count;
4339   int interrupt_handler;
4340   rtx pr_initial;
4341   int pr_live;
4342
4343   if ((lookup_attribute
4344        ("interrupt_handler",
4345         DECL_ATTRIBUTES (current_function_decl)))
4346       != NULL_TREE)
4347     interrupt_handler = 1;
4348   else
4349     interrupt_handler = 0;
4350
4351   for (count = 0; 32 * count < FIRST_PSEUDO_REGISTER; count++)
4352     live_regs_mask[count] = 0;
4353   /* If we can save a lot of saves by switching to double mode, do that.  */
4354   if (TARGET_SH4 && TARGET_FMOVD && TARGET_FPU_SINGLE)
4355     for (count = 0, reg = FIRST_FP_REG; reg <= LAST_FP_REG; reg += 2)
4356       if (regs_ever_live[reg] && regs_ever_live[reg+1]
4357           && (! call_used_regs[reg] || (interrupt_handler && ! pragma_trapa))
4358           && ++count > 2)
4359         {
4360           target_flags &= ~FPU_SINGLE_BIT;
4361           break;
4362         }
4363   pr_initial = has_hard_reg_initial_val (Pmode,
4364                                          TARGET_SHMEDIA
4365                                          ? PR_MEDIA_REG : PR_REG);
4366   pr_live = (pr_initial
4367              ? REGNO (pr_initial) != (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
4368              : regs_ever_live[TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG]);
4369   /* Force PR to be live if the prologue has to call the SHmedia
4370      argument decoder or register saver.  */
4371   if (TARGET_SHCOMPACT
4372       && ((current_function_args_info.call_cookie
4373            & ~ CALL_COOKIE_RET_TRAMP (1))
4374           || current_function_has_nonlocal_label))
4375     pr_live = 1;
4376   for (count = 0, reg = FIRST_PSEUDO_REGISTER - 1; reg >= 0; reg--)
4377     {
4378       if (reg == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
4379           ? pr_live
4380           : (interrupt_handler && ! pragma_trapa)
4381           ? (/* Need to save all the regs ever live.  */
4382              (regs_ever_live[reg]
4383               || (call_used_regs[reg]
4384                   && (! fixed_regs[reg] || reg == MACH_REG || reg == MACL_REG)
4385                   && pr_live))
4386              && reg != STACK_POINTER_REGNUM && reg != ARG_POINTER_REGNUM
4387              && reg != RETURN_ADDRESS_POINTER_REGNUM
4388              && reg != T_REG && reg != GBR_REG && reg != FPSCR_REG)
4389           : (/* Only push those regs which are used and need to be saved.  */
4390              regs_ever_live[reg] && ! call_used_regs[reg]))
4391         {
4392           live_regs_mask[reg / 32] |= 1 << (reg % 32);
4393           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
4394
4395           if ((TARGET_SH4 || TARGET_SH5) && TARGET_FMOVD
4396               && GET_MODE_CLASS (REGISTER_NATURAL_MODE (reg)) == MODE_FLOAT)
4397             {
4398               if (FP_REGISTER_P (reg))
4399                 {
4400                   if (! TARGET_FPU_SINGLE && ! regs_ever_live[reg ^ 1])
4401                     {
4402                       live_regs_mask[(reg ^ 1) / 32] |= 1 << ((reg ^ 1) % 32);
4403                       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg ^ 1));
4404                     }
4405                 }
4406               else if (XD_REGISTER_P (reg))
4407                 {
4408                   /* Must switch to double mode to access these registers.  */
4409                   target_flags &= ~FPU_SINGLE_BIT;
4410                 }
4411             }
4412         }
4413     }
4414
4415   *count_ptr = count;
4416 }
4417
4418 /* Code to generate prologue and epilogue sequences */
4419
4420 /* PUSHED is the number of bytes that are bing pushed on the
4421    stack for register saves.  Return the frame size, padded
4422    appropriately so that the stack stays properly aligned.  */
4423 static HOST_WIDE_INT
4424 rounded_frame_size (pushed)
4425      int pushed;
4426 {
4427   HOST_WIDE_INT size = get_frame_size ();
4428   HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4429
4430   return ((size + pushed + align - 1) & -align) - pushed;
4431 }
4432
4433 /* Choose a call-clobbered target-branch register that remains
4434    unchanged along the whole function.  We set it up as the return
4435    value in the prologue.  */
4436 int
4437 sh_media_register_for_return ()
4438 {
4439   int regno;
4440   int tr0_used;
4441
4442   if (! current_function_is_leaf)
4443     return -1;
4444
4445   tr0_used = flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM];
4446
4447   for (regno = FIRST_TARGET_REG + tr0_used; regno <= LAST_TARGET_REG; regno++)
4448     if (call_used_regs[regno] && ! regs_ever_live[regno])
4449       return regno;
4450
4451   return -1;
4452 }
4453
4454 void
4455 sh_expand_prologue ()
4456 {
4457   HOST_WIDE_INT live_regs_mask[(FIRST_PSEUDO_REGISTER + 31) / 32];
4458   int d, i;
4459   int d_rounding = 0;
4460   int save_flags = target_flags;
4461
4462   current_function_interrupt
4463     = lookup_attribute ("interrupt_handler",
4464                         DECL_ATTRIBUTES (current_function_decl))
4465     != NULL_TREE;
4466
4467   /* We have pretend args if we had an object sent partially in registers
4468      and partially on the stack, e.g. a large structure.  */
4469   output_stack_adjust (-current_function_pretend_args_size
4470                        - current_function_args_info.stack_regs * 8,
4471                        stack_pointer_rtx, TARGET_SH5 ? 0 : 1);
4472
4473   extra_push = 0;
4474
4475   if (TARGET_SHCOMPACT && flag_pic && current_function_args_info.call_cookie)
4476     /* We're going to use the PIC register to load the address of the
4477        incoming-argument decoder and/or of the return trampoline from
4478        the GOT, so make sure the PIC register is preserved and
4479        initialized.  */
4480     regs_ever_live[PIC_OFFSET_TABLE_REGNUM] = 1;
4481
4482   if (TARGET_SHCOMPACT
4483       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
4484     {
4485       int reg;
4486
4487       /* First, make all registers with incoming arguments that will
4488          be pushed onto the stack live, so that register renaming
4489          doesn't overwrite them.  */
4490       for (reg = 0; reg < NPARM_REGS (SImode); reg++)
4491         if (CALL_COOKIE_STACKSEQ_GET (current_function_args_info.call_cookie)
4492             >= NPARM_REGS (SImode) - reg)
4493           for (; reg < NPARM_REGS (SImode); reg++)
4494             emit_insn (gen_shcompact_preserve_incoming_args
4495                        (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
4496         else if (CALL_COOKIE_INT_REG_GET
4497                  (current_function_args_info.call_cookie, reg) == 1)
4498           emit_insn (gen_shcompact_preserve_incoming_args
4499                      (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
4500
4501       emit_move_insn (gen_rtx_REG (Pmode, MACL_REG),
4502                       stack_pointer_rtx);
4503       emit_move_insn (gen_rtx_REG (SImode, R0_REG),
4504                       GEN_INT (current_function_args_info.call_cookie));
4505       emit_move_insn (gen_rtx_REG (SImode, MACH_REG),
4506                       gen_rtx_REG (SImode, R0_REG));
4507     }
4508   else if (TARGET_SHMEDIA)
4509     {
4510       int tr = sh_media_register_for_return ();
4511
4512       if (tr >= 0)
4513         {
4514           rtx insn = emit_move_insn (gen_rtx_REG (DImode, tr),
4515                                      gen_rtx_REG (DImode, PR_MEDIA_REG));
4516
4517           /* If this function only exits with sibcalls, this copy
4518              will be flagged as dead.  */
4519           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
4520                                                 const0_rtx,
4521                                                 REG_NOTES (insn));
4522         }
4523     }
4524
4525   /* Emit the code for SETUP_VARARGS.  */
4526   if (current_function_varargs || current_function_stdarg)
4527     {
4528       /* This is not used by the SH3E calling convention  */
4529       if (TARGET_SH1 && ! TARGET_SH3E && ! TARGET_SH5 && ! TARGET_HITACHI)
4530         {
4531           /* Push arg regs as if they'd been provided by caller in stack.  */
4532           for (i = 0; i < NPARM_REGS(SImode); i++)
4533             {
4534               int rn = NPARM_REGS(SImode) + FIRST_PARM_REG - i - 1;
4535               if (i >= (NPARM_REGS(SImode) 
4536                         - current_function_args_info.arg_count[(int) SH_ARG_INT]
4537                         ))
4538                 break;
4539               push (rn);
4540               extra_push += 4;
4541             }
4542         }
4543     }
4544
4545   /* If we're supposed to switch stacks at function entry, do so now.  */
4546   if (sp_switch)
4547     emit_insn (gen_sp_switch_1 ());
4548
4549   calc_live_regs (&d, live_regs_mask);
4550   /* ??? Maybe we could save some switching if we can move a mode switch
4551      that already happens to be at the function start into the prologue.  */
4552   if (target_flags != save_flags)
4553     emit_insn (gen_toggle_sz ());
4554     
4555   if (TARGET_SH5)
4556     {
4557       int i;
4558       int offset;
4559       int align;
4560       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
4561       int offset_in_r0 = -1;
4562       int sp_in_r0 = 0;
4563
4564       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
4565         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
4566                       - d % (STACK_BOUNDARY / BITS_PER_UNIT));
4567
4568       offset = d + d_rounding;
4569       output_stack_adjust (-offset, stack_pointer_rtx, 1);
4570
4571       /* We loop twice: first, we save 8-byte aligned registers in the
4572          higher addresses, that are known to be aligned.  Then, we
4573          proceed to saving 32-bit registers that don't need 8-byte
4574          alignment.  */
4575       for (align = 1; align >= 0; align--)
4576         for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
4577           if (live_regs_mask[i/32] & (1 << (i % 32)))
4578             {
4579               enum machine_mode mode = REGISTER_NATURAL_MODE (i);
4580               int reg = i;
4581               rtx reg_rtx, mem_rtx, pre_dec = NULL_RTX;
4582
4583               if (mode == SFmode && (i % 2) == 1
4584                   && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
4585                   && (live_regs_mask[(i ^ 1) / 32] & (1 << ((i ^ 1) % 32))))
4586                 {
4587                   mode = DFmode;
4588                   i--;
4589                   reg--;
4590                 }
4591                 
4592               /* If we're doing the aligned pass and this is not aligned,
4593                  or we're doing the unaligned pass and this is aligned,
4594                  skip it.  */
4595               if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
4596                    == 0) != align)
4597                 continue;
4598
4599               offset -= GET_MODE_SIZE (mode);
4600
4601               reg_rtx = gen_rtx_REG (mode, reg);
4602
4603               mem_rtx = gen_rtx_MEM (mode,
4604                                      gen_rtx_PLUS (Pmode,
4605                                                    stack_pointer_rtx,
4606                                                    GEN_INT (offset)));
4607
4608               GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_pre_dec);
4609
4610               mem_rtx = NULL_RTX;
4611
4612             try_pre_dec:
4613               do
4614                 if (HAVE_PRE_DECREMENT
4615                     && (offset_in_r0 - offset == GET_MODE_SIZE (mode)
4616                         || mem_rtx == NULL_RTX
4617                         || i == PR_REG || SPECIAL_REGISTER_P (i)))
4618                   {
4619                     pre_dec = gen_rtx_MEM (mode,
4620                                            gen_rtx_PRE_DEC (Pmode, r0));
4621
4622                     GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (pre_dec, 0),
4623                                               pre_dec_ok);
4624
4625                     pre_dec = NULL_RTX;
4626
4627                     break;
4628
4629                   pre_dec_ok:
4630                     mem_rtx = NULL_RTX;
4631                     offset += GET_MODE_SIZE (mode);
4632                   }
4633               while (0);
4634
4635               if (mem_rtx != NULL_RTX)
4636                 goto addr_ok;
4637
4638               if (offset_in_r0 == -1)
4639                 {
4640                   emit_move_insn (r0, GEN_INT (offset));
4641                   offset_in_r0 = offset;
4642                 }
4643               else if (offset != offset_in_r0)
4644                 {
4645                   emit_move_insn (r0,
4646                                   gen_rtx_PLUS
4647                                   (Pmode, r0,
4648                                    GEN_INT (offset - offset_in_r0)));
4649                   offset_in_r0 += offset - offset_in_r0;
4650                 }
4651                                                   
4652               if (pre_dec != NULL_RTX)
4653                 {
4654                   if (! sp_in_r0)
4655                     {
4656                       emit_move_insn (r0,
4657                                       gen_rtx_PLUS
4658                                       (Pmode, r0, stack_pointer_rtx));
4659                       sp_in_r0 = 1;
4660                     }
4661
4662                   offset -= GET_MODE_SIZE (mode);
4663                   offset_in_r0 -= GET_MODE_SIZE (mode);
4664
4665                   mem_rtx = pre_dec;
4666                 }
4667               else if (sp_in_r0)
4668                 mem_rtx = gen_rtx_MEM (mode, r0);
4669               else
4670                 mem_rtx = gen_rtx_MEM (mode,
4671                                        gen_rtx_PLUS (Pmode,
4672                                                      stack_pointer_rtx,
4673                                                      r0));
4674
4675               /* We must not use an r0-based address for target-branch
4676                  registers or for special registers without pre-dec
4677                  memory addresses, since we store their values in r0
4678                  first.  */
4679               if (TARGET_REGISTER_P (i)
4680                   || ((i == PR_REG || SPECIAL_REGISTER_P (i))
4681                       && mem_rtx != pre_dec))
4682                 abort ();
4683
4684             addr_ok:
4685               if (TARGET_REGISTER_P (i)
4686                   || ((i == PR_REG || SPECIAL_REGISTER_P (i))
4687                       && mem_rtx != pre_dec))
4688                 {
4689                   rtx r0mode = gen_rtx_REG (GET_MODE (reg_rtx), R0_REG);
4690
4691                   emit_move_insn (r0mode, reg_rtx);
4692
4693                   offset_in_r0 = -1;
4694                   sp_in_r0 = 0;
4695
4696                   reg_rtx = r0mode;
4697                 }
4698
4699               emit_move_insn (mem_rtx, reg_rtx);
4700             }
4701
4702       if (offset != d_rounding)
4703         abort ();
4704     }
4705   else
4706     push_regs (live_regs_mask);
4707
4708   if (flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM])
4709     {
4710       rtx insn = get_last_insn ();
4711       rtx last = emit_insn (gen_GOTaddr2picreg ());
4712
4713       /* Mark these insns as possibly dead.  Sometimes, flow2 may
4714          delete all uses of the PIC register.  In this case, let it
4715          delete the initialization too.  */
4716       do
4717         {
4718           insn = NEXT_INSN (insn);
4719
4720           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
4721                                                 const0_rtx,
4722                                                 REG_NOTES (insn));
4723         }
4724       while (insn != last);
4725     }
4726
4727   if (SHMEDIA_REGS_STACK_ADJUST ())
4728     {
4729       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
4730                       gen_rtx_SYMBOL_REF (Pmode,
4731                                           TARGET_FPU_ANY
4732                                           ? "__GCC_push_shmedia_regs"
4733                                           : "__GCC_push_shmedia_regs_nofpu"));
4734       /* This must NOT go through the PLT, otherwise mach and macl
4735          may be clobbered.  */
4736       emit_insn (gen_shmedia_save_restore_regs_compact
4737                  (GEN_INT (-SHMEDIA_REGS_STACK_ADJUST ())));
4738     }
4739
4740   if (target_flags != save_flags)
4741     {
4742       rtx insn = emit_insn (gen_toggle_sz ());
4743
4744       /* If we're lucky, a mode switch in the function body will
4745          overwrite fpscr, turning this insn dead.  Tell flow this
4746          insn is ok to delete.  */
4747       REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
4748                                             const0_rtx,
4749                                             REG_NOTES (insn));
4750     }
4751
4752   target_flags = save_flags;
4753
4754   output_stack_adjust (-rounded_frame_size (d) + d_rounding,
4755                        stack_pointer_rtx, TARGET_SH5 ? 0 : 1);
4756
4757   if (frame_pointer_needed)
4758     emit_insn (GEN_MOV (frame_pointer_rtx, stack_pointer_rtx));
4759
4760   if (TARGET_SHCOMPACT
4761       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
4762     {
4763       /* This must NOT go through the PLT, otherwise mach and macl
4764          may be clobbered.  */
4765       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
4766                       gen_rtx_SYMBOL_REF (Pmode,
4767                                           "__GCC_shcompact_incoming_args"));
4768       emit_insn (gen_shcompact_incoming_args ());
4769     }
4770 }
4771
4772 void
4773 sh_expand_epilogue ()
4774 {
4775   HOST_WIDE_INT live_regs_mask[(FIRST_PSEUDO_REGISTER + 31) / 32];
4776   int d, i;
4777   int d_rounding = 0;
4778
4779   int save_flags = target_flags;
4780   int frame_size;
4781
4782   calc_live_regs (&d, live_regs_mask);
4783
4784   if (TARGET_SH5 && d % (STACK_BOUNDARY / BITS_PER_UNIT))
4785     d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
4786                   - d % (STACK_BOUNDARY / BITS_PER_UNIT));
4787
4788   frame_size = rounded_frame_size (d) - d_rounding;
4789
4790   if (frame_pointer_needed)
4791     {
4792       output_stack_adjust (frame_size, frame_pointer_rtx, 7);
4793
4794       /* We must avoid moving the stack pointer adjustment past code
4795          which reads from the local frame, else an interrupt could
4796          occur after the SP adjustment and clobber data in the local
4797          frame.  */
4798       emit_insn (gen_blockage ());
4799       emit_insn (GEN_MOV (stack_pointer_rtx, frame_pointer_rtx));
4800     }
4801   else if (frame_size)
4802     {
4803       /* We must avoid moving the stack pointer adjustment past code
4804          which reads from the local frame, else an interrupt could
4805          occur after the SP adjustment and clobber data in the local
4806          frame.  */
4807       emit_insn (gen_blockage ());
4808       output_stack_adjust (frame_size, stack_pointer_rtx, 7);
4809     }
4810
4811   if (SHMEDIA_REGS_STACK_ADJUST ())
4812     {
4813       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
4814                       gen_rtx_SYMBOL_REF (Pmode,
4815                                           TARGET_FPU_ANY
4816                                           ? "__GCC_pop_shmedia_regs"
4817                                           : "__GCC_pop_shmedia_regs_nofpu"));
4818       /* This must NOT go through the PLT, otherwise mach and macl
4819          may be clobbered.  */
4820       emit_insn (gen_shmedia_save_restore_regs_compact
4821                  (GEN_INT (SHMEDIA_REGS_STACK_ADJUST ())));
4822     }
4823
4824   /* Pop all the registers.  */
4825
4826   if (target_flags != save_flags)
4827     emit_insn (gen_toggle_sz ());
4828   if (TARGET_SH5)
4829     {
4830       int offset = d_rounding;
4831       int offset_in_r0 = -1;
4832       int sp_in_r0 = 0;
4833       int align;
4834       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
4835       
4836       /* We loop twice: first, we save 8-byte aligned registers in the
4837          higher addresses, that are known to be aligned.  Then, we
4838          proceed to saving 32-bit registers that don't need 8-byte
4839          alignment.  */
4840       for (align = 0; align <= 1; align++)
4841         for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4842           if (live_regs_mask[i/32] & (1 << (i % 32)))
4843             {
4844               enum machine_mode mode = REGISTER_NATURAL_MODE (i);
4845               int reg = i;
4846               rtx reg_rtx, mem_rtx, post_inc = NULL_RTX, insn;
4847
4848               if (mode == SFmode && (i % 2) == 0
4849                   && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
4850                   && (live_regs_mask[(i ^ 1) / 32] & (1 << ((i ^ 1) % 32))))
4851                 {
4852                   mode = DFmode;
4853                   i++;
4854                 }
4855
4856               /* If we're doing the aligned pass and this is not aligned,
4857                  or we're doing the unaligned pass and this is aligned,
4858                  skip it.  */
4859               if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
4860                    == 0) != align)
4861                 continue;
4862
4863               reg_rtx = gen_rtx_REG (mode, reg);
4864
4865               mem_rtx = gen_rtx_MEM (mode,
4866                                      gen_rtx_PLUS (Pmode,
4867                                                    stack_pointer_rtx,
4868                                                    GEN_INT (offset)));
4869
4870               GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_post_inc);
4871
4872               mem_rtx = NULL_RTX;
4873
4874             try_post_inc:
4875               do
4876                 if (HAVE_POST_INCREMENT
4877                     && (offset == offset_in_r0
4878                         || (offset + GET_MODE_SIZE (mode) != d + d_rounding
4879                             && mem_rtx == NULL_RTX)
4880                         || i == PR_REG || SPECIAL_REGISTER_P (i)))
4881                   {
4882                     post_inc = gen_rtx_MEM (mode,
4883                                             gen_rtx_POST_INC (Pmode, r0));
4884
4885                     GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (post_inc, 0),
4886                                               post_inc_ok);
4887
4888                     post_inc = NULL_RTX;
4889
4890                     break;
4891                     
4892                   post_inc_ok:
4893                     mem_rtx = NULL_RTX;
4894                   }
4895               while (0);
4896               
4897               if (mem_rtx != NULL_RTX)
4898                 goto addr_ok;
4899
4900               if (offset_in_r0 == -1)
4901                 {
4902                   emit_move_insn (r0, GEN_INT (offset));
4903                   offset_in_r0 = offset;
4904                 }
4905               else if (offset != offset_in_r0)
4906                 {
4907                   emit_move_insn (r0,
4908                                   gen_rtx_PLUS
4909                                   (Pmode, r0,
4910                                    GEN_INT (offset - offset_in_r0)));
4911                   offset_in_r0 += offset - offset_in_r0;
4912                 }
4913                   
4914               if (post_inc != NULL_RTX)
4915                 {
4916                   if (! sp_in_r0)
4917                     {
4918                       emit_move_insn (r0,
4919                                       gen_rtx_PLUS
4920                                       (Pmode, r0, stack_pointer_rtx));
4921                       sp_in_r0 = 1;
4922                     }
4923                   
4924                   mem_rtx = post_inc;
4925
4926                   offset_in_r0 += GET_MODE_SIZE (mode);
4927                 }
4928               else if (sp_in_r0)
4929                 mem_rtx = gen_rtx_MEM (mode, r0);
4930               else
4931                 mem_rtx = gen_rtx_MEM (mode,
4932                                        gen_rtx_PLUS (Pmode,
4933                                                      stack_pointer_rtx,
4934                                                      r0));
4935
4936               if ((i == PR_REG || SPECIAL_REGISTER_P (i))
4937                   && mem_rtx != post_inc)
4938                 abort ();
4939
4940             addr_ok:
4941               if ((i == PR_REG || SPECIAL_REGISTER_P (i))
4942                   && mem_rtx != post_inc)
4943                 {
4944                   insn = emit_move_insn (r0, mem_rtx);
4945                   mem_rtx = r0;
4946                 }
4947               else if (TARGET_REGISTER_P (i))
4948                 {
4949                   rtx r1 = gen_rtx_REG (mode, R1_REG);
4950
4951                   insn = emit_move_insn (r1, mem_rtx);
4952                   mem_rtx = r1;
4953                 }
4954
4955               insn = emit_move_insn (reg_rtx, mem_rtx);
4956
4957               offset += GET_MODE_SIZE (mode);
4958             }
4959
4960       if (offset != d + d_rounding)
4961         abort ();
4962
4963       goto finish;
4964     }
4965   else
4966     d = 0;
4967   if (live_regs_mask[PR_REG / 32] & (1 << (PR_REG % 32)))
4968     pop (PR_REG);
4969   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4970     {
4971       int j = (FIRST_PSEUDO_REGISTER - 1) - i;
4972
4973       if (j != PR_REG && live_regs_mask[j / 32] & (1 << (j % 32)))
4974         pop (j);
4975     }
4976  finish:
4977   if (target_flags != save_flags)
4978     emit_insn (gen_toggle_sz ());
4979   target_flags = save_flags;
4980
4981   output_stack_adjust (extra_push + current_function_pretend_args_size
4982                        + d + d_rounding
4983                        + current_function_args_info.stack_regs * 8,
4984                        stack_pointer_rtx, 7);
4985
4986   /* Switch back to the normal stack if necessary.  */
4987   if (sp_switch)
4988     emit_insn (gen_sp_switch_2 ());
4989
4990   /* Tell flow the insn that pops PR isn't dead.  */
4991   /* PR_REG will never be live in SHmedia mode, and we don't need to
4992      USE PR_MEDIA_REG, since it will be explicitly copied to TR0_REG
4993      by the return pattern.  */
4994   if (live_regs_mask[PR_REG / 32] & (1 << (PR_REG % 32)))
4995     emit_insn (gen_rtx_USE (VOIDmode, gen_rtx_REG (SImode, PR_REG)));
4996 }
4997
4998 static int sh_need_epilogue_known = 0;
4999
5000 int
5001 sh_need_epilogue ()
5002 {
5003   if (! sh_need_epilogue_known)
5004     {
5005       rtx epilogue;
5006
5007       start_sequence ();
5008       sh_expand_epilogue ();
5009       epilogue = gen_sequence ();
5010       end_sequence ();
5011       sh_need_epilogue_known
5012         = (GET_CODE (epilogue) == SEQUENCE && XVECLEN (epilogue, 0) == 0
5013            ? -1 : 1);
5014     }
5015   return sh_need_epilogue_known > 0;
5016 }
5017
5018 /* Clear variables at function end.  */
5019
5020 static void
5021 sh_output_function_epilogue (file, size)
5022      FILE *file ATTRIBUTE_UNUSED;
5023      HOST_WIDE_INT size ATTRIBUTE_UNUSED;
5024 {
5025   trap_exit = pragma_interrupt = pragma_trapa = pragma_nosave_low_regs = 0;
5026   sh_need_epilogue_known = 0;
5027   sp_switch = NULL_RTX;
5028 }
5029
5030 rtx
5031 sh_builtin_saveregs ()
5032 {
5033   /* First unnamed integer register.  */
5034   int first_intreg = current_function_args_info.arg_count[(int) SH_ARG_INT];
5035   /* Number of integer registers we need to save.  */
5036   int n_intregs = MAX (0, NPARM_REGS (SImode) - first_intreg);
5037   /* First unnamed SFmode float reg */
5038   int first_floatreg = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
5039   /* Number of SFmode float regs to save.  */
5040   int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
5041   rtx regbuf, fpregs;
5042   int bufsize, regno;
5043   HOST_WIDE_INT alias_set;
5044
5045   if (TARGET_SH5)
5046     {
5047       if (n_intregs)
5048         {
5049           int pushregs = n_intregs;
5050
5051           while (pushregs < NPARM_REGS (SImode) - 1
5052                  && (CALL_COOKIE_INT_REG_GET
5053                         (current_function_args_info.call_cookie,
5054                          NPARM_REGS (SImode) - pushregs)
5055                      == 1))
5056             {
5057               current_function_args_info.call_cookie
5058                 &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
5059                                           - pushregs, 1);
5060               pushregs++;
5061             }
5062
5063           if (pushregs == NPARM_REGS (SImode))
5064             current_function_args_info.call_cookie
5065               |= (CALL_COOKIE_INT_REG (0, 1)
5066                   | CALL_COOKIE_STACKSEQ (pushregs - 1));
5067           else
5068             current_function_args_info.call_cookie
5069               |= CALL_COOKIE_STACKSEQ (pushregs);
5070
5071           current_function_pretend_args_size += 8 * n_intregs;
5072         }
5073       if (TARGET_SHCOMPACT)
5074         return const0_rtx;
5075     }
5076   
5077   if (! TARGET_SH3E && ! TARGET_SH4 && ! TARGET_SH5)
5078     {
5079       error ("__builtin_saveregs not supported by this subtarget");
5080       return const0_rtx;
5081     }
5082
5083   if (TARGET_SHMEDIA)
5084     n_floatregs = 0;
5085
5086   /* Allocate block of memory for the regs.  */
5087   /* ??? If n_intregs + n_floatregs == 0, should we allocate at least 1 byte?
5088      Or can assign_stack_local accept a 0 SIZE argument?  */
5089   bufsize = (n_intregs * UNITS_PER_WORD) + (n_floatregs * UNITS_PER_WORD);
5090
5091   if (TARGET_SHMEDIA)
5092     regbuf = gen_rtx_MEM (BLKmode,
5093                           gen_rtx_REG (Pmode, ARG_POINTER_REGNUM));
5094   else if (n_floatregs & 1)
5095     {
5096       rtx addr;
5097
5098       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
5099       addr = copy_to_mode_reg (Pmode, XEXP (regbuf, 0));
5100       emit_insn (gen_iorsi3 (addr, addr, GEN_INT (UNITS_PER_WORD)));
5101       regbuf = change_address (regbuf, BLKmode, addr);
5102     }
5103   else
5104     regbuf = assign_stack_local (BLKmode, bufsize, 0);
5105   alias_set = get_varargs_alias_set ();
5106   set_mem_alias_set (regbuf, alias_set);
5107
5108   /* Save int args.
5109      This is optimized to only save the regs that are necessary.  Explicitly
5110      named args need not be saved.  */
5111   if (n_intregs > 0)
5112     move_block_from_reg (BASE_ARG_REG (SImode) + first_intreg,
5113                          adjust_address (regbuf, BLKmode,
5114                                          n_floatregs * UNITS_PER_WORD),
5115                          n_intregs, n_intregs * UNITS_PER_WORD);
5116
5117   if (TARGET_SHMEDIA)
5118     /* Return the address of the regbuf.  */
5119     return XEXP (regbuf, 0);
5120
5121   /* Save float args.
5122      This is optimized to only save the regs that are necessary.  Explicitly
5123      named args need not be saved.
5124      We explicitly build a pointer to the buffer because it halves the insn
5125      count when not optimizing (otherwise the pointer is built for each reg
5126      saved).
5127      We emit the moves in reverse order so that we can use predecrement.  */
5128
5129   fpregs = gen_reg_rtx (Pmode);
5130   emit_move_insn (fpregs, XEXP (regbuf, 0));
5131   emit_insn (gen_addsi3 (fpregs, fpregs,
5132                          GEN_INT (n_floatregs * UNITS_PER_WORD)));
5133   if (TARGET_SH4)
5134     {
5135       rtx mem;
5136       for (regno = NPARM_REGS (DFmode) - 2; regno >= first_floatreg; regno -= 2)
5137         {
5138           emit_insn (gen_addsi3 (fpregs, fpregs,
5139                                  GEN_INT (-2 * UNITS_PER_WORD)));
5140           mem = gen_rtx_MEM (DFmode, fpregs);
5141           set_mem_alias_set (mem, alias_set);
5142           emit_move_insn (mem, 
5143                           gen_rtx (REG, DFmode, BASE_ARG_REG (DFmode) + regno));
5144         }
5145       regno = first_floatreg;
5146       if (regno & 1)
5147         {
5148           emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5149           mem = gen_rtx_MEM (SFmode, fpregs);
5150           set_mem_alias_set (mem, alias_set);
5151           emit_move_insn (mem,
5152                           gen_rtx (REG, SFmode, BASE_ARG_REG (SFmode) + regno
5153                                                 - (TARGET_LITTLE_ENDIAN != 0)));
5154         }
5155     }
5156   else
5157     for (regno = NPARM_REGS (SFmode) - 1; regno >= first_floatreg; regno--)
5158       {
5159         rtx mem;
5160
5161         emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5162         mem = gen_rtx_MEM (SFmode, fpregs);
5163         set_mem_alias_set (mem, alias_set);
5164         emit_move_insn (mem,
5165                         gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno));
5166       }
5167
5168   /* Return the address of the regbuf.  */
5169   return XEXP (regbuf, 0);
5170 }
5171
5172 /* Define the `__builtin_va_list' type for the ABI.  */
5173
5174 tree
5175 sh_build_va_list ()
5176 {
5177   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5178   tree record;
5179
5180   if (TARGET_SH5 || (! TARGET_SH3E && ! TARGET_SH4) || TARGET_HITACHI)
5181     return ptr_type_node;
5182
5183   record = make_node (RECORD_TYPE);
5184
5185   f_next_o = build_decl (FIELD_DECL, get_identifier ("__va_next_o"),
5186                          ptr_type_node);
5187   f_next_o_limit = build_decl (FIELD_DECL,
5188                                get_identifier ("__va_next_o_limit"),
5189                                ptr_type_node);
5190   f_next_fp = build_decl (FIELD_DECL, get_identifier ("__va_next_fp"),
5191                           ptr_type_node);
5192   f_next_fp_limit = build_decl (FIELD_DECL,
5193                                 get_identifier ("__va_next_fp_limit"),
5194                                 ptr_type_node);
5195   f_next_stack = build_decl (FIELD_DECL, get_identifier ("__va_next_stack"),
5196                              ptr_type_node);
5197
5198   DECL_FIELD_CONTEXT (f_next_o) = record;
5199   DECL_FIELD_CONTEXT (f_next_o_limit) = record;
5200   DECL_FIELD_CONTEXT (f_next_fp) = record;
5201   DECL_FIELD_CONTEXT (f_next_fp_limit) = record;
5202   DECL_FIELD_CONTEXT (f_next_stack) = record;
5203
5204   TYPE_FIELDS (record) = f_next_o;
5205   TREE_CHAIN (f_next_o) = f_next_o_limit;
5206   TREE_CHAIN (f_next_o_limit) = f_next_fp;
5207   TREE_CHAIN (f_next_fp) = f_next_fp_limit;
5208   TREE_CHAIN (f_next_fp_limit) = f_next_stack;
5209
5210   layout_type (record);
5211
5212   return record;
5213 }
5214
5215 /* Implement `va_start' for varargs and stdarg.  */
5216
5217 void
5218 sh_va_start (stdarg_p, valist, nextarg)
5219      int stdarg_p;
5220      tree valist;
5221      rtx nextarg;
5222 {
5223   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5224   tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
5225   tree t, u;
5226   int nfp, nint;
5227
5228   if (TARGET_SH5)
5229     {
5230       expand_builtin_saveregs ();
5231       /* When the varargs dummy argument is ``passed'' on a register,
5232          we don't want std_expand_builtin_va_start() to apply any
5233          correction for it, so set stdarg_p so as to pretend there's
5234          no such dummy argument.  */
5235       if (current_function_args_info.arg_count[(int) SH_ARG_INT]
5236           < NPARM_REGS (SImode))
5237         stdarg_p = 1;
5238       std_expand_builtin_va_start (stdarg_p, valist, nextarg);
5239       return;
5240     }
5241
5242   if ((! TARGET_SH3E && ! TARGET_SH4) || TARGET_HITACHI)
5243     {
5244       std_expand_builtin_va_start (stdarg_p, valist, nextarg);
5245       return;
5246     }
5247
5248   f_next_o = TYPE_FIELDS (va_list_type_node);
5249   f_next_o_limit = TREE_CHAIN (f_next_o);
5250   f_next_fp = TREE_CHAIN (f_next_o_limit);
5251   f_next_fp_limit = TREE_CHAIN (f_next_fp);
5252   f_next_stack = TREE_CHAIN (f_next_fp_limit);
5253
5254   next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
5255   next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
5256                         valist, f_next_o_limit);
5257   next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp), valist, f_next_fp);
5258   next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
5259                          valist, f_next_fp_limit);
5260   next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
5261                       valist, f_next_stack);
5262
5263   /* Call __builtin_saveregs.  */
5264   u = make_tree (ptr_type_node, expand_builtin_saveregs ());
5265   t = build (MODIFY_EXPR, ptr_type_node, next_fp, u);
5266   TREE_SIDE_EFFECTS (t) = 1;
5267   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5268
5269   nfp = current_function_args_info.arg_count[SH_ARG_FLOAT];
5270   if (nfp < 8)
5271     nfp = 8 - nfp;
5272   else
5273     nfp = 0;
5274   u = fold (build (PLUS_EXPR, ptr_type_node, u,
5275                    build_int_2 (UNITS_PER_WORD * nfp, 0)));
5276   t = build (MODIFY_EXPR, ptr_type_node, next_fp_limit, u);
5277   TREE_SIDE_EFFECTS (t) = 1;
5278   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5279
5280   t = build (MODIFY_EXPR, ptr_type_node, next_o, u);
5281   TREE_SIDE_EFFECTS (t) = 1;
5282   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5283
5284   nint = current_function_args_info.arg_count[SH_ARG_INT];
5285   if (nint < 4)
5286     nint = 4 - nint;
5287   else
5288     nint = 0;
5289   u = fold (build (PLUS_EXPR, ptr_type_node, u,
5290                    build_int_2 (UNITS_PER_WORD * nint, 0)));
5291   t = build (MODIFY_EXPR, ptr_type_node, next_o_limit, u);
5292   TREE_SIDE_EFFECTS (t) = 1;
5293   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5294
5295   u = make_tree (ptr_type_node, nextarg);
5296   if (! stdarg_p && (nint == 0 || nfp == 0))
5297     {
5298       u = fold (build (PLUS_EXPR, ptr_type_node, u,
5299                        build_int_2 (-UNITS_PER_WORD, -1)));
5300     }
5301   t = build (MODIFY_EXPR, ptr_type_node, next_stack, u);
5302   TREE_SIDE_EFFECTS (t) = 1;
5303   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
5304 }
5305
5306 /* Implement `va_arg'.  */
5307
5308 rtx
5309 sh_va_arg (valist, type)
5310      tree valist, type;
5311 {
5312   HOST_WIDE_INT size, rsize;
5313   tree tmp, pptr_type_node;
5314   rtx addr_rtx, r;
5315   rtx result;
5316   int pass_by_ref = MUST_PASS_IN_STACK (TYPE_MODE (type), type);
5317
5318   size = int_size_in_bytes (type);
5319   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
5320   pptr_type_node = build_pointer_type (ptr_type_node);
5321
5322   if (pass_by_ref)
5323     type = build_pointer_type (type);
5324
5325   if (! TARGET_SH5 && (TARGET_SH3E || TARGET_SH4) && ! TARGET_HITACHI)
5326     {
5327       tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5328       tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
5329       int pass_as_float;
5330       rtx lab_false, lab_over;
5331
5332       f_next_o = TYPE_FIELDS (va_list_type_node);
5333       f_next_o_limit = TREE_CHAIN (f_next_o);
5334       f_next_fp = TREE_CHAIN (f_next_o_limit);
5335       f_next_fp_limit = TREE_CHAIN (f_next_fp);
5336       f_next_stack = TREE_CHAIN (f_next_fp_limit);
5337
5338       next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
5339       next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
5340                             valist, f_next_o_limit);
5341       next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp),
5342                        valist, f_next_fp);
5343       next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
5344                              valist, f_next_fp_limit);
5345       next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
5346                           valist, f_next_stack);
5347
5348       if (TARGET_SH4)
5349         {
5350           pass_as_float = ((TREE_CODE (type) == REAL_TYPE && size <= 8)
5351                            || (TREE_CODE (type) == COMPLEX_TYPE
5352                                && TREE_CODE (TREE_TYPE (type)) == REAL_TYPE
5353                                && size <= 16));
5354         }
5355       else
5356         {
5357           pass_as_float = (TREE_CODE (type) == REAL_TYPE && size == 4);
5358         }
5359
5360       addr_rtx = gen_reg_rtx (Pmode);
5361       lab_false = gen_label_rtx ();
5362       lab_over = gen_label_rtx ();
5363
5364       if (pass_as_float)
5365         {
5366           int first_floatreg
5367             = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
5368           int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
5369
5370           emit_cmp_and_jump_insns (expand_expr (next_fp, NULL_RTX, Pmode,
5371                                                 EXPAND_NORMAL),
5372                                    expand_expr (next_fp_limit, NULL_RTX,
5373                                                 Pmode, EXPAND_NORMAL),
5374                                    GE, const1_rtx, Pmode, 1, lab_false);
5375
5376           if (TYPE_ALIGN (type) > BITS_PER_WORD
5377               || (((TREE_CODE (type) == REAL_TYPE && size == 8) || size == 16)
5378                   && (n_floatregs & 1)))
5379             {
5380               tmp = build (BIT_AND_EXPR, ptr_type_node, next_fp,
5381                            build_int_2 (UNITS_PER_WORD, 0));
5382               tmp = build (PLUS_EXPR, ptr_type_node, next_fp, tmp);
5383               tmp = build (MODIFY_EXPR, ptr_type_node, next_fp, tmp);
5384               TREE_SIDE_EFFECTS (tmp) = 1;
5385               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
5386             }
5387
5388           tmp = build1 (ADDR_EXPR, pptr_type_node, next_fp);
5389           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5390           if (r != addr_rtx)
5391             emit_move_insn (addr_rtx, r);
5392
5393           emit_jump_insn (gen_jump (lab_over));
5394           emit_barrier ();
5395           emit_label (lab_false);
5396
5397           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
5398           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5399           if (r != addr_rtx)
5400             emit_move_insn (addr_rtx, r);
5401         }
5402       else
5403         {
5404           tmp = build (PLUS_EXPR, ptr_type_node, next_o,
5405                        build_int_2 (rsize, 0));
5406           
5407           emit_cmp_and_jump_insns (expand_expr (tmp, NULL_RTX, Pmode,
5408                                                 EXPAND_NORMAL),
5409                                    expand_expr (next_o_limit, NULL_RTX,
5410                                                 Pmode, EXPAND_NORMAL),
5411                                    GT, const1_rtx, Pmode, 1, lab_false);
5412
5413           tmp = build1 (ADDR_EXPR, pptr_type_node, next_o);
5414           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5415           if (r != addr_rtx)
5416             emit_move_insn (addr_rtx, r);
5417
5418           emit_jump_insn (gen_jump (lab_over));
5419           emit_barrier ();
5420           emit_label (lab_false);
5421
5422           if (size > 4 && ! TARGET_SH4)
5423             {
5424               tmp = build (MODIFY_EXPR, ptr_type_node, next_o, next_o_limit);
5425               TREE_SIDE_EFFECTS (tmp) = 1;
5426               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
5427             }
5428
5429           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
5430           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
5431           if (r != addr_rtx)
5432             emit_move_insn (addr_rtx, r);
5433         }
5434
5435       emit_label (lab_over);
5436
5437       tmp = make_tree (pptr_type_node, addr_rtx);
5438       valist = build1 (INDIRECT_REF, ptr_type_node, tmp);
5439     }
5440
5441   /* ??? In va-sh.h, there had been code to make values larger than
5442      size 8 indirect.  This does not match the FUNCTION_ARG macros.  */
5443
5444   result = std_expand_builtin_va_arg (valist, type);
5445   if (pass_by_ref)
5446     {
5447 #ifdef POINTERS_EXTEND_UNSIGNED
5448       if (GET_MODE (addr) != Pmode)
5449         addr = convert_memory_address (Pmode, result);
5450 #endif
5451       result = gen_rtx_MEM (ptr_mode, force_reg (Pmode, result));
5452       set_mem_alias_set (result, get_varargs_alias_set ());
5453     }
5454   /* ??? expand_builtin_va_arg will also set the alias set of the dereferenced
5455      argument to the varargs alias set.  */
5456   return result;
5457 }
5458
5459 /* Define the offset between two registers, one to be eliminated, and
5460    the other its replacement, at the start of a routine.  */
5461
5462 int
5463 initial_elimination_offset (from, to)
5464      int from;
5465      int to;
5466 {
5467   int regs_saved;
5468   int regs_saved_rounding = 0;
5469   int total_saved_regs_space;
5470   int total_auto_space;
5471   int save_flags = target_flags;
5472   int copy_flags;
5473
5474   HOST_WIDE_INT live_regs_mask[(FIRST_PSEUDO_REGISTER + 31) / 32];
5475   calc_live_regs (&regs_saved, live_regs_mask);
5476   regs_saved += SHMEDIA_REGS_STACK_ADJUST ();
5477   if (TARGET_SH5 && regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT))
5478     regs_saved_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5479                            - regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT));
5480
5481   total_auto_space = rounded_frame_size (regs_saved) - regs_saved_rounding;
5482   copy_flags = target_flags;
5483   target_flags = save_flags;
5484
5485   total_saved_regs_space = regs_saved + regs_saved_rounding;
5486
5487   if (from == ARG_POINTER_REGNUM && to == FRAME_POINTER_REGNUM)
5488     return total_saved_regs_space + total_auto_space
5489       + current_function_args_info.byref_regs * 8;
5490
5491   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
5492     return total_saved_regs_space + total_auto_space
5493       + current_function_args_info.byref_regs * 8;
5494
5495   /* Initial gap between fp and sp is 0.  */
5496   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
5497     return 0;
5498
5499   if (from == RETURN_ADDRESS_POINTER_REGNUM
5500       && (to == FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM))
5501       if (TARGET_SH5)
5502         {
5503           int i, n = total_saved_regs_space;
5504           int align;
5505           int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
5506           
5507           n += total_auto_space;
5508
5509           /* If it wasn't saved, there's not much we can do.  */
5510           if ((live_regs_mask[pr_reg / 32] & (1 << (pr_reg % 32))) == 0)
5511             return n;
5512
5513           target_flags = copy_flags;
5514
5515           /* We loop twice: first, check 8-byte aligned registers,
5516              that are stored in the higher addresses, that are known
5517              to be aligned.  Then, check 32-bit registers that don't
5518              need 8-byte alignment.  */
5519           for (align = 1; align >= 0; align--)
5520             for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
5521               if (live_regs_mask[i/32] & (1 << (i % 32)))
5522                 {
5523                   enum machine_mode mode = REGISTER_NATURAL_MODE (i);
5524
5525                   if (mode == SFmode && (i % 2) == 1
5526                       && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
5527                       && (live_regs_mask[(i ^ 1) / 32]
5528                           & (1 << ((i ^ 1) % 32))))
5529                     {
5530                       mode = DFmode;
5531                       i--;
5532                     }
5533                 
5534                   /* If we're doing the aligned pass and this is not aligned,
5535                      or we're doing the unaligned pass and this is aligned,
5536                      skip it.  */
5537                   if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT)
5538                        == 0) != align)
5539                     continue;
5540
5541                   n -= GET_MODE_SIZE (mode);
5542
5543                   if (i == pr_reg)
5544                     {
5545                       target_flags = save_flags;
5546                       return n;
5547                     }
5548                 }
5549
5550           abort ();
5551         }
5552       else
5553     return total_auto_space;
5554
5555   abort ();
5556 }
5557 \f
5558 /* Handle machine specific pragmas to be semi-compatible with Hitachi
5559    compiler.  */
5560
5561 void
5562 sh_pr_interrupt (pfile)
5563      cpp_reader *pfile ATTRIBUTE_UNUSED;
5564 {
5565   pragma_interrupt = 1;
5566 }
5567
5568 void
5569 sh_pr_trapa (pfile)
5570      cpp_reader *pfile ATTRIBUTE_UNUSED;
5571 {
5572   pragma_interrupt = pragma_trapa = 1;
5573 }
5574
5575 void
5576 sh_pr_nosave_low_regs (pfile)
5577      cpp_reader *pfile ATTRIBUTE_UNUSED;
5578 {
5579   pragma_nosave_low_regs = 1;
5580 }
5581
5582 /* Generate 'handle_interrupt' attribute for decls */
5583
5584 static void
5585 sh_insert_attributes (node, attributes)
5586      tree node;
5587      tree * attributes;
5588 {
5589   if (! pragma_interrupt
5590       || TREE_CODE (node) != FUNCTION_DECL)
5591     return;
5592
5593   /* We are only interested in fields.  */
5594   if (TREE_CODE_CLASS (TREE_CODE (node)) != 'd')
5595     return;
5596
5597   /* Add a 'handle_interrupt' attribute.  */
5598   * attributes = tree_cons (get_identifier ("interrupt_handler"), NULL, * attributes);
5599
5600   return;
5601 }
5602
5603 /* Supported attributes:
5604
5605    interrupt_handler -- specifies this function is an interrupt handler.
5606
5607    sp_switch -- specifies an alternate stack for an interrupt handler
5608    to run on.
5609
5610    trap_exit -- use a trapa to exit an interrupt function instead of
5611    an rte instruction.  */
5612
5613 const struct attribute_spec sh_attribute_table[] =
5614 {
5615   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
5616   { "interrupt_handler", 0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
5617   { "sp_switch",         1, 1, true,  false, false, sh_handle_sp_switch_attribute },
5618   { "trap_exit",         1, 1, true,  false, false, sh_handle_trap_exit_attribute },
5619   { NULL,                0, 0, false, false, false, NULL }
5620 };
5621
5622 /* Handle an "interrupt_handler" attribute; arguments as in
5623    struct attribute_spec.handler.  */
5624 static tree
5625 sh_handle_interrupt_handler_attribute (node, name, args, flags, no_add_attrs)
5626      tree *node;
5627      tree name;
5628      tree args ATTRIBUTE_UNUSED;
5629      int flags ATTRIBUTE_UNUSED;
5630      bool *no_add_attrs;
5631 {
5632   if (TREE_CODE (*node) != FUNCTION_DECL)
5633     {
5634       warning ("`%s' attribute only applies to functions",
5635                IDENTIFIER_POINTER (name));
5636       *no_add_attrs = true;
5637     }
5638
5639   return NULL_TREE;
5640 }
5641
5642 /* Handle an "sp_switch" attribute; arguments as in
5643    struct attribute_spec.handler.  */
5644 static tree
5645 sh_handle_sp_switch_attribute (node, name, args, flags, no_add_attrs)
5646      tree *node;
5647      tree name;
5648      tree args;
5649      int flags ATTRIBUTE_UNUSED;
5650      bool *no_add_attrs;
5651 {
5652   if (TREE_CODE (*node) != FUNCTION_DECL)
5653     {
5654       warning ("`%s' attribute only applies to functions",
5655                IDENTIFIER_POINTER (name));
5656       *no_add_attrs = true;
5657     }
5658   else if (!pragma_interrupt)
5659     {
5660       /* The sp_switch attribute only has meaning for interrupt functions.  */
5661       warning ("`%s' attribute only applies to interrupt functions",
5662                IDENTIFIER_POINTER (name));
5663       *no_add_attrs = true;
5664     }
5665   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
5666     {
5667       /* The argument must be a constant string.  */
5668       warning ("`%s' attribute argument not a string constant",
5669                IDENTIFIER_POINTER (name));
5670       *no_add_attrs = true;
5671     }
5672   else
5673     {
5674       sp_switch = gen_rtx_SYMBOL_REF (VOIDmode,
5675                                       TREE_STRING_POINTER (TREE_VALUE (args)));
5676     }
5677
5678   return NULL_TREE;
5679 }
5680
5681 /* Handle an "trap_exit" attribute; arguments as in
5682    struct attribute_spec.handler.  */
5683 static tree
5684 sh_handle_trap_exit_attribute (node, name, args, flags, no_add_attrs)
5685      tree *node;
5686      tree name;
5687      tree args;
5688      int flags ATTRIBUTE_UNUSED;
5689      bool *no_add_attrs;
5690 {
5691   if (TREE_CODE (*node) != FUNCTION_DECL)
5692     {
5693       warning ("`%s' attribute only applies to functions",
5694                IDENTIFIER_POINTER (name));
5695       *no_add_attrs = true;
5696     }
5697   else if (!pragma_interrupt)
5698     {
5699       /* The trap_exit attribute only has meaning for interrupt functions.  */
5700       warning ("`%s' attribute only applies to interrupt functions",
5701                IDENTIFIER_POINTER (name));
5702       *no_add_attrs = true;
5703     }
5704   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
5705     {
5706       /* The argument must be a constant integer.  */
5707       warning ("`%s' attribute argument not an integer constant",
5708                IDENTIFIER_POINTER (name));
5709       *no_add_attrs = true;
5710     }
5711   else
5712     {
5713       trap_exit = TREE_INT_CST_LOW (TREE_VALUE (args));
5714     }
5715
5716   return NULL_TREE;
5717 }
5718
5719 \f
5720 /* Predicates used by the templates.  */
5721
5722 /* Returns 1 if OP is MACL, MACH or PR.  The input must be a REG rtx.
5723    Used only in general_movsrc_operand.  */
5724
5725 int
5726 system_reg_operand (op, mode)
5727      rtx op;
5728      enum machine_mode mode ATTRIBUTE_UNUSED;
5729 {
5730   switch (REGNO (op))
5731     {
5732     case PR_REG:
5733     case MACL_REG:
5734     case MACH_REG:
5735       return 1;
5736     }
5737   return 0;
5738 }
5739
5740 /* Returns 1 if OP can be source of a simple move operation.
5741    Same as general_operand, but a LABEL_REF is valid, PRE_DEC is
5742    invalid as are subregs of system registers.  */
5743
5744 int
5745 general_movsrc_operand (op, mode)
5746      rtx op;
5747      enum machine_mode mode;
5748 {
5749   if (GET_CODE (op) == MEM)
5750     {
5751       rtx inside = XEXP (op, 0);
5752       if (GET_CODE (inside) == CONST)
5753         inside = XEXP (inside, 0);
5754
5755       if (GET_CODE (inside) == LABEL_REF)
5756         return 1;
5757
5758       if (GET_CODE (inside) == PLUS
5759           && GET_CODE (XEXP (inside, 0)) == LABEL_REF
5760           && GET_CODE (XEXP (inside, 1)) == CONST_INT)
5761         return 1;
5762
5763       /* Only post inc allowed.  */
5764       if (GET_CODE (inside) == PRE_DEC)
5765         return 0;
5766     }
5767
5768   if ((mode == QImode || mode == HImode)
5769       && (GET_CODE (op) == SUBREG
5770           && GET_CODE (XEXP (op, 0)) == REG
5771           && system_reg_operand (XEXP (op, 0), mode)))
5772     return 0;
5773
5774   return general_operand (op, mode);
5775 }
5776
5777 /* Returns 1 if OP can be a destination of a move.
5778    Same as general_operand, but no preinc allowed.  */
5779
5780 int
5781 general_movdst_operand (op, mode)
5782      rtx op;
5783      enum machine_mode mode;
5784 {
5785   /* Only pre dec allowed.  */
5786   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == POST_INC)
5787     return 0;
5788
5789   return general_operand (op, mode);
5790 }
5791
5792 /* Accept a register, but not a subreg of any kind.  This allows us to
5793    avoid pathological cases in reload wrt data movement common in 
5794    int->fp conversion.  */
5795
5796 int
5797 reg_no_subreg_operand (op, mode)
5798      register rtx op;
5799      enum machine_mode mode;
5800 {
5801   if (GET_CODE (op) == SUBREG)
5802     return 0;
5803   return register_operand (op, mode);
5804 }
5805
5806 /* Returns 1 if OP is a normal arithmetic register.  */
5807
5808 int
5809 arith_reg_operand (op, mode)
5810      rtx op;
5811      enum machine_mode mode;
5812 {
5813   if (register_operand (op, mode))
5814     {
5815       int regno;
5816
5817       if (GET_CODE (op) == REG)
5818         regno = REGNO (op);
5819       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
5820         regno = REGNO (SUBREG_REG (op));
5821       else
5822         return 1;
5823
5824       return (regno != T_REG && regno != PR_REG
5825               && ! TARGET_REGISTER_P (regno)
5826               && (regno != FPUL_REG || TARGET_SH4)
5827               && regno != MACH_REG && regno != MACL_REG);
5828     }
5829   return 0;
5830 }
5831
5832 int
5833 fp_arith_reg_operand (op, mode)
5834      rtx op;
5835      enum machine_mode mode;
5836 {
5837   if (register_operand (op, mode))
5838     {
5839       int regno;
5840
5841       if (GET_CODE (op) == REG)
5842         regno = REGNO (op);
5843       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
5844         regno = REGNO (SUBREG_REG (op));
5845       else
5846         return 1;
5847
5848       return (regno >= FIRST_PSEUDO_REGISTER
5849               || FP_REGISTER_P (regno));
5850     }
5851   return 0;
5852 }
5853
5854 /* Returns 1 if OP is a valid source operand for an arithmetic insn.  */
5855
5856 int
5857 arith_operand (op, mode)
5858      rtx op;
5859      enum machine_mode mode;
5860 {
5861   if (arith_reg_operand (op, mode))
5862     return 1;
5863
5864   if (TARGET_SHMEDIA)
5865     {
5866       /* FIXME: We should be checking whether the CONST_INT fits in a
5867          CONST_OK_FOR_J here, but this causes reload_cse to crash when
5868          attempting to transform a sequence of two 64-bit sets of the
5869          same register from literal constants into a set and an add,
5870          when the difference is too wide for an add.  */
5871       if (GET_CODE (op) == CONST_INT
5872           || EXTRA_CONSTRAINT_S (op))
5873         return 1;
5874       else
5875         return 0;
5876     }
5877   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_I (INTVAL (op)))
5878     return 1;
5879
5880   return 0;
5881 }
5882
5883 /* Returns 1 if OP is a valid source operand for a compare insn.  */
5884
5885 int
5886 arith_reg_or_0_operand (op, mode)
5887      rtx op;
5888      enum machine_mode mode;
5889 {
5890   if (arith_reg_operand (op, mode))
5891     return 1;
5892
5893   if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_N (INTVAL (op)))
5894     return 1;
5895
5896   return 0;
5897 }
5898
5899 /* Return 1 if OP is a valid source operand for an SHmedia operation
5900    that takes either a register or a 6-bit immediate.  */
5901
5902 int
5903 shmedia_6bit_operand (op, mode)
5904      rtx op;
5905      enum machine_mode mode;
5906 {
5907   return (arith_reg_operand (op, mode)
5908           || (GET_CODE (op) == CONST_INT && CONST_OK_FOR_O (INTVAL (op))));
5909 }
5910
5911 /* Returns 1 if OP is a valid source operand for a logical operation.  */
5912
5913 int
5914 logical_operand (op, mode)
5915      rtx op;
5916      enum machine_mode mode;
5917 {
5918   if (arith_reg_operand (op, mode))
5919     return 1;
5920
5921   if (TARGET_SHMEDIA)
5922     {
5923       if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_P (INTVAL (op)))
5924         return 1;
5925       else
5926         return 0;
5927     }
5928   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_L (INTVAL (op)))
5929     return 1;
5930
5931   return 0;
5932 }
5933
5934 /* Nonzero if OP is a floating point value with value 0.0.  */
5935
5936 int
5937 fp_zero_operand (op)
5938      rtx op;
5939 {
5940   REAL_VALUE_TYPE r;
5941
5942   if (GET_MODE (op) != SFmode)
5943     return 0;
5944
5945   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
5946   return REAL_VALUES_EQUAL (r, dconst0) && ! REAL_VALUE_MINUS_ZERO (r);
5947 }
5948
5949 /* Nonzero if OP is a floating point value with value 1.0.  */
5950
5951 int
5952 fp_one_operand (op)
5953      rtx op;
5954 {
5955   REAL_VALUE_TYPE r;
5956
5957   if (GET_MODE (op) != SFmode)
5958     return 0;
5959
5960   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
5961   return REAL_VALUES_EQUAL (r, dconst1);
5962 }
5963
5964 /* For -m4 and -m4-single-only, mode switching is used.  If we are
5965    compiling without -mfmovd, movsf_ie isn't taken into account for
5966    mode switching.  We could check in machine_dependent_reorg for
5967    cases where we know we are in single precision mode, but there is
5968    interface to find that out during reload, so we must avoid
5969    choosing an fldi alternative during reload and thus failing to
5970    allocate a scratch register for the constant loading.  */
5971 int
5972 fldi_ok ()
5973 {
5974   return ! TARGET_SH4 || TARGET_FMOVD || reload_completed;
5975 }
5976
5977 int
5978 tertiary_reload_operand (op, mode)
5979      rtx op;
5980      enum machine_mode mode ATTRIBUTE_UNUSED;
5981 {
5982   enum rtx_code code = GET_CODE (op);
5983   return code == MEM || (TARGET_SH4 && code == CONST_DOUBLE);
5984 }
5985
5986 int
5987 fpscr_operand (op, mode)
5988      rtx op;
5989      enum machine_mode mode ATTRIBUTE_UNUSED;
5990 {
5991   return (GET_CODE (op) == REG && REGNO (op) == FPSCR_REG
5992           && GET_MODE (op) == PSImode);
5993 }
5994
5995 int
5996 fpul_operand (op, mode)
5997      rtx op;
5998      enum machine_mode mode;
5999 {
6000   if (TARGET_SHMEDIA)
6001     return fp_arith_reg_operand (op, mode);
6002
6003   return (GET_CODE (op) == REG
6004           && (REGNO (op) == FPUL_REG || REGNO (op) >= FIRST_PSEUDO_REGISTER)
6005           && GET_MODE (op) == mode);
6006 }
6007
6008 int
6009 symbol_ref_operand (op, mode)
6010      rtx op;
6011      enum machine_mode mode ATTRIBUTE_UNUSED;
6012 {
6013   return (GET_CODE (op) == SYMBOL_REF);
6014 }
6015
6016 int
6017 commutative_float_operator (op, mode)
6018      rtx op;
6019      enum machine_mode mode;
6020 {
6021   if (GET_MODE (op) != mode)
6022     return 0;
6023   switch (GET_CODE (op))
6024     {
6025     case PLUS:
6026     case MULT:
6027       return 1;
6028     default:
6029       break;
6030     }
6031   return 0;
6032 }
6033
6034 int
6035 noncommutative_float_operator (op, mode)
6036      rtx op;
6037      enum machine_mode mode;
6038 {
6039   if (GET_MODE (op) != mode)
6040     return 0;
6041   switch (GET_CODE (op))
6042     {
6043     case MINUS:
6044     case DIV:
6045       return 1;
6046     default:
6047       break;
6048     }
6049   return 0;
6050 }
6051
6052 int
6053 binary_float_operator (op, mode)
6054      rtx op;
6055      enum machine_mode mode;
6056 {
6057   if (GET_MODE (op) != mode)
6058     return 0;
6059   switch (GET_CODE (op))
6060     {
6061     case PLUS:
6062     case MINUS:
6063     case MULT:
6064     case DIV:
6065       return 1;
6066     default:
6067       break;
6068     }
6069   return 0;
6070 }
6071
6072 /* Accept pseudos and branch target registers.  */
6073 int
6074 target_reg_operand (op, mode)
6075      rtx op;
6076      enum machine_mode mode;
6077 {
6078   if (mode != DImode
6079       || GET_MODE (op) != DImode)
6080     return 0;
6081
6082   if (GET_CODE (op) == SUBREG)
6083     op = XEXP (op, 0);
6084
6085   if (GET_CODE (op) != REG)
6086     return 0;
6087
6088   /* We must protect ourselves from matching pseudos that are virtual
6089      register, because they will eventually be replaced with hardware
6090      registers that aren't branch-target registers.  */
6091   if (REGNO (op) > LAST_VIRTUAL_REGISTER
6092       || TARGET_REGISTER_P (REGNO (op)))
6093     return 1;
6094
6095   return 0;
6096 }
6097
6098 /* Same as target_reg_operand, except that label_refs and symbol_refs
6099    are accepted before reload.  */
6100 int
6101 target_operand (op, mode)
6102      rtx op;
6103      enum machine_mode mode;
6104 {
6105   if (mode != DImode)
6106     return 0;
6107
6108   if ((GET_MODE (op) == DImode || GET_MODE (op) == VOIDmode)
6109       && EXTRA_CONSTRAINT_T (op))
6110     return ! reload_completed;
6111
6112   return target_reg_operand (op, mode);
6113 }
6114
6115 \f
6116 /* Return the destination address of a branch.  */
6117    
6118 static int
6119 branch_dest (branch)
6120      rtx branch;
6121 {
6122   rtx dest = SET_SRC (PATTERN (branch));
6123   int dest_uid;
6124
6125   if (GET_CODE (dest) == IF_THEN_ELSE)
6126     dest = XEXP (dest, 1);
6127   dest = XEXP (dest, 0);
6128   dest_uid = INSN_UID (dest);
6129   return INSN_ADDRESSES (dest_uid);
6130 }
6131 \f
6132 /* Return non-zero if REG is not used after INSN.
6133    We assume REG is a reload reg, and therefore does
6134    not live past labels.  It may live past calls or jumps though.  */
6135 int
6136 reg_unused_after (reg, insn)
6137      rtx reg;
6138      rtx insn;
6139 {
6140   enum rtx_code code;
6141   rtx set;
6142
6143   /* If the reg is set by this instruction, then it is safe for our
6144      case.  Disregard the case where this is a store to memory, since
6145      we are checking a register used in the store address.  */
6146   set = single_set (insn);
6147   if (set && GET_CODE (SET_DEST (set)) != MEM
6148       && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6149     return 1;
6150
6151   while ((insn = NEXT_INSN (insn)))
6152     {
6153       code = GET_CODE (insn);
6154
6155 #if 0
6156       /* If this is a label that existed before reload, then the register
6157          if dead here.  However, if this is a label added by reorg, then
6158          the register may still be live here.  We can't tell the difference,
6159          so we just ignore labels completely.  */
6160       if (code == CODE_LABEL)
6161         return 1;
6162       /* else */
6163 #endif
6164
6165       if (code == JUMP_INSN)
6166         return 0;
6167
6168       /* If this is a sequence, we must handle them all at once.
6169          We could have for instance a call that sets the target register,
6170          and an insn in a delay slot that uses the register.  In this case,
6171          we must return 0.  */
6172       else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
6173         {
6174           int i;
6175           int retval = 0;
6176
6177           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
6178             {
6179               rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
6180               rtx set = single_set (this_insn);
6181
6182               if (GET_CODE (this_insn) == CALL_INSN)
6183                 code = CALL_INSN;
6184               else if (GET_CODE (this_insn) == JUMP_INSN)
6185                 {
6186                   if (INSN_ANNULLED_BRANCH_P (this_insn))
6187                     return 0;
6188                   code = JUMP_INSN;
6189                 }
6190
6191               if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
6192                 return 0;
6193               if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6194                 {
6195                   if (GET_CODE (SET_DEST (set)) != MEM)
6196                     retval = 1;
6197                   else
6198                     return 0;
6199                 }
6200               if (set == 0
6201                   && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
6202                 return 0;
6203             }
6204           if (retval == 1)
6205             return 1;
6206           else if (code == JUMP_INSN)
6207             return 0;
6208         }
6209       else if (GET_RTX_CLASS (code) == 'i')
6210         {
6211           rtx set = single_set (insn);
6212
6213           if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
6214             return 0;
6215           if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
6216             return GET_CODE (SET_DEST (set)) != MEM;
6217           if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
6218             return 0;
6219         }
6220
6221       if (code == CALL_INSN && call_used_regs[REGNO (reg)])
6222         return 1;
6223     }
6224   return 1;
6225 }
6226 \f
6227 #include "ggc.h"
6228
6229 rtx
6230 get_fpscr_rtx ()
6231 {
6232   static rtx fpscr_rtx;
6233
6234   if (! fpscr_rtx)
6235     {
6236       fpscr_rtx = gen_rtx (REG, PSImode, FPSCR_REG);
6237       REG_USERVAR_P (fpscr_rtx) = 1;
6238       ggc_add_rtx_root (&fpscr_rtx, 1);
6239       mark_user_reg (fpscr_rtx);
6240     }
6241   if (! reload_completed || mdep_reorg_phase != SH_AFTER_MDEP_REORG)
6242     mark_user_reg (fpscr_rtx);
6243   return fpscr_rtx;
6244 }
6245
6246 void
6247 emit_sf_insn (pat)
6248      rtx pat;
6249 {
6250   emit_insn (pat);
6251 }
6252
6253 void
6254 emit_df_insn (pat)
6255      rtx pat;
6256 {
6257   emit_insn (pat);
6258 }
6259
6260 void
6261 expand_sf_unop (fun, operands)
6262      rtx (*fun) PARAMS ((rtx, rtx, rtx));
6263      rtx *operands;
6264 {
6265   emit_sf_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
6266 }
6267
6268 void
6269 expand_sf_binop (fun, operands)
6270      rtx (*fun) PARAMS ((rtx, rtx, rtx, rtx));
6271      rtx *operands;
6272 {
6273   emit_sf_insn ((*fun) (operands[0], operands[1], operands[2],
6274                          get_fpscr_rtx ()));
6275 }
6276
6277 void
6278 expand_df_unop (fun, operands)
6279      rtx (*fun) PARAMS ((rtx, rtx, rtx));
6280      rtx *operands;
6281 {
6282   emit_df_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
6283 }
6284
6285 void
6286 expand_df_binop (fun, operands)
6287      rtx (*fun) PARAMS ((rtx, rtx, rtx, rtx));
6288      rtx *operands;
6289 {
6290   emit_df_insn ((*fun) (operands[0], operands[1], operands[2],
6291                          get_fpscr_rtx ()));
6292 }
6293 \f
6294 /* ??? gcc does flow analysis strictly after common subexpression
6295    elimination.  As a result, common subespression elimination fails
6296    when there are some intervening statements setting the same register.
6297    If we did nothing about this, this would hurt the precision switching
6298    for SH4 badly.  There is some cse after reload, but it is unable to
6299    undo the extra register pressure from the unused instructions, and
6300    it cannot remove auto-increment loads.
6301
6302    A C code example that shows this flow/cse weakness for (at least) SH
6303    and sparc (as of gcc ss-970706) is this:
6304
6305 double
6306 f(double a)
6307 {
6308   double d;
6309   d = 0.1;
6310   a += d;
6311   d = 1.1;
6312   d = 0.1;
6313   a *= d;
6314   return a;
6315 }
6316
6317    So we add another pass before common subexpression elimination, to
6318    remove assignments that are dead due to a following assignment in the
6319    same basic block.  */
6320
6321 static void 
6322 mark_use (x, reg_set_block)
6323      rtx x, *reg_set_block;
6324 {
6325   enum rtx_code code;
6326
6327   if (! x)
6328     return;
6329   code = GET_CODE (x);
6330   switch (code)
6331     {
6332     case REG:
6333       {
6334         int regno = REGNO (x);
6335         int nregs = (regno < FIRST_PSEUDO_REGISTER
6336                      ? HARD_REGNO_NREGS (regno, GET_MODE (x))
6337                      : 1);
6338         do
6339           {
6340             reg_set_block[regno + nregs - 1] = 0;
6341           }
6342         while (--nregs);
6343         break;
6344       }
6345     case SET:
6346       {
6347         rtx dest = SET_DEST (x);
6348
6349         if (GET_CODE (dest) == SUBREG)
6350           dest = SUBREG_REG (dest);
6351         if (GET_CODE (dest) != REG)
6352           mark_use (dest, reg_set_block);
6353         mark_use (SET_SRC (x), reg_set_block);
6354         break;
6355       }
6356     case CLOBBER:
6357       break;
6358     default:
6359       {
6360         const char *fmt = GET_RTX_FORMAT (code);
6361         int i, j;
6362         for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
6363           {
6364             if (fmt[i] == 'e')
6365               mark_use (XEXP (x, i), reg_set_block);
6366             else if (fmt[i] == 'E')
6367               for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6368                 mark_use (XVECEXP (x, i, j), reg_set_block);
6369           }
6370         break;
6371       }
6372     }
6373 }
6374 \f
6375 static rtx get_free_reg PARAMS ((HARD_REG_SET));
6376
6377 /* This function returns a register to use to load the address to load
6378    the fpscr from.  Currently it always returns r1 or r7, but when we are
6379    able to use pseudo registers after combine, or have a better mechanism
6380    for choosing a register, it should be done here.  */
6381 /* REGS_LIVE is the liveness information for the point for which we
6382    need this allocation.  In some bare-bones exit blocks, r1 is live at the
6383    start.  We can even have all of r0..r3 being live:
6384 __complex__ long long f (double d) { if (d == 0) return 2; else return 3; }
6385    INSN before which new insns are placed with will clobber the register
6386    we return.  If a basic block consists only of setting the return value
6387    register to a pseudo and using that register, the return value is not
6388    live before or after this block, yet we we'll insert our insns right in
6389    the middle.  */
6390
6391 static rtx
6392 get_free_reg (regs_live)
6393      HARD_REG_SET regs_live;
6394 {
6395   if (! TEST_HARD_REG_BIT (regs_live, 1))
6396     return gen_rtx_REG (Pmode, 1);
6397
6398   /* Hard reg 1 is live; since this is a SMALL_REGISTER_CLASSES target,
6399      there shouldn't be anything but a jump before the function end.  */
6400   if (! TEST_HARD_REG_BIT (regs_live, 7))
6401     return gen_rtx_REG (Pmode, 7);
6402
6403   abort ();
6404 }
6405
6406 /* This function will set the fpscr from memory. 
6407    MODE is the mode we are setting it to.  */
6408 void
6409 fpscr_set_from_mem (mode, regs_live)
6410      int mode;
6411      HARD_REG_SET regs_live;
6412 {
6413   enum attr_fp_mode fp_mode = mode;
6414   rtx addr_reg = get_free_reg (regs_live);
6415
6416   if (fp_mode == (enum attr_fp_mode) NORMAL_MODE (FP_MODE))
6417     emit_insn (gen_fpu_switch1 (addr_reg));
6418   else
6419     emit_insn (gen_fpu_switch0 (addr_reg));
6420 }
6421
6422 /* Is the given character a logical line separator for the assembler?  */
6423 #ifndef IS_ASM_LOGICAL_LINE_SEPARATOR
6424 #define IS_ASM_LOGICAL_LINE_SEPARATOR(C) ((C) == ';')
6425 #endif
6426
6427 int
6428 sh_insn_length_adjustment (insn)
6429      rtx insn;
6430 {
6431   /* Instructions with unfilled delay slots take up an extra two bytes for
6432      the nop in the delay slot.  */
6433   if (((GET_CODE (insn) == INSN
6434         && GET_CODE (PATTERN (insn)) != USE
6435         && GET_CODE (PATTERN (insn)) != CLOBBER)
6436        || GET_CODE (insn) == CALL_INSN
6437        || (GET_CODE (insn) == JUMP_INSN
6438            && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
6439            && GET_CODE (PATTERN (insn)) != ADDR_VEC))
6440       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE
6441       && get_attr_needs_delay_slot (insn) == NEEDS_DELAY_SLOT_YES)
6442     return 2;
6443
6444   /* sh-dsp parallel processing insn take four bytes instead of two.  */
6445      
6446   if (GET_CODE (insn) == INSN)
6447     {
6448       int sum = 0;
6449       rtx body = PATTERN (insn);
6450       const char *template;
6451       char c;
6452       int maybe_label = 1;
6453
6454       if (GET_CODE (body) == ASM_INPUT)
6455         template = XSTR (body, 0);
6456       else if (asm_noperands (body) >= 0)
6457         template
6458           = decode_asm_operands (body, NULL, NULL, NULL, NULL);
6459       else
6460         return 0;
6461       do
6462         {
6463           int ppi_adjust = 0;
6464
6465           do
6466             c = *template++;
6467           while (c == ' ' || c == '\t');
6468           /* all sh-dsp parallel-processing insns start with p.
6469              The only non-ppi sh insn starting with p is pref.
6470              The only ppi starting with pr is prnd.  */
6471           if ((c == 'p' || c == 'P') && strncasecmp ("re", template, 2))
6472             ppi_adjust = 2;
6473           /* The repeat pseudo-insn expands two three insns, a total of
6474              six bytes in size.  */
6475           else if ((c == 'r' || c == 'R')
6476                    && ! strncasecmp ("epeat", template, 5))
6477             ppi_adjust = 4;
6478           while (c && c != '\n' && ! IS_ASM_LOGICAL_LINE_SEPARATOR (c))
6479             {
6480               /* If this is a label, it is obviously not a ppi insn.  */
6481               if (c == ':' && maybe_label)
6482                 {
6483                   ppi_adjust = 0;
6484                   break;
6485                 }
6486               else if (c == '\'' || c == '"')
6487                 maybe_label = 0;
6488               c = *template++;
6489             }
6490           sum += ppi_adjust;
6491           maybe_label = c != ':';
6492         }
6493       while (c);
6494       return sum;
6495     }
6496   return 0;
6497 }
6498 \f
6499 /* Return TRUE if X references a SYMBOL_REF or LABEL_REF whose symbol
6500    isn't protected by a PIC unspec.  */
6501 int
6502 nonpic_symbol_mentioned_p (x)
6503      rtx x;
6504 {
6505   register const char *fmt;
6506   register int i;
6507
6508   if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF
6509       || GET_CODE (x) == PC)
6510     return 1;
6511
6512   /* We don't want to look into the possible MEM location of a
6513      CONST_DOUBLE, since we're not going to use it, in general.  */
6514   if (GET_CODE (x) == CONST_DOUBLE)
6515     return 0;
6516
6517   if (GET_CODE (x) == UNSPEC
6518       && (XINT (x, 1) == UNSPEC_PIC
6519           || XINT (x, 1) == UNSPEC_GOT
6520           || XINT (x, 1) == UNSPEC_GOTOFF
6521           || XINT (x, 1) == UNSPEC_GOTPLT
6522           || XINT (x, 1) == UNSPEC_PLT))
6523       return 0;
6524
6525   fmt = GET_RTX_FORMAT (GET_CODE (x));
6526   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
6527     {
6528       if (fmt[i] == 'E')
6529         {
6530           register int j;
6531
6532           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6533             if (nonpic_symbol_mentioned_p (XVECEXP (x, i, j)))
6534               return 1;
6535         }
6536       else if (fmt[i] == 'e' && nonpic_symbol_mentioned_p (XEXP (x, i)))
6537         return 1;
6538     }
6539
6540   return 0;
6541 }
6542
6543 /* Convert a non-PIC address in `orig' to a PIC address using @GOT or
6544    @GOTOFF in `reg'.  */
6545 rtx
6546 legitimize_pic_address (orig, mode, reg)
6547      rtx orig;
6548      enum machine_mode mode ATTRIBUTE_UNUSED;
6549      rtx reg;
6550 {
6551   if (GET_CODE (orig) == LABEL_REF
6552       || (GET_CODE (orig) == SYMBOL_REF
6553           && (CONSTANT_POOL_ADDRESS_P (orig)
6554               /* SYMBOL_REF_FLAG is set on static symbols.  */
6555               || SYMBOL_REF_FLAG (orig))))
6556     {
6557       if (reg == 0)
6558         reg = gen_reg_rtx (Pmode);
6559
6560       emit_insn (gen_symGOTOFF2reg (reg, orig));
6561       return reg;
6562     }
6563   else if (GET_CODE (orig) == SYMBOL_REF)
6564     {
6565       if (reg == 0)
6566         reg = gen_reg_rtx (Pmode);
6567
6568       emit_insn (gen_symGOT2reg (reg, orig));
6569       return reg;
6570     }
6571   return orig;
6572 }
6573
6574 /* Mark the use of a constant in the literal table. If the constant
6575    has multiple labels, make it unique.  */
6576 static rtx mark_constant_pool_use (x)
6577      rtx x;
6578 {
6579   rtx insn, lab, pattern;
6580
6581   if (x == NULL)
6582     return x;
6583
6584   switch (GET_CODE (x))
6585     {
6586     case LABEL_REF:
6587       x = XEXP (x, 0);
6588     case CODE_LABEL:
6589       break;
6590     default:
6591       return x;
6592     }
6593
6594   /* Get the first label in the list of labels for the same constant
6595      and delete another labels in the list.  */
6596   lab = x;
6597   for (insn = PREV_INSN (x); insn; insn = PREV_INSN (insn))
6598     {
6599       if (GET_CODE (insn) != CODE_LABEL
6600           || LABEL_REFS (insn) != NEXT_INSN (insn))
6601         break;
6602       lab = insn;
6603     }
6604
6605   for (insn = LABEL_REFS (lab); insn; insn = LABEL_REFS (insn))
6606     INSN_DELETED_P (insn) = 1;
6607
6608   /* Mark constants in a window.  */
6609   for (insn = NEXT_INSN (x); insn; insn = NEXT_INSN (insn))
6610     {
6611       if (GET_CODE (insn) != INSN)
6612         continue;
6613
6614       pattern = PATTERN (insn);
6615       if (GET_CODE (pattern) != UNSPEC_VOLATILE)
6616         continue;
6617
6618       switch (XINT (pattern, 1))
6619         {
6620         case UNSPECV_CONST2:
6621         case UNSPECV_CONST4:
6622         case UNSPECV_CONST8:
6623           XVECEXP (pattern, 0, 1) = const1_rtx;
6624           break;
6625         case UNSPECV_WINDOW_END:
6626           if (XVECEXP (pattern, 0, 0) == x)
6627             return lab;
6628           break;
6629         case UNSPECV_CONST_END:
6630           return lab;
6631         default:
6632           break;
6633         }
6634     }
6635
6636   return lab;
6637 }
6638 \f
6639 /* Return true if it's possible to redirect BRANCH1 to the destination
6640    of an unconditional jump BRANCH2.  We only want to do this if the
6641    resulting branch will have a short displacement.  */
6642 int 
6643 sh_can_redirect_branch (branch1, branch2)
6644      rtx branch1;
6645      rtx branch2;
6646 {
6647   if (flag_expensive_optimizations && simplejump_p (branch2))
6648     {
6649       rtx dest = XEXP (SET_SRC (single_set (branch2)), 0);
6650       rtx insn;
6651       int distance;
6652       
6653       for (distance = 0, insn = NEXT_INSN (branch1); 
6654            insn && distance < 256; 
6655            insn = PREV_INSN (insn))
6656         {
6657           if (insn == dest)    
6658             return 1;
6659           else
6660             distance += get_attr_length (insn);
6661         }
6662       for (distance = 0, insn = NEXT_INSN (branch1); 
6663            insn && distance < 256; 
6664            insn = NEXT_INSN (insn))
6665         {
6666           if (insn == dest)    
6667             return 1;
6668           else
6669             distance += get_attr_length (insn);
6670         }
6671     }
6672   return 0;
6673 }
6674
6675 #ifndef OBJECT_FORMAT_ELF
6676 static void
6677 sh_asm_named_section (name, flags)
6678      const char *name;
6679      unsigned int flags ATTRIBUTE_UNUSED;
6680 {
6681   /* ??? Perhaps we should be using default_coff_asm_named_section.  */
6682   fprintf (asm_out_file, "\t.section %s\n", name);
6683 }
6684 #endif /* ! OBJECT_FORMAT_ELF */
6685
6686 /* A C statement (sans semicolon) to update the integer variable COST
6687    based on the relationship between INSN that is dependent on
6688    DEP_INSN through the dependence LINK.  The default is to make no
6689    adjustment to COST.  This can be used for example to specify to
6690    the scheduler that an output- or anti-dependence does not incur
6691    the same cost as a data-dependence.  */
6692 static int
6693 sh_adjust_cost (insn, link, dep_insn, cost)
6694      rtx insn;
6695      rtx link ATTRIBUTE_UNUSED;
6696      rtx dep_insn;
6697      int cost;
6698 {
6699   rtx reg;
6700
6701   if (GET_CODE(insn) == CALL_INSN)
6702     {
6703       /* The only input for a call that is timing-critical is the
6704          function's address.  */
6705       rtx call = PATTERN (insn);
6706
6707       if (GET_CODE (call) == PARALLEL)
6708         call = XVECEXP (call, 0 ,0);
6709       if (GET_CODE (call) == SET)
6710         call = SET_SRC (call);
6711       if (GET_CODE (call) == CALL && GET_CODE (XEXP (call, 0)) == MEM
6712           && ! reg_set_p (XEXP (XEXP (call, 0), 0), dep_insn))
6713         cost = 0;
6714     }
6715   /* All sfunc calls are parallels with at least four components.
6716      Exploit this to avoid unnecessary calls to sfunc_uses_reg.  */
6717   else if (GET_CODE (PATTERN (insn)) == PARALLEL
6718            && XVECLEN (PATTERN (insn), 0) >= 4
6719            && (reg = sfunc_uses_reg (insn)))
6720     {
6721       /* Likewise, the most timing critical input for an sfuncs call
6722          is the function address.  However, sfuncs typically start
6723          using their arguments pretty quickly.
6724          Assume a four cycle delay before they are needed.  */
6725       if (! reg_set_p (reg, dep_insn))
6726         cost -= TARGET_SUPERSCALAR ? 40 : 4;
6727     }
6728   /* Adjust load_si / pcload_si type insns latency.  Use the known
6729      nominal latency and form of the insn to speed up the check.  */
6730   else if (cost == 3
6731            && GET_CODE (PATTERN (dep_insn)) == SET
6732            /* Latency for dmpy type insns is also 3, so check the that
6733               it's actually a move insn.  */
6734            && general_movsrc_operand (SET_SRC (PATTERN (dep_insn)), SImode))
6735     cost = 2;
6736   else if (cost == 30
6737            && GET_CODE (PATTERN (dep_insn)) == SET
6738            && GET_MODE (SET_SRC (PATTERN (dep_insn))) == SImode)
6739     cost = 20;
6740
6741   return cost;
6742 }
6743
6744 /* For use by ALLOCATE_INITIAL_VALUE.  Note that sh.md contains some
6745    'special function' patterns (type sfunc) that clobber pr, but that
6746    do not look like function calls to leaf_function_p.  Hence we must
6747    do this extra check.  */
6748 int
6749 sh_pr_n_sets ()
6750 {
6751   return REG_N_SETS (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
6752 }
6753
6754 /* This Function Returns non zero if DFA based scheduler
6755    interface is to be used.At present supported only for
6756    SH4.  */
6757 static int
6758 sh_use_dfa_interface()
6759 {
6760         if (TARGET_SH4)
6761                 return 1;
6762         else
6763                 return 0;
6764 }
6765
6766 /* This function returns "2" that signifies dual issue 
6767    for SH4 processor.To be used by DFA pipeline description.  */
6768 static int
6769 sh_issue_rate()
6770 {
6771         if(TARGET_SH4)
6772                 return 2;
6773         else
6774                 return 1;
6775 }
6776
6777 /* SHmedia requires registers for branches, so we can't generate new
6778    branches past reload.  */
6779 static bool
6780 sh_cannot_modify_jumps_p ()
6781 {
6782   return (TARGET_SHMEDIA && (reload_in_progress || reload_completed));
6783 }
6784
6785 static bool
6786 sh_ms_bitfield_layout_p (record_type)
6787      tree record_type ATTRIBUTE_UNUSED;
6788 {
6789   return TARGET_SH5;
6790 }
6791
6792 /* If using PIC, mark a SYMBOL_REF for a non-global symbol so that we
6793    may access it using GOTOFF instead of GOT.  */
6794
6795 static void
6796 sh_encode_section_info (decl, first)
6797      tree decl;
6798      int first;
6799 {
6800   rtx rtl, symbol;
6801
6802   if (DECL_P (decl))
6803     rtl = DECL_RTL (decl);
6804   else
6805     rtl = TREE_CST_RTL (decl);
6806   if (GET_CODE (rtl) != MEM)
6807     return;
6808   symbol = XEXP (rtl, 0);
6809   if (GET_CODE (symbol) != SYMBOL_REF)
6810     return;
6811
6812   if (flag_pic)
6813     {
6814       SYMBOL_REF_FLAG (symbol) =
6815         (TREE_CODE_CLASS (TREE_CODE (decl)) != 'd'
6816          || MODULE_LOCAL_P (decl)
6817          || ! TREE_PUBLIC (decl));
6818     }
6819
6820   if (TARGET_SH5 && first && TREE_CODE (decl) != FUNCTION_DECL)
6821     XEXP (rtl, 0) = gen_datalabel_ref (symbol);
6822 }