OSDN Git Service

43657e41e858de46c50fab355b15925256306008
[pf3gnuchains/gcc-fork.git] / gcc / config / sh / sh.c
1 /* Output routines for GCC for Renesas / SuperH SH.
2    Copyright (C) 1993, 1994, 1995, 1997, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004 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 GCC.
8
9 GCC 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 GCC 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 GCC; 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 "coretypes.h"
27 #include "tm.h"
28 #include "insn-config.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "expr.h"
33 #include "optabs.h"
34 #include "function.h"
35 #include "regs.h"
36 #include "hard-reg-set.h"
37 #include "output.h"
38 #include "insn-attr.h"
39 #include "toplev.h"
40 #include "recog.h"
41 #include "c-pragma.h"
42 #include "integrate.h"
43 #include "tm_p.h"
44 #include "target.h"
45 #include "target-def.h"
46 #include "real.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "ra.h"
50 #include "cfglayout.h"
51 #include "intl.h"
52
53 int code_for_indirect_jump_scratch = CODE_FOR_indirect_jump_scratch;
54
55 #define MSW (TARGET_LITTLE_ENDIAN ? 1 : 0)
56 #define LSW (TARGET_LITTLE_ENDIAN ? 0 : 1)
57
58 /* These are some macros to abstract register modes.  */
59 #define CONST_OK_FOR_ADD(size) \
60   (TARGET_SHMEDIA ? CONST_OK_FOR_I10 (size) : CONST_OK_FOR_I08 (size))
61 #define GEN_MOV (*(TARGET_SHMEDIA64 ? gen_movdi : gen_movsi))
62 #define GEN_ADD3 (*(TARGET_SHMEDIA64 ? gen_adddi3 : gen_addsi3))
63 #define GEN_SUB3 (*(TARGET_SHMEDIA64 ? gen_subdi3 : gen_subsi3))
64
65 /* Set to 1 by expand_prologue() when the function is an interrupt handler.  */
66 int current_function_interrupt;
67
68 /* ??? The pragma interrupt support will not work for SH3.  */
69 /* This is set by #pragma interrupt and #pragma trapa, and causes gcc to
70    output code for the next function appropriate for an interrupt handler.  */
71 int pragma_interrupt;
72
73 /* This is set by the trap_exit attribute for functions.   It specifies
74    a trap number to be used in a trapa instruction at function exit
75    (instead of an rte instruction).  */
76 int trap_exit;
77
78 /* This is used by the sp_switch attribute for functions.  It specifies
79    a variable holding the address of the stack the interrupt function
80    should switch to/from at entry/exit.  */
81 rtx sp_switch;
82
83 /* This is set by #pragma trapa, and is similar to the above, except that
84    the compiler doesn't emit code to preserve all registers.  */
85 static int pragma_trapa;
86
87 /* This is set by #pragma nosave_low_regs.  This is useful on the SH3,
88    which has a separate set of low regs for User and Supervisor modes.
89    This should only be used for the lowest level of interrupts.  Higher levels
90    of interrupts must save the registers in case they themselves are
91    interrupted.  */
92 int pragma_nosave_low_regs;
93
94 /* This is used for communication between SETUP_INCOMING_VARARGS and
95    sh_expand_prologue.  */
96 int current_function_anonymous_args;
97
98 /* Global variables for machine-dependent things.  */
99
100 /* Which cpu are we scheduling for.  */
101 enum processor_type sh_cpu;
102
103 /* Saved operands from the last compare to use when we generate an scc
104    or bcc insn.  */
105
106 rtx sh_compare_op0;
107 rtx sh_compare_op1;
108
109 /* Provides the class number of the smallest class containing
110    reg number.  */
111
112 enum reg_class regno_reg_class[FIRST_PSEUDO_REGISTER] =
113 {
114   R0_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   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
123   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
124   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
125   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
126   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
127   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
128   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
129   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
130   FP0_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   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
139   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
140   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
141   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
142   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
143   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
144   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
145   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
146   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
147   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
148   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
149   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
150   NO_REGS, GENERAL_REGS, PR_REGS, T_REGS,
151   MAC_REGS, MAC_REGS, FPUL_REGS, FPSCR_REGS,
152   GENERAL_REGS,
153 };
154
155 char sh_register_names[FIRST_PSEUDO_REGISTER] \
156   [MAX_REGISTER_NAME_LENGTH + 1] = SH_REGISTER_NAMES_INITIALIZER;
157
158 char sh_additional_register_names[ADDREGNAMES_SIZE] \
159   [MAX_ADDITIONAL_REGISTER_NAME_LENGTH + 1]
160   = SH_ADDITIONAL_REGISTER_NAMES_INITIALIZER;
161
162 /* Provide reg_class from a letter such as appears in the machine
163    description.  *: target independently reserved letter.
164    reg_class_from_letter['e' - 'a'] is set to NO_REGS for TARGET_FMOVD.  */
165
166 enum reg_class reg_class_from_letter[] =
167 {
168   /* a */ ALL_REGS,  /* b */ TARGET_REGS, /* c */ FPSCR_REGS, /* d */ DF_REGS,
169   /* e */ FP_REGS,   /* f */ FP_REGS,  /* g **/ NO_REGS,     /* h */ NO_REGS,
170   /* i **/ NO_REGS,  /* j */ NO_REGS,  /* k */ SIBCALL_REGS, /* l */ PR_REGS,
171   /* m **/ NO_REGS,  /* n **/ NO_REGS, /* o **/ NO_REGS,     /* p **/ NO_REGS,
172   /* q */ NO_REGS,   /* r **/ NO_REGS, /* s **/ NO_REGS,     /* t */ T_REGS,
173   /* u */ NO_REGS,   /* v */ NO_REGS,  /* w */ FP0_REGS,     /* x */ MAC_REGS,
174   /* y */ FPUL_REGS, /* z */ R0_REGS
175 };
176
177 int assembler_dialect;
178
179 static bool shmedia_space_reserved_for_target_registers;
180
181 static void split_branches (rtx);
182 static int branch_dest (rtx);
183 static void force_into (rtx, rtx);
184 static void print_slot (rtx);
185 static rtx add_constant (rtx, enum machine_mode, rtx);
186 static void dump_table (rtx);
187 static int hi_const (rtx);
188 static int broken_move (rtx);
189 static int mova_p (rtx);
190 static rtx find_barrier (int, rtx, rtx);
191 static int noncall_uses_reg (rtx, rtx, rtx *);
192 static rtx gen_block_redirect (rtx, int, int);
193 static void sh_reorg (void);
194 static void output_stack_adjust (int, rtx, int, HARD_REG_SET *);
195 static rtx frame_insn (rtx);
196 static rtx push (int);
197 static void pop (int);
198 static void push_regs (HARD_REG_SET *, int);
199 static int calc_live_regs (HARD_REG_SET *);
200 static void mark_use (rtx, rtx *);
201 static HOST_WIDE_INT rounded_frame_size (int);
202 static rtx mark_constant_pool_use (rtx);
203 const struct attribute_spec sh_attribute_table[];
204 static tree sh_handle_interrupt_handler_attribute (tree *, tree, tree, int, bool *);
205 static tree sh_handle_sp_switch_attribute (tree *, tree, tree, int, bool *);
206 static tree sh_handle_trap_exit_attribute (tree *, tree, tree, int, bool *);
207 static tree sh_handle_renesas_attribute (tree *, tree, tree, int, bool *);
208 static void sh_output_function_epilogue (FILE *, HOST_WIDE_INT);
209 static void sh_insert_attributes (tree, tree *);
210 static int sh_adjust_cost (rtx, rtx, rtx, int);
211 static int sh_use_dfa_interface (void);
212 static int sh_issue_rate (void);
213 static bool sh_function_ok_for_sibcall (tree, tree);
214
215 static bool sh_cannot_modify_jumps_p (void);
216 static int sh_target_reg_class (void);
217 static bool sh_optimize_target_register_callee_saved (bool);
218 static bool sh_ms_bitfield_layout_p (tree);
219
220 static void sh_init_builtins (void);
221 static void sh_media_init_builtins (void);
222 static rtx sh_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
223 static void sh_output_mi_thunk (FILE *, tree, HOST_WIDE_INT, HOST_WIDE_INT, tree);
224 static void sh_file_start (void);
225 static int flow_dependent_p (rtx, rtx);
226 static void flow_dependent_p_1 (rtx, rtx, void *);
227 static int shiftcosts (rtx);
228 static int andcosts (rtx);
229 static int addsubcosts (rtx);
230 static int multcosts (rtx);
231 static bool unspec_caller_rtx_p (rtx);
232 static bool sh_cannot_copy_insn_p (rtx);
233 static bool sh_rtx_costs (rtx, int, int, int *);
234 static int sh_address_cost (rtx);
235 static int shmedia_target_regs_stack_space (HARD_REG_SET *);
236 static int shmedia_reserve_space_for_target_registers_p (int, HARD_REG_SET *);
237 static int shmedia_target_regs_stack_adjust (HARD_REG_SET *);
238 static int scavenge_reg (HARD_REG_SET *s);
239 struct save_schedule_s;
240 static struct save_entry_s *sh5_schedule_saves (HARD_REG_SET *,
241                                                 struct save_schedule_s *, int);
242
243 static bool sh_promote_prototypes (tree);
244 static rtx sh_struct_value_rtx (tree, int);
245 static bool sh_return_in_memory (tree, tree);
246 static rtx sh_builtin_saveregs (void);
247 static void sh_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode, tree, int *, int);
248 static bool sh_strict_argument_naming (CUMULATIVE_ARGS *);
249 static bool sh_pretend_outgoing_varargs_named (CUMULATIVE_ARGS *);
250 static tree sh_build_builtin_va_list (void);
251
252 \f
253 /* Initialize the GCC target structure.  */
254 #undef TARGET_ATTRIBUTE_TABLE
255 #define TARGET_ATTRIBUTE_TABLE sh_attribute_table
256
257 /* The next two are used for debug info when compiling with -gdwarf.  */
258 #undef TARGET_ASM_UNALIGNED_HI_OP
259 #define TARGET_ASM_UNALIGNED_HI_OP "\t.uaword\t"
260 #undef TARGET_ASM_UNALIGNED_SI_OP
261 #define TARGET_ASM_UNALIGNED_SI_OP "\t.ualong\t"
262
263 /* These are NULLed out on non-SH5 in OVERRIDE_OPTIONS.  */
264 #undef TARGET_ASM_UNALIGNED_DI_OP
265 #define TARGET_ASM_UNALIGNED_DI_OP "\t.uaquad\t"
266 #undef TARGET_ASM_ALIGNED_DI_OP
267 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
268
269 #undef TARGET_ASM_FUNCTION_EPILOGUE
270 #define TARGET_ASM_FUNCTION_EPILOGUE sh_output_function_epilogue
271
272 #undef TARGET_ASM_OUTPUT_MI_THUNK
273 #define TARGET_ASM_OUTPUT_MI_THUNK sh_output_mi_thunk
274
275 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
276 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
277
278 #undef TARGET_ASM_FILE_START
279 #define TARGET_ASM_FILE_START sh_file_start
280 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
281 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
282
283 #undef TARGET_INSERT_ATTRIBUTES
284 #define TARGET_INSERT_ATTRIBUTES sh_insert_attributes
285
286 #undef TARGET_SCHED_ADJUST_COST
287 #define TARGET_SCHED_ADJUST_COST sh_adjust_cost
288
289 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE 
290 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE \
291                                 sh_use_dfa_interface
292 #undef TARGET_SCHED_ISSUE_RATE
293 #define TARGET_SCHED_ISSUE_RATE sh_issue_rate
294
295 #undef TARGET_CANNOT_MODIFY_JUMPS_P
296 #define TARGET_CANNOT_MODIFY_JUMPS_P sh_cannot_modify_jumps_p
297 #undef TARGET_BRANCH_TARGET_REGISTER_CLASS
298 #define TARGET_BRANCH_TARGET_REGISTER_CLASS sh_target_reg_class
299 #undef TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED
300 #define TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED \
301  sh_optimize_target_register_callee_saved
302
303 #undef TARGET_MS_BITFIELD_LAYOUT_P
304 #define TARGET_MS_BITFIELD_LAYOUT_P sh_ms_bitfield_layout_p
305
306 #undef TARGET_INIT_BUILTINS
307 #define TARGET_INIT_BUILTINS sh_init_builtins
308 #undef TARGET_EXPAND_BUILTIN
309 #define TARGET_EXPAND_BUILTIN sh_expand_builtin
310
311 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
312 #define TARGET_FUNCTION_OK_FOR_SIBCALL sh_function_ok_for_sibcall
313
314 #undef TARGET_CANNOT_COPY_INSN_P
315 #define TARGET_CANNOT_COPY_INSN_P sh_cannot_copy_insn_p
316 #undef TARGET_RTX_COSTS
317 #define TARGET_RTX_COSTS sh_rtx_costs
318 #undef TARGET_ADDRESS_COST
319 #define TARGET_ADDRESS_COST sh_address_cost
320
321 #undef TARGET_MACHINE_DEPENDENT_REORG
322 #define TARGET_MACHINE_DEPENDENT_REORG sh_reorg
323
324 #ifdef HAVE_AS_TLS
325 #undef TARGET_HAVE_TLS
326 #define TARGET_HAVE_TLS true
327 #endif
328
329 #undef TARGET_PROMOTE_PROTOTYPES
330 #define TARGET_PROMOTE_PROTOTYPES sh_promote_prototypes
331 #undef TARGET_PROMOTE_FUNCTION_ARGS
332 #define TARGET_PROMOTE_FUNCTION_ARGS sh_promote_prototypes
333 #undef TARGET_PROMOTE_FUNCTION_RETURN
334 #define TARGET_PROMOTE_FUNCTION_RETURN sh_promote_prototypes
335
336 #undef TARGET_STRUCT_VALUE_RTX
337 #define TARGET_STRUCT_VALUE_RTX sh_struct_value_rtx
338 #undef TARGET_RETURN_IN_MEMORY
339 #define TARGET_RETURN_IN_MEMORY sh_return_in_memory
340
341 #undef TARGET_EXPAND_BUILTIN_SAVEREGS
342 #define TARGET_EXPAND_BUILTIN_SAVEREGS sh_builtin_saveregs
343 #undef TARGET_SETUP_INCOMING_VARARGS
344 #define TARGET_SETUP_INCOMING_VARARGS sh_setup_incoming_varargs
345 #undef TARGET_STRICT_ARGUMENT_NAMING
346 #define TARGET_STRICT_ARGUMENT_NAMING sh_strict_argument_naming
347 #undef TARGET_PRETEND_OUTGOING_VARARGS_NAMED
348 #define TARGET_PRETEND_OUTGOING_VARARGS_NAMED sh_pretend_outgoing_varargs_named
349
350 #undef TARGET_BUILD_BUILTIN_VA_LIST
351 #define TARGET_BUILD_BUILTIN_VA_LIST sh_build_builtin_va_list
352
353 #undef TARGET_PCH_VALID_P
354 #define TARGET_PCH_VALID_P sh_pch_valid_p
355
356 struct gcc_target targetm = TARGET_INITIALIZER;
357 \f
358 /* Print the operand address in x to the stream.  */
359
360 void
361 print_operand_address (FILE *stream, rtx x)
362 {
363   switch (GET_CODE (x))
364     {
365     case REG:
366     case SUBREG:
367       fprintf (stream, "@%s", reg_names[true_regnum (x)]);
368       break;
369
370     case PLUS:
371       {
372         rtx base = XEXP (x, 0);
373         rtx index = XEXP (x, 1);
374
375         switch (GET_CODE (index))
376           {
377           case CONST_INT:
378             fprintf (stream, "@(%d,%s)", (int) INTVAL (index),
379                      reg_names[true_regnum (base)]);
380             break;
381
382           case REG:
383           case SUBREG:
384             {
385               int base_num = true_regnum (base);
386               int index_num = true_regnum (index);
387
388               fprintf (stream, "@(r0,%s)",
389                        reg_names[MAX (base_num, index_num)]);
390               break;
391             }
392
393           default:
394             debug_rtx (x);
395             abort ();
396           }
397       }
398       break;
399
400     case PRE_DEC:
401       fprintf (stream, "@-%s", reg_names[true_regnum (XEXP (x, 0))]);
402       break;
403
404     case POST_INC:
405       fprintf (stream, "@%s+", reg_names[true_regnum (XEXP (x, 0))]);
406       break;
407
408     default:
409       x = mark_constant_pool_use (x);
410       output_addr_const (stream, x);
411       break;
412     }
413 }
414
415 /* Print operand x (an rtx) in assembler syntax to file stream
416    according to modifier code.
417
418    '.'  print a .s if insn needs delay slot
419    ','  print LOCAL_LABEL_PREFIX
420    '@'  print trap, rte or rts depending upon pragma interruptness
421    '#'  output a nop if there is nothing to put in the delay slot
422    '''  print likelihood suffix (/u for unlikely).
423    'O'  print a constant without the #
424    'R'  print the LSW of a dp value - changes if in little endian
425    'S'  print the MSW of a dp value - changes if in little endian
426    'T'  print the next word of a dp value - same as 'R' in big endian mode.
427    'M'  print an `x' if `m' will print `base,index'.
428    'N'  print 'r63' if the operand is (const_int 0).
429    'm'  print a pair `base,offset' or `base,index', for LD and ST.
430    'u'  prints the lowest 16 bits of CONST_INT, as an unsigned value.
431    'o'  output an operator.  */
432
433 void
434 print_operand (FILE *stream, rtx x, int code)
435 {
436   switch (code)
437     {
438     case '.':
439       if (final_sequence
440           && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
441           && get_attr_length (XVECEXP (final_sequence, 0, 1)))
442         fprintf (stream, ASSEMBLER_DIALECT ? "/s" : ".s");
443       break;
444     case ',':
445       fprintf (stream, "%s", LOCAL_LABEL_PREFIX);
446       break;
447     case '@':
448       if (trap_exit)
449         fprintf (stream, "trapa #%d", trap_exit);
450       else if (sh_cfun_interrupt_handler_p ())
451         fprintf (stream, "rte");
452       else
453         fprintf (stream, "rts");
454       break;
455     case '#':
456       /* Output a nop if there's nothing in the delay slot.  */
457       if (dbr_sequence_length () == 0)
458         fprintf (stream, "\n\tnop");
459       break;
460     case '\'':
461       {
462         rtx note = find_reg_note (current_output_insn, REG_BR_PROB, 0);
463
464         if (note && INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
465           fputs ("/u", stream);
466         break;
467       }
468     case 'O':
469       x = mark_constant_pool_use (x);
470       output_addr_const (stream, x);
471       break;
472     case 'R':
473       fputs (reg_names[REGNO (x) + LSW], (stream));
474       break;
475     case 'S':
476       fputs (reg_names[REGNO (x) + MSW], (stream));
477       break;
478     case 'T':
479       /* Next word of a double.  */
480       switch (GET_CODE (x))
481         {
482         case REG:
483           fputs (reg_names[REGNO (x) + 1], (stream));
484           break;
485         case MEM:
486           if (GET_CODE (XEXP (x, 0)) != PRE_DEC
487               && GET_CODE (XEXP (x, 0)) != POST_INC)
488             x = adjust_address (x, SImode, 4);
489           print_operand_address (stream, XEXP (x, 0));
490           break;
491         default:
492           break;
493         }
494       break;
495     case 'o':
496       switch (GET_CODE (x))
497         {
498         case PLUS:  fputs ("add", stream); break;
499         case MINUS: fputs ("sub", stream); break;
500         case MULT:  fputs ("mul", stream); break;
501         case DIV:   fputs ("div", stream); break;
502         case EQ:    fputs ("eq",  stream); break;
503         case NE:    fputs ("ne",  stream); break;
504         case GT:  case LT:  fputs ("gt",  stream); break;
505         case GE:  case LE:  fputs ("ge",  stream); break;
506         case GTU: case LTU: fputs ("gtu", stream); break;
507         case GEU: case LEU: fputs ("geu", stream); break;
508         default:
509           break;
510         }
511       break;
512     case 'M':
513       if (GET_CODE (x) == MEM
514           && GET_CODE (XEXP (x, 0)) == PLUS
515           && (GET_CODE (XEXP (XEXP (x, 0), 1)) == REG
516               || GET_CODE (XEXP (XEXP (x, 0), 1)) == SUBREG))
517         fputc ('x', stream);
518       break;
519
520     case 'm':
521       if (GET_CODE (x) != MEM)
522         abort ();
523       x = XEXP (x, 0);
524       switch (GET_CODE (x))
525         {
526         case REG:
527         case SUBREG:
528           print_operand (stream, x, 0);
529           fputs (", 0", stream);
530           break;
531
532         case PLUS:
533           print_operand (stream, XEXP (x, 0), 0);
534           fputs (", ", stream);
535           print_operand (stream, XEXP (x, 1), 0);
536           break;
537
538         default:
539           abort ();
540         }
541       break;
542
543     case 'N':
544       if (x == CONST0_RTX (GET_MODE (x)))
545         {
546           fprintf ((stream), "r63");
547           break;
548         }
549       goto default_output;
550     case 'u':
551       if (GET_CODE (x) == CONST_INT)
552         {
553           fprintf ((stream), "%u", (unsigned) INTVAL (x) & (0x10000 - 1));
554           break;
555         }
556       /* Fall through.  */
557
558     default_output:
559     default:
560       switch (GET_CODE (x))
561         {
562           /* FIXME: We need this on SHmedia32 because reload generates
563              some sign-extended HI or QI loads into DImode registers
564              but, because Pmode is SImode, the address ends up with a
565              subreg:SI of the DImode register.  Maybe reload should be
566              fixed so as to apply alter_subreg to such loads?  */
567         case SUBREG:
568           if (SUBREG_BYTE (x) != 0
569               || GET_CODE (SUBREG_REG (x)) != REG)
570             abort ();
571
572           x = SUBREG_REG (x);
573           /* Fall through.  */
574
575         case REG:
576           if (FP_REGISTER_P (REGNO (x))
577               && GET_MODE (x) == V16SFmode)
578             fprintf ((stream), "mtrx%s", reg_names[REGNO (x)] + 2);
579           else if (FP_REGISTER_P (REGNO (x))
580                    && GET_MODE (x) == V4SFmode)
581             fprintf ((stream), "fv%s", reg_names[REGNO (x)] + 2);
582           else if (GET_CODE (x) == REG
583                    && GET_MODE (x) == V2SFmode)
584             fprintf ((stream), "fp%s", reg_names[REGNO (x)] + 2);
585           else if (FP_REGISTER_P (REGNO (x))
586                    && GET_MODE_SIZE (GET_MODE (x)) > 4)
587             fprintf ((stream), "d%s", reg_names[REGNO (x)] + 1);
588           else
589             fputs (reg_names[REGNO (x)], (stream));
590           break;
591
592         case MEM:
593           output_address (XEXP (x, 0));
594           break;
595           
596         case CONST:
597           if (TARGET_SHMEDIA
598               && GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
599               && GET_MODE (XEXP (x, 0)) == DImode
600               && GET_CODE (XEXP (XEXP (x, 0), 0)) == TRUNCATE
601               && GET_MODE (XEXP (XEXP (x, 0), 0)) == HImode)
602             {
603               rtx val = XEXP (XEXP (XEXP (x, 0), 0), 0);
604
605               fputc ('(', stream);
606               if (GET_CODE (val) == ASHIFTRT)
607                 {
608                   fputc ('(', stream);
609                   if (GET_CODE (XEXP (val, 0)) == CONST)
610                     fputc ('(', stream);
611                   output_addr_const (stream, XEXP (val, 0));
612                   if (GET_CODE (XEXP (val, 0)) == CONST)
613                     fputc (')', stream);
614                   fputs (" >> ", stream);
615                   output_addr_const (stream, XEXP (val, 1));
616                   fputc (')', stream);
617                 }
618               else
619                 {
620                   if (GET_CODE (val) == CONST)
621                     fputc ('(', stream);
622                   output_addr_const (stream, val);
623                   if (GET_CODE (val) == CONST)
624                     fputc (')', stream);
625                 }
626               fputs (" & 65535)", stream);
627               break;
628             }
629
630           /* Fall through.  */
631         default:
632           if (TARGET_SH1)
633             fputc ('#', stream);
634           output_addr_const (stream, x);
635           break;
636         }
637       break;
638     }
639 }
640 \f
641 /* Like force_operand, but guarantees that VALUE ends up in TARGET.  */
642 static void
643 force_into (rtx value, rtx target)
644 {
645   value = force_operand (value, target);
646   if (! rtx_equal_p (value, target))
647     emit_insn (gen_move_insn (target, value));
648 }
649
650 /* Emit code to perform a block move.  Choose the best method.
651
652    OPERANDS[0] is the destination.
653    OPERANDS[1] is the source.
654    OPERANDS[2] is the size.
655    OPERANDS[3] is the alignment safe to use.  */
656
657 int
658 expand_block_move (rtx *operands)
659 {
660   int align = INTVAL (operands[3]);
661   int constp = (GET_CODE (operands[2]) == CONST_INT);
662   int bytes = (constp ? INTVAL (operands[2]) : 0);
663
664   /* If it isn't a constant number of bytes, or if it doesn't have 4 byte
665      alignment, or if it isn't a multiple of 4 bytes, then fail.  */
666   if (! constp || align < 4 || (bytes % 4 != 0))
667     return 0;
668
669   if (TARGET_HARD_SH4)
670     {
671       if (bytes < 12)
672         return 0;
673       else if (bytes == 12)
674         {
675           tree entry_name;
676           rtx sym;
677           rtx func_addr_rtx;
678           rtx r4 = gen_rtx (REG, SImode, 4);
679           rtx r5 = gen_rtx (REG, SImode, 5);
680
681           entry_name = get_identifier ("__movstrSI12_i4");
682
683           sym = function_symbol (IDENTIFIER_POINTER (entry_name));
684           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
685           force_into (XEXP (operands[0], 0), r4);
686           force_into (XEXP (operands[1], 0), r5);
687           emit_insn (gen_block_move_real_i4 (func_addr_rtx));
688           return 1;
689         }
690       else if (! TARGET_SMALLCODE)
691         {
692           tree entry_name;
693           rtx sym;
694           rtx func_addr_rtx;
695           int dwords;
696           rtx r4 = gen_rtx (REG, SImode, 4);
697           rtx r5 = gen_rtx (REG, SImode, 5);
698           rtx r6 = gen_rtx (REG, SImode, 6);
699
700           entry_name = get_identifier (bytes & 4
701                                        ? "__movstr_i4_odd"
702                                        : "__movstr_i4_even");
703           sym = function_symbol (IDENTIFIER_POINTER (entry_name));
704           func_addr_rtx = copy_to_mode_reg (Pmode, sym);
705           force_into (XEXP (operands[0], 0), r4);
706           force_into (XEXP (operands[1], 0), r5);
707
708           dwords = bytes >> 3;
709           emit_insn (gen_move_insn (r6, GEN_INT (dwords - 1)));
710           emit_insn (gen_block_lump_real_i4 (func_addr_rtx));
711           return 1;
712         }
713       else
714         return 0;
715     }
716   if (bytes < 64)
717     {
718       char entry[30];
719       tree entry_name;
720       rtx sym;
721       rtx func_addr_rtx;
722       rtx r4 = gen_rtx_REG (SImode, 4);
723       rtx r5 = gen_rtx_REG (SImode, 5);
724
725       sprintf (entry, "__movstrSI%d", bytes);
726       entry_name = get_identifier (entry);
727       sym = function_symbol (IDENTIFIER_POINTER (entry_name));
728       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
729       force_into (XEXP (operands[0], 0), r4);
730       force_into (XEXP (operands[1], 0), r5);
731       emit_insn (gen_block_move_real (func_addr_rtx));
732       return 1;
733     }
734
735   /* This is the same number of bytes as a memcpy call, but to a different
736      less common function name, so this will occasionally use more space.  */
737   if (! TARGET_SMALLCODE)
738     {
739       tree entry_name;
740       rtx sym;
741       rtx func_addr_rtx;
742       int final_switch, while_loop;
743       rtx r4 = gen_rtx_REG (SImode, 4);
744       rtx r5 = gen_rtx_REG (SImode, 5);
745       rtx r6 = gen_rtx_REG (SImode, 6);
746
747       entry_name = get_identifier ("__movstr");
748       sym = function_symbol (IDENTIFIER_POINTER (entry_name));
749       func_addr_rtx = copy_to_mode_reg (Pmode, sym);
750       force_into (XEXP (operands[0], 0), r4);
751       force_into (XEXP (operands[1], 0), r5);
752
753       /* r6 controls the size of the move.  16 is decremented from it
754          for each 64 bytes moved.  Then the negative bit left over is used
755          as an index into a list of move instructions.  e.g., a 72 byte move
756          would be set up with size(r6) = 14, for one iteration through the
757          big while loop, and a switch of -2 for the last part.  */
758
759       final_switch = 16 - ((bytes / 4) % 16);
760       while_loop = ((bytes / 4) / 16 - 1) * 16;
761       emit_insn (gen_move_insn (r6, GEN_INT (while_loop + final_switch)));
762       emit_insn (gen_block_lump_real (func_addr_rtx));
763       return 1;
764     }
765
766   return 0;
767 }
768
769 /* Prepare operands for a move define_expand; specifically, one of the
770    operands must be in a register.  */
771
772 int
773 prepare_move_operands (rtx operands[], enum machine_mode mode)
774 {
775   if ((mode == SImode || mode == DImode)
776       && flag_pic
777       && ! ((mode == Pmode || mode == ptr_mode)
778             && tls_symbolic_operand (operands[1], Pmode) != 0))
779     {
780       rtx temp;
781       if (SYMBOLIC_CONST_P (operands[1]))
782         {
783           if (GET_CODE (operands[0]) == MEM)
784             operands[1] = force_reg (Pmode, operands[1]);
785           else if (TARGET_SHMEDIA
786                    && GET_CODE (operands[1]) == LABEL_REF
787                    && target_reg_operand (operands[0], mode))
788             /* It's ok.  */;
789           else
790             {
791               temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
792               operands[1] = legitimize_pic_address (operands[1], mode, temp);
793             }
794         }
795       else if (GET_CODE (operands[1]) == CONST
796                && GET_CODE (XEXP (operands[1], 0)) == PLUS
797                && SYMBOLIC_CONST_P (XEXP (XEXP (operands[1], 0), 0)))
798         {
799           temp = no_new_pseudos ? operands[0] : gen_reg_rtx (Pmode);
800           temp = legitimize_pic_address (XEXP (XEXP (operands[1], 0), 0),
801                                          mode, temp);
802           operands[1] = expand_binop (mode, add_optab, temp,
803                                       XEXP (XEXP (operands[1], 0), 1),
804                                       no_new_pseudos ? temp
805                                       : gen_reg_rtx (Pmode),
806                                       0, OPTAB_LIB_WIDEN);
807         }
808     }
809
810   if (! reload_in_progress && ! reload_completed)
811     {
812       /* Copy the source to a register if both operands aren't registers.  */
813       if (! register_operand (operands[0], mode)
814           && ! sh_register_operand (operands[1], mode))
815         operands[1] = copy_to_mode_reg (mode, operands[1]);
816
817       if (GET_CODE (operands[0]) == MEM && ! memory_operand (operands[0], mode))
818         {
819           /* This is like change_address_1 (operands[0], mode, 0, 1) ,
820              except that we can't use that function because it is static.  */
821           rtx new = change_address (operands[0], mode, 0);
822           MEM_COPY_ATTRIBUTES (new, operands[0]);
823           operands[0] = new;
824         }
825
826       /* This case can happen while generating code to move the result
827          of a library call to the target.  Reject `st r0,@(rX,rY)' because
828          reload will fail to find a spill register for rX, since r0 is already
829          being used for the source.  */
830       else if (refers_to_regno_p (R0_REG, R0_REG + 1, operands[1], (rtx *)0)
831                && GET_CODE (operands[0]) == MEM
832                && GET_CODE (XEXP (operands[0], 0)) == PLUS
833                && GET_CODE (XEXP (XEXP (operands[0], 0), 1)) == REG)
834         operands[1] = copy_to_mode_reg (mode, operands[1]);
835     }
836
837   if (mode == Pmode || mode == ptr_mode)
838     {
839       rtx op0, op1;
840       enum tls_model tls_kind;
841
842       op0 = operands[0];
843       op1 = operands[1];
844       if ((tls_kind = tls_symbolic_operand (op1, Pmode)))
845         {
846           rtx tga_op1, tga_ret, tmp, tmp2;
847
848           
849           switch (tls_kind)
850             {
851             case TLS_MODEL_GLOBAL_DYNAMIC:
852               tga_ret = gen_rtx_REG (Pmode, R0_REG);
853               emit_insn (gen_tls_global_dynamic (tga_ret, op1));
854               op1 = tga_ret;
855               break;
856
857             case TLS_MODEL_LOCAL_DYNAMIC:
858               tga_ret = gen_rtx_REG (Pmode, R0_REG);
859               emit_insn (gen_tls_local_dynamic (tga_ret, op1));
860
861               tmp = gen_reg_rtx (Pmode);
862               emit_move_insn (tmp, tga_ret);
863
864               if (register_operand (op0, Pmode))
865                 tmp2 = op0;
866               else
867                 tmp2 = gen_reg_rtx (Pmode);
868
869               emit_insn (gen_symDTPOFF2reg (tmp2, op1, tmp));
870               op1 = tmp2;
871               break;
872
873             case TLS_MODEL_INITIAL_EXEC:
874               if (! flag_pic)
875                 emit_insn (gen_GOTaddr2picreg ());
876               tga_op1 = gen_reg_rtx (Pmode);
877               tmp = gen_sym2GOTTPOFF (op1);
878               emit_insn (gen_tls_initial_exec (tga_op1, tmp));
879               op1 = tga_op1;
880               break;
881
882             case TLS_MODEL_LOCAL_EXEC:
883               tmp2 = gen_reg_rtx (Pmode);
884               emit_insn (gen_load_gbr (tmp2));
885               tmp = gen_reg_rtx (Pmode);
886               emit_insn (gen_symTPOFF2reg (tmp, op1));
887               RTX_UNCHANGING_P (tmp) = 1;
888
889               if (register_operand (op0, Pmode))
890                 op1 = op0;
891               else
892                 op1 = gen_reg_rtx (Pmode);
893
894               emit_insn (gen_addsi3 (op1, tmp, tmp2));
895               break;
896
897             default:
898               abort ();
899             }
900           operands[1] = op1;
901         }
902     }
903
904   return 0;
905 }
906
907 /* Prepare the operands for an scc instruction; make sure that the
908    compare has been done.  */
909 rtx
910 prepare_scc_operands (enum rtx_code code)
911 {
912   rtx t_reg = gen_rtx_REG (SImode, T_REG);
913   enum rtx_code oldcode = code;
914   enum machine_mode mode;
915
916   /* First need a compare insn.  */
917   switch (code)
918     {
919     case NE:
920       /* It isn't possible to handle this case.  */
921       abort ();
922     case LT:
923       code = GT;
924       break;
925     case LE:
926       code = GE;
927       break;
928     case LTU:
929       code = GTU;
930       break;
931     case LEU:
932       code = GEU;
933       break;
934     default:
935       break;
936     }
937   if (code != oldcode)
938     {
939       rtx tmp = sh_compare_op0;
940       sh_compare_op0 = sh_compare_op1;
941       sh_compare_op1 = tmp;
942     }
943
944   mode = GET_MODE (sh_compare_op0);
945   if (mode == VOIDmode)
946     mode = GET_MODE (sh_compare_op1);
947
948   sh_compare_op0 = force_reg (mode, sh_compare_op0);
949   if ((code != EQ && code != NE
950        && (sh_compare_op1 != const0_rtx
951            || code == GTU  || code == GEU || code == LTU || code == LEU))
952       || (mode == DImode && sh_compare_op1 != const0_rtx)
953       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
954     sh_compare_op1 = force_reg (mode, sh_compare_op1);
955
956   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
957     (mode == SFmode ? emit_sf_insn : emit_df_insn)
958      (gen_rtx (PARALLEL, VOIDmode, gen_rtvec (2,
959                 gen_rtx (SET, VOIDmode, t_reg,
960                          gen_rtx (code, SImode,
961                                   sh_compare_op0, sh_compare_op1)),
962                 gen_rtx (USE, VOIDmode, get_fpscr_rtx ()))));
963   else
964     emit_insn (gen_rtx (SET, VOIDmode, t_reg,
965                         gen_rtx (code, SImode, sh_compare_op0,
966                                  sh_compare_op1)));
967
968   return t_reg;
969 }
970
971 /* Called from the md file, set up the operands of a compare instruction.  */
972
973 void
974 from_compare (rtx *operands, int code)
975 {
976   enum machine_mode mode = GET_MODE (sh_compare_op0);
977   rtx insn;
978   if (mode == VOIDmode)
979     mode = GET_MODE (sh_compare_op1);
980   if (code != EQ
981       || mode == DImode
982       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
983     {
984       /* Force args into regs, since we can't use constants here.  */
985       sh_compare_op0 = force_reg (mode, sh_compare_op0);
986       if (sh_compare_op1 != const0_rtx
987           || code == GTU  || code == GEU
988           || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
989         sh_compare_op1 = force_reg (mode, sh_compare_op1);
990     }
991   if (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT && code == GE)
992     {
993       from_compare (operands, GT);
994       insn = gen_ieee_ccmpeqsf_t (sh_compare_op0, sh_compare_op1);
995     }
996   else
997     insn = gen_rtx_SET (VOIDmode,
998                         gen_rtx_REG (SImode, T_REG),
999                         gen_rtx (code, SImode, sh_compare_op0,
1000                                  sh_compare_op1));
1001   if (TARGET_SH4 && GET_MODE_CLASS (mode) == MODE_FLOAT)
1002     {
1003       insn = gen_rtx (PARALLEL, VOIDmode,
1004                       gen_rtvec (2, insn,
1005                                  gen_rtx (USE, VOIDmode, get_fpscr_rtx ())));
1006       (mode == SFmode ? emit_sf_insn : emit_df_insn) (insn);
1007     }
1008   else
1009     emit_insn (insn);
1010 }
1011 \f
1012 /* Functions to output assembly code.  */
1013
1014 /* Return a sequence of instructions to perform DI or DF move.
1015
1016    Since the SH cannot move a DI or DF in one instruction, we have
1017    to take care when we see overlapping source and dest registers.  */
1018
1019 const char *
1020 output_movedouble (rtx insn ATTRIBUTE_UNUSED, rtx operands[],
1021                    enum machine_mode mode)
1022 {
1023   rtx dst = operands[0];
1024   rtx src = operands[1];
1025
1026   if (GET_CODE (dst) == MEM
1027       && GET_CODE (XEXP (dst, 0)) == PRE_DEC)
1028     return "mov.l       %T1,%0\n\tmov.l %1,%0";
1029
1030   if (register_operand (dst, mode)
1031       && register_operand (src, mode))
1032     {
1033       if (REGNO (src) == MACH_REG)
1034         return "sts     mach,%S0\n\tsts macl,%R0";
1035
1036       /* When mov.d r1,r2 do r2->r3 then r1->r2;
1037          when mov.d r1,r0 do r1->r0 then r2->r1.  */
1038
1039       if (REGNO (src) + 1 == REGNO (dst))
1040         return "mov     %T1,%T0\n\tmov  %1,%0";
1041       else
1042         return "mov     %1,%0\n\tmov    %T1,%T0";
1043     }
1044   else if (GET_CODE (src) == CONST_INT)
1045     {
1046       if (INTVAL (src) < 0)
1047         output_asm_insn ("mov   #-1,%S0", operands);
1048       else
1049         output_asm_insn ("mov   #0,%S0", operands);
1050
1051       return "mov       %1,%R0";
1052     }
1053   else if (GET_CODE (src) == MEM)
1054     {
1055       int ptrreg = -1;
1056       int dreg = REGNO (dst);
1057       rtx inside = XEXP (src, 0);
1058
1059       if (GET_CODE (inside) == REG)
1060         ptrreg = REGNO (inside);
1061       else if (GET_CODE (inside) == SUBREG)
1062         ptrreg = subreg_regno (inside);
1063       else if (GET_CODE (inside) == PLUS)
1064         {
1065           ptrreg = REGNO (XEXP (inside, 0));
1066           /* ??? A r0+REG address shouldn't be possible here, because it isn't
1067              an offsettable address.  Unfortunately, offsettable addresses use
1068              QImode to check the offset, and a QImode offsettable address
1069              requires r0 for the other operand, which is not currently
1070              supported, so we can't use the 'o' constraint.
1071              Thus we must check for and handle r0+REG addresses here.
1072              We punt for now, since this is likely very rare.  */
1073           if (GET_CODE (XEXP (inside, 1)) == REG)
1074             abort ();
1075         }
1076       else if (GET_CODE (inside) == LABEL_REF)
1077         return "mov.l   %1,%0\n\tmov.l  %1+4,%T0";
1078       else if (GET_CODE (inside) == POST_INC)
1079         return "mov.l   %1,%0\n\tmov.l  %1,%T0";
1080       else
1081         abort ();
1082
1083       /* Work out the safe way to copy.  Copy into the second half first.  */
1084       if (dreg == ptrreg)
1085         return "mov.l   %T1,%T0\n\tmov.l        %1,%0";
1086     }
1087
1088   return "mov.l %1,%0\n\tmov.l  %T1,%T0";
1089 }
1090
1091 /* Print an instruction which would have gone into a delay slot after
1092    another instruction, but couldn't because the other instruction expanded
1093    into a sequence where putting the slot insn at the end wouldn't work.  */
1094
1095 static void
1096 print_slot (rtx insn)
1097 {
1098   final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file, optimize, 0, 1);
1099
1100   INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
1101 }
1102
1103 const char *
1104 output_far_jump (rtx insn, rtx op)
1105 {
1106   struct { rtx lab, reg, op; } this;
1107   rtx braf_base_lab = NULL_RTX;
1108   const char *jump;
1109   int far;
1110   int offset = branch_dest (insn) - INSN_ADDRESSES (INSN_UID (insn));
1111   rtx prev;
1112
1113   this.lab = gen_label_rtx ();
1114
1115   if (TARGET_SH2
1116       && offset >= -32764
1117       && offset - get_attr_length (insn) <= 32766)
1118     {
1119       far = 0;
1120       jump = "mov.w     %O0,%1; braf    %1";
1121     }
1122   else
1123     {
1124       far = 1;
1125       if (flag_pic)
1126         {
1127           if (TARGET_SH2)
1128             jump = "mov.l       %O0,%1; braf    %1";
1129           else
1130             jump = "mov.l       r0,@-r15; mova  %O0,r0; mov.l   @r0,%1; add     r0,%1; mov.l    @r15+,r0; jmp   @%1";
1131         }
1132       else
1133         jump = "mov.l   %O0,%1; jmp     @%1";
1134     }
1135   /* If we have a scratch register available, use it.  */
1136   if (GET_CODE ((prev = prev_nonnote_insn (insn))) == INSN
1137       && INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
1138     {
1139       this.reg = SET_DEST (XVECEXP (PATTERN (prev), 0, 0));
1140       if (REGNO (this.reg) == R0_REG && flag_pic && ! TARGET_SH2)
1141         jump = "mov.l   r1,@-r15; mova  %O0,r0; mov.l   @r0,r1; add     r1,r0; mov.l    @r15+,r1; jmp   @%1";
1142       output_asm_insn (jump, &this.lab);
1143       if (dbr_sequence_length ())
1144         print_slot (final_sequence);
1145       else
1146         output_asm_insn ("nop", 0);
1147     }
1148   else
1149     {
1150       /* Output the delay slot insn first if any.  */
1151       if (dbr_sequence_length ())
1152         print_slot (final_sequence);
1153
1154       this.reg = gen_rtx_REG (SImode, 13);
1155       /* We must keep the stack aligned to 8-byte boundaries on SH5.
1156          Fortunately, MACL is fixed and call-clobbered, and we never
1157          need its value across jumps, so save r13 in it instead of in
1158          the stack.  */
1159       if (TARGET_SH5)
1160         output_asm_insn ("lds   r13, macl", 0);
1161       else
1162         output_asm_insn ("mov.l r13,@-r15", 0);
1163       output_asm_insn (jump, &this.lab);
1164       if (TARGET_SH5)
1165         output_asm_insn ("sts   macl, r13", 0);
1166       else
1167         output_asm_insn ("mov.l @r15+,r13", 0);
1168     }
1169   if (far && flag_pic && TARGET_SH2)
1170     {
1171       braf_base_lab = gen_label_rtx ();
1172       (*targetm.asm_out.internal_label) (asm_out_file, "L",
1173                                  CODE_LABEL_NUMBER (braf_base_lab));
1174     }
1175   if (far)
1176     output_asm_insn (".align    2", 0);
1177   (*targetm.asm_out.internal_label) (asm_out_file, "L", CODE_LABEL_NUMBER (this.lab));
1178   this.op = op;
1179   if (far && flag_pic)
1180     {
1181       if (TARGET_SH2)
1182         this.lab = braf_base_lab;
1183       output_asm_insn (".long   %O2-%O0", &this.lab);
1184     }
1185   else
1186     output_asm_insn (far ? ".long       %O2" : ".word %O2-%O0", &this.lab);
1187   return "";
1188 }
1189
1190 /* Local label counter, used for constants in the pool and inside
1191    pattern branches.  */
1192
1193 static int lf = 100;
1194
1195 /* Output code for ordinary branches.  */
1196
1197 const char *
1198 output_branch (int logic, rtx insn, rtx *operands)
1199 {
1200   switch (get_attr_length (insn))
1201     {
1202     case 6:
1203       /* This can happen if filling the delay slot has caused a forward
1204          branch to exceed its range (we could reverse it, but only
1205          when we know we won't overextend other branches; this should
1206          best be handled by relaxation).
1207          It can also happen when other condbranches hoist delay slot insn
1208          from their destination, thus leading to code size increase.
1209          But the branch will still be in the range -4092..+4098 bytes.  */
1210
1211       if (! TARGET_RELAX)
1212         {
1213           int label = lf++;
1214           /* The call to print_slot will clobber the operands.  */
1215           rtx op0 = operands[0];
1216     
1217           /* If the instruction in the delay slot is annulled (true), then
1218              there is no delay slot where we can put it now.  The only safe
1219              place for it is after the label.  final will do that by default.  */
1220     
1221           if (final_sequence
1222               && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
1223             {
1224               asm_fprintf (asm_out_file, "\tb%s%ss\t%LLF%d\n", logic ? "f" : "t",
1225                            ASSEMBLER_DIALECT ? "/" : ".", label);
1226               print_slot (final_sequence);
1227             }
1228           else
1229             asm_fprintf (asm_out_file, "\tb%s\t%LLF%d\n", logic ? "f" : "t", label);
1230     
1231           output_asm_insn ("bra\t%l0", &op0);
1232           fprintf (asm_out_file, "\tnop\n");
1233           (*targetm.asm_out.internal_label)(asm_out_file, "LF", label);
1234     
1235           return "";
1236         }
1237       /* When relaxing, handle this like a short branch.  The linker
1238          will fix it up if it still doesn't fit after relaxation.  */
1239     case 2:
1240       return logic ? "bt%.\t%l0" : "bf%.\t%l0";
1241
1242       /* These are for SH2e, in which we have to account for the
1243          extra nop because of the hardware bug in annulled branches.  */
1244     case 8:
1245       if (! TARGET_RELAX)
1246         {
1247           int label = lf++;
1248
1249           if (final_sequence
1250               && INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0)))
1251             abort ();
1252           asm_fprintf (asm_out_file, "b%s%ss\t%LLF%d\n",
1253                        logic ? "f" : "t",
1254                        ASSEMBLER_DIALECT ? "/" : ".", label);
1255           fprintf (asm_out_file, "\tnop\n");
1256           output_asm_insn ("bra\t%l0", operands);
1257           fprintf (asm_out_file, "\tnop\n");
1258           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
1259
1260           return "";
1261         }
1262       /* When relaxing, fall through.  */
1263     case 4:
1264       {
1265         char buffer[10];
1266         
1267         sprintf (buffer, "b%s%ss\t%%l0",
1268                  logic ? "t" : "f",
1269                  ASSEMBLER_DIALECT ? "/" : ".");
1270         output_asm_insn (buffer, &operands[0]);
1271         return "nop";
1272       }
1273
1274     default:
1275       /* There should be no longer branches now - that would
1276          indicate that something has destroyed the branches set
1277          up in machine_dependent_reorg.  */
1278       abort ();
1279     }
1280 }
1281
1282 const char *
1283 output_branchy_insn (enum rtx_code code, const char *template,
1284                      rtx insn, rtx *operands)
1285 {
1286   rtx next_insn = NEXT_INSN (insn);
1287
1288   if (next_insn && GET_CODE (next_insn) == JUMP_INSN && condjump_p (next_insn))
1289     {
1290       rtx src = SET_SRC (PATTERN (next_insn));
1291       if (GET_CODE (src) == IF_THEN_ELSE && GET_CODE (XEXP (src, 0)) != code)
1292         {
1293           /* Following branch not taken */
1294           operands[9] = gen_label_rtx ();
1295           emit_label_after (operands[9], next_insn);
1296           INSN_ADDRESSES_NEW (operands[9],
1297                               INSN_ADDRESSES (INSN_UID (next_insn))
1298                               + get_attr_length (next_insn));
1299           return template;
1300         }
1301       else
1302         {
1303           int offset = (branch_dest (next_insn)
1304                         - INSN_ADDRESSES (INSN_UID (next_insn)) + 4);
1305           if (offset >= -252 && offset <= 258)
1306             {
1307               if (GET_CODE (src) == IF_THEN_ELSE)
1308                 /* branch_true */
1309                 src = XEXP (src, 1);
1310               operands[9] = src;
1311               return template;
1312             }
1313         }
1314     }
1315   operands[9] = gen_label_rtx ();
1316   emit_label_after (operands[9], insn);
1317   INSN_ADDRESSES_NEW (operands[9],
1318                       INSN_ADDRESSES (INSN_UID (insn))
1319                       + get_attr_length (insn));
1320   return template;
1321 }
1322
1323 const char *
1324 output_ieee_ccmpeq (rtx insn, rtx *operands)
1325 {
1326   return output_branchy_insn (NE, "bt\t%l9\\;fcmp/eq\t%1,%0", insn, operands);
1327 }
1328 \f
1329 /* Output the start of the assembler file.  */
1330
1331 static void
1332 sh_file_start (void)
1333 {
1334   default_file_start ();
1335
1336   if (TARGET_ELF)
1337     /* We need to show the text section with the proper
1338        attributes as in TEXT_SECTION_ASM_OP, before dwarf2out
1339        emits it without attributes in TEXT_SECTION_ASM_OP, else GAS
1340        will complain.  We can teach GAS specifically about the
1341        default attributes for our choice of text section, but
1342        then we would have to change GAS again if/when we change
1343        the text section name.  */
1344     fprintf (asm_out_file, "%s\n", TEXT_SECTION_ASM_OP);
1345   else
1346     /* Switch to the data section so that the coffsem symbol
1347        isn't in the text section.  */
1348     data_section ();
1349
1350   if (TARGET_LITTLE_ENDIAN)
1351     fputs ("\t.little\n", asm_out_file);
1352
1353   if (!TARGET_ELF)
1354     {
1355       if (TARGET_SHCOMPACT)
1356         fputs ("\t.mode\tSHcompact\n", asm_out_file);
1357       else if (TARGET_SHMEDIA)
1358         fprintf (asm_out_file, "\t.mode\tSHmedia\n\t.abi\t%i\n",
1359                  TARGET_SHMEDIA64 ? 64 : 32);
1360     }
1361 }
1362 \f
1363 /* Check if PAT includes UNSPEC_CALLER unspec pattern.  */
1364
1365 static bool
1366 unspec_caller_rtx_p (rtx pat)
1367 {
1368   switch (GET_CODE (pat))
1369     {
1370     case CONST:
1371       return unspec_caller_rtx_p (XEXP (pat, 0));
1372     case PLUS:
1373     case MINUS:
1374       if (unspec_caller_rtx_p (XEXP (pat, 0)))
1375         return true;
1376       return unspec_caller_rtx_p (XEXP (pat, 1));
1377     case UNSPEC:
1378       if (XINT (pat, 1) == UNSPEC_CALLER)
1379         return true;
1380     default:
1381       break;
1382     }
1383
1384   return false;
1385 }
1386
1387 /* Indicate that INSN cannot be duplicated.  This is true for insn
1388    that generates an unique label.  */
1389
1390 static bool
1391 sh_cannot_copy_insn_p (rtx insn)
1392 {
1393   rtx pat;
1394
1395   if (!reload_completed || !flag_pic)
1396     return false;
1397
1398   if (GET_CODE (insn) != INSN)
1399     return false;
1400   if (asm_noperands (insn) >= 0)
1401     return false;
1402
1403   pat = PATTERN (insn);
1404   if (GET_CODE (pat) != SET)
1405     return false;
1406   pat = SET_SRC (pat);
1407
1408   if (unspec_caller_rtx_p (pat))
1409     return true;
1410
1411   return false;
1412 }
1413 \f
1414 /* Actual number of instructions used to make a shift by N.  */
1415 static const char ashiftrt_insns[] =
1416   { 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};
1417
1418 /* Left shift and logical right shift are the same.  */
1419 static const char shift_insns[]    =
1420   { 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};
1421
1422 /* Individual shift amounts needed to get the above length sequences.
1423    One bit right shifts clobber the T bit, so when possible, put one bit
1424    shifts in the middle of the sequence, so the ends are eligible for
1425    branch delay slots.  */
1426 static const short shift_amounts[32][5] = {
1427   {0}, {1}, {2}, {2, 1},
1428   {2, 2}, {2, 1, 2}, {2, 2, 2}, {2, 2, 1, 2},
1429   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1430   {8, 2, 2}, {8, 2, 1, 2}, {8, -2, 8}, {8, -1, 8},
1431   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1432   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1433   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1434   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1435
1436 /* Likewise, but for shift amounts < 16, up to three highmost bits
1437    might be clobbered.  This is typically used when combined with some
1438    kind of sign or zero extension.  */
1439    
1440 static const char ext_shift_insns[]    =
1441   { 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};
1442
1443 static const short ext_shift_amounts[32][4] = {
1444   {0}, {1}, {2}, {2, 1},
1445   {2, 2}, {2, 1, 2}, {8, -2}, {8, -1},
1446   {8}, {8, 1}, {8, 2}, {8, 1, 2},
1447   {8, 2, 2}, {16, -2, -1}, {16, -2}, {16, -1},
1448   {16}, {16, 1}, {16, 2}, {16, 1, 2},
1449   {16, 2, 2}, {16, 2, 1, 2}, {16, -2, 8}, {16, -1, 8},
1450   {16, 8}, {16, 1, 8}, {16, 8, 2}, {16, 8, 1, 2},
1451   {16, 8, 2, 2}, {16, -1, -2, 16}, {16, -2, 16}, {16, -1, 16}};
1452
1453 /* Assuming we have a value that has been sign-extended by at least one bit,
1454    can we use the ext_shift_amounts with the last shift turned to an arithmetic shift
1455    to shift it by N without data loss, and quicker than by other means?  */
1456 #define EXT_SHIFT_SIGNED(n) (((n) | 8) == 15)
1457
1458 /* This is used in length attributes in sh.md to help compute the length
1459    of arbitrary constant shift instructions.  */
1460
1461 int
1462 shift_insns_rtx (rtx insn)
1463 {
1464   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
1465   int shift_count = INTVAL (XEXP (set_src, 1));
1466   enum rtx_code shift_code = GET_CODE (set_src);
1467
1468   switch (shift_code)
1469     {
1470     case ASHIFTRT:
1471       return ashiftrt_insns[shift_count];
1472     case LSHIFTRT:
1473     case ASHIFT:
1474       return shift_insns[shift_count];
1475     default:
1476       abort();
1477     }
1478 }
1479
1480 /* Return the cost of a shift.  */
1481
1482 static inline int
1483 shiftcosts (rtx x)
1484 {
1485   int value;
1486
1487   if (TARGET_SHMEDIA)
1488     return 1;
1489
1490   if (GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
1491     {
1492       if (GET_MODE (x) == DImode
1493           && GET_CODE (XEXP (x, 1)) == CONST_INT
1494           && INTVAL (XEXP (x, 1)) == 1)
1495         return 2;
1496
1497       /* Everything else is invalid, because there is no pattern for it.  */
1498       return 10000;
1499     }
1500   /* If shift by a non constant, then this will be expensive.  */
1501   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1502     return SH_DYNAMIC_SHIFT_COST;
1503
1504   value = INTVAL (XEXP (x, 1));
1505
1506   /* Otherwise, return the true cost in instructions.  */
1507   if (GET_CODE (x) == ASHIFTRT)
1508     {
1509       int cost = ashiftrt_insns[value];
1510       /* If SH3, then we put the constant in a reg and use shad.  */
1511       if (cost > 1 + SH_DYNAMIC_SHIFT_COST)
1512         cost = 1 + SH_DYNAMIC_SHIFT_COST;
1513       return cost;
1514     }
1515   else
1516     return shift_insns[value];
1517 }
1518
1519 /* Return the cost of an AND operation.  */
1520
1521 static inline int
1522 andcosts (rtx x)
1523 {
1524   int i;
1525
1526   /* Anding with a register is a single cycle and instruction.  */
1527   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
1528     return 1;
1529
1530   i = INTVAL (XEXP (x, 1));
1531
1532   if (TARGET_SHMEDIA)
1533     {
1534       if ((GET_CODE (XEXP (x, 1)) == CONST_INT
1535            && CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1))))
1536           || EXTRA_CONSTRAINT_C16 (XEXP (x, 1)))
1537         return 1;
1538       else
1539         return 2;
1540     }
1541
1542   /* These constants are single cycle extu.[bw] instructions.  */
1543   if (i == 0xff || i == 0xffff)
1544     return 1;
1545   /* Constants that can be used in an and immediate instruction in a single
1546      cycle, but this requires r0, so make it a little more expensive.  */
1547   if (CONST_OK_FOR_K08 (i))
1548     return 2;
1549   /* Constants that can be loaded with a mov immediate and an and.
1550      This case is probably unnecessary.  */
1551   if (CONST_OK_FOR_I08 (i))
1552     return 2;
1553   /* Any other constants requires a 2 cycle pc-relative load plus an and.
1554      This case is probably unnecessary.  */
1555   return 3;
1556 }
1557
1558 /* Return the cost of an addition or a subtraction.  */
1559
1560 static inline int
1561 addsubcosts (rtx x)
1562 {
1563   /* Adding a register is a single cycle insn.  */
1564   if (GET_CODE (XEXP (x, 1)) == REG
1565       || GET_CODE (XEXP (x, 1)) == SUBREG)
1566     return 1;
1567
1568   /* Likewise for small constants.  */
1569   if (GET_CODE (XEXP (x, 1)) == CONST_INT
1570       && CONST_OK_FOR_ADD (INTVAL (XEXP (x, 1))))
1571     return 1;
1572
1573   if (TARGET_SHMEDIA)
1574     switch (GET_CODE (XEXP (x, 1)))
1575       {
1576       case CONST:
1577       case LABEL_REF:
1578       case SYMBOL_REF:
1579         return TARGET_SHMEDIA64 ? 5 : 3;
1580
1581       case CONST_INT:
1582         if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1))))
1583           return 2;
1584         else if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1)) >> 16))
1585           return 3;
1586         else if (CONST_OK_FOR_I16 ((INTVAL (XEXP (x, 1)) >> 16) >> 16))
1587           return 4;
1588
1589         /* Fall through.  */
1590       default:
1591           return 5;
1592       }
1593
1594   /* Any other constant requires a 2 cycle pc-relative load plus an
1595      addition.  */
1596   return 3;
1597 }
1598
1599 /* Return the cost of a multiply.  */
1600 static inline int
1601 multcosts (rtx x ATTRIBUTE_UNUSED)
1602 {
1603   if (TARGET_SHMEDIA)
1604     return 3;
1605
1606   if (TARGET_SH2)
1607     {
1608       /* We have a mul insn, so we can never take more than the mul and the
1609          read of the mac reg, but count more because of the latency and extra
1610          reg usage.  */
1611       if (TARGET_SMALLCODE)
1612         return 2;
1613       return 3;
1614     }
1615
1616   /* If we're aiming at small code, then just count the number of
1617      insns in a multiply call sequence.  */
1618   if (TARGET_SMALLCODE)
1619     return 5;
1620
1621   /* Otherwise count all the insns in the routine we'd be calling too.  */
1622   return 20;
1623 }
1624
1625 /* Compute a (partial) cost for rtx X.  Return true if the complete
1626    cost has been computed, and false if subexpressions should be
1627    scanned.  In either case, *TOTAL contains the cost result.  */
1628
1629 static bool
1630 sh_rtx_costs (rtx x, int code, int outer_code, int *total)
1631 {
1632   switch (code)
1633     {
1634     case CONST_INT:
1635       if (TARGET_SHMEDIA)
1636         {
1637           if (INTVAL (x) == 0)
1638             *total = 0;
1639           else if (outer_code == AND && and_operand ((x), DImode))
1640             *total = 0;
1641           else if ((outer_code == IOR || outer_code == XOR
1642                     || outer_code == PLUS)
1643                    && CONST_OK_FOR_I10 (INTVAL (x)))
1644             *total = 0;
1645           else if (CONST_OK_FOR_I16 (INTVAL (x)))
1646             *total = COSTS_N_INSNS (outer_code != SET);
1647           else if (CONST_OK_FOR_I16 (INTVAL (x) >> 16))
1648             *total = COSTS_N_INSNS (2);
1649           else if (CONST_OK_FOR_I16 ((INTVAL (x) >> 16) >> 16))
1650             *total = COSTS_N_INSNS (3);
1651           else
1652             *total = COSTS_N_INSNS (4);
1653           return true;
1654         }
1655       if (CONST_OK_FOR_I08 (INTVAL (x)))
1656         *total = 0;
1657       else if ((outer_code == AND || outer_code == IOR || outer_code == XOR)
1658                && CONST_OK_FOR_K08 (INTVAL (x)))
1659         *total = 1;
1660       else
1661         *total = 8;
1662       return true;
1663
1664     case CONST:
1665     case LABEL_REF:
1666     case SYMBOL_REF:
1667       if (TARGET_SHMEDIA64)
1668         *total = COSTS_N_INSNS (4);
1669       else if (TARGET_SHMEDIA32)
1670         *total = COSTS_N_INSNS (2);
1671       else
1672         *total = 5;
1673       return true;
1674
1675     case CONST_DOUBLE:
1676       if (TARGET_SHMEDIA)
1677         *total = COSTS_N_INSNS (4);
1678       else
1679         *total = 10;
1680       return true;
1681
1682     case PLUS:
1683       *total = COSTS_N_INSNS (addsubcosts (x));
1684       return true;
1685
1686     case AND:
1687       *total = COSTS_N_INSNS (andcosts (x));
1688       return true;
1689
1690     case MULT:
1691       *total = COSTS_N_INSNS (multcosts (x));
1692       return true;
1693
1694     case ASHIFT:
1695     case ASHIFTRT:
1696     case LSHIFTRT:
1697       *total = COSTS_N_INSNS (shiftcosts (x));
1698       return true;
1699
1700     case DIV:
1701     case UDIV:
1702     case MOD:
1703     case UMOD:
1704       *total = COSTS_N_INSNS (20);
1705       return true;
1706
1707     case FLOAT:
1708     case FIX:
1709       *total = 100;
1710       return true;
1711
1712     default:
1713       return false;
1714     }
1715 }
1716
1717 /* Compute the cost of an address.  For the SH, all valid addresses are
1718    the same cost.  Use a slightly higher cost for reg + reg addressing,
1719    since it increases pressure on r0.  */
1720
1721 static int
1722 sh_address_cost (rtx X)
1723 {
1724   return (GET_CODE (X) == PLUS
1725           && ! CONSTANT_P (XEXP (X, 1))
1726           && ! TARGET_SHMEDIA ? 1 : 0);
1727 }
1728
1729 /* Code to expand a shift.  */
1730
1731 void
1732 gen_ashift (int type, int n, rtx reg)
1733 {
1734   /* Negative values here come from the shift_amounts array.  */
1735   if (n < 0)
1736     {
1737       if (type == ASHIFT)
1738         type = LSHIFTRT;
1739       else
1740         type = ASHIFT;
1741       n = -n;
1742     }
1743
1744   switch (type)
1745     {
1746     case ASHIFTRT:
1747       emit_insn (gen_ashrsi3_k (reg, reg, GEN_INT (n)));
1748       break;
1749     case LSHIFTRT:
1750       if (n == 1)
1751         emit_insn (gen_lshrsi3_m (reg, reg, GEN_INT (n)));
1752       else
1753         emit_insn (gen_lshrsi3_k (reg, reg, GEN_INT (n)));
1754       break;
1755     case ASHIFT:
1756       emit_insn (gen_ashlsi3_std (reg, reg, GEN_INT (n)));
1757       break;
1758     }
1759 }
1760
1761 /* Same for HImode */
1762
1763 void
1764 gen_ashift_hi (int type, int n, rtx reg)
1765 {
1766   /* Negative values here come from the shift_amounts array.  */
1767   if (n < 0)
1768     {
1769       if (type == ASHIFT)
1770         type = LSHIFTRT;
1771       else
1772         type = ASHIFT;
1773       n = -n;
1774     }
1775
1776   switch (type)
1777     {
1778     case ASHIFTRT:
1779     case LSHIFTRT:
1780       /* We don't have HImode right shift operations because using the
1781          ordinary 32 bit shift instructions for that doesn't generate proper
1782          zero/sign extension.
1783          gen_ashift_hi is only called in contexts where we know that the
1784          sign extension works out correctly.  */
1785       {
1786         int offset = 0;
1787         if (GET_CODE (reg) == SUBREG)
1788           {
1789             offset = SUBREG_BYTE (reg);
1790             reg = SUBREG_REG (reg);
1791           }
1792         gen_ashift (type, n, gen_rtx_SUBREG (SImode, reg, offset));
1793         break;
1794       }
1795     case ASHIFT:
1796       emit_insn (gen_ashlhi3_k (reg, reg, GEN_INT (n)));
1797       break;
1798     }
1799 }
1800
1801 /* Output RTL to split a constant shift into its component SH constant
1802    shift instructions.  */
1803    
1804 void
1805 gen_shifty_op (int code, rtx *operands)
1806 {
1807   int value = INTVAL (operands[2]);
1808   int max, i;
1809
1810   /* Truncate the shift count in case it is out of bounds.  */
1811   value = value & 0x1f;
1812  
1813   if (value == 31)
1814     {
1815       if (code == LSHIFTRT)
1816         {
1817           emit_insn (gen_rotlsi3_1 (operands[0], operands[0]));
1818           emit_insn (gen_movt (operands[0]));
1819           return;
1820         }
1821       else if (code == ASHIFT)
1822         {
1823           /* There is a two instruction sequence for 31 bit left shifts,
1824              but it requires r0.  */
1825           if (GET_CODE (operands[0]) == REG && REGNO (operands[0]) == 0)
1826             {
1827               emit_insn (gen_andsi3 (operands[0], operands[0], const1_rtx));
1828               emit_insn (gen_rotlsi3_31 (operands[0], operands[0]));
1829               return;
1830             }
1831         }
1832     }
1833   else if (value == 0)
1834     {
1835       /* This can happen when not optimizing.  We must output something here
1836          to prevent the compiler from aborting in final.c after the try_split
1837          call.  */
1838       emit_insn (gen_nop ());
1839       return;
1840     }
1841
1842   max = shift_insns[value];
1843   for (i = 0; i < max; i++)
1844     gen_ashift (code, shift_amounts[value][i], operands[0]);
1845 }
1846    
1847 /* Same as above, but optimized for values where the topmost bits don't
1848    matter.  */
1849
1850 void
1851 gen_shifty_hi_op (int code, rtx *operands)
1852 {
1853   int value = INTVAL (operands[2]);
1854   int max, i;
1855   void (*gen_fun) (int, int, rtx);
1856
1857   /* This operation is used by and_shl for SImode values with a few
1858      high bits known to be cleared.  */
1859   value &= 31;
1860   if (value == 0)
1861     {
1862       emit_insn (gen_nop ());
1863       return;
1864     }
1865
1866   gen_fun = GET_MODE (operands[0]) == HImode ? gen_ashift_hi : gen_ashift;
1867   if (code == ASHIFT)
1868     {
1869       max = ext_shift_insns[value];
1870       for (i = 0; i < max; i++)
1871         gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1872     }
1873   else
1874     /* When shifting right, emit the shifts in reverse order, so that
1875        solitary negative values come first.  */
1876     for (i = ext_shift_insns[value] - 1; i >= 0; i--)
1877       gen_fun (code, ext_shift_amounts[value][i], operands[0]);
1878 }
1879
1880 /* Output RTL for an arithmetic right shift.  */
1881
1882 /* ??? Rewrite to use super-optimizer sequences.  */
1883
1884 int
1885 expand_ashiftrt (rtx *operands)
1886 {
1887   rtx sym;
1888   rtx wrk;
1889   char func[18];
1890   tree func_name;
1891   int value;
1892
1893   if (TARGET_SH3)
1894     {
1895       if (GET_CODE (operands[2]) != CONST_INT)
1896         {
1897           rtx count = copy_to_mode_reg (SImode, operands[2]);
1898           emit_insn (gen_negsi2 (count, count));
1899           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1900           return 1;
1901         }
1902       else if (ashiftrt_insns[INTVAL (operands[2]) & 31]
1903                > 1 + SH_DYNAMIC_SHIFT_COST)
1904         {
1905           rtx count
1906             = force_reg (SImode, GEN_INT (- (INTVAL (operands[2]) & 31)));
1907           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
1908           return 1;
1909         }
1910     }
1911   if (GET_CODE (operands[2]) != CONST_INT)
1912     return 0;
1913
1914   value = INTVAL (operands[2]) & 31;
1915
1916   if (value == 31)
1917     {
1918       emit_insn (gen_ashrsi2_31 (operands[0], operands[1]));
1919       return 1;
1920     }
1921   else if (value >= 16 && value <= 19)
1922     {
1923       wrk = gen_reg_rtx (SImode);
1924       emit_insn (gen_ashrsi2_16 (wrk, operands[1]));
1925       value -= 16;
1926       while (value--)
1927         gen_ashift (ASHIFTRT, 1, wrk);
1928       emit_move_insn (operands[0], wrk);
1929       return 1;
1930     }
1931   /* Expand a short sequence inline, longer call a magic routine.  */
1932   else if (value <= 5)
1933     {
1934       wrk = gen_reg_rtx (SImode);
1935       emit_move_insn (wrk, operands[1]);
1936       while (value--)
1937         gen_ashift (ASHIFTRT, 1, wrk);
1938       emit_move_insn (operands[0], wrk);
1939       return 1;
1940     }
1941
1942   wrk = gen_reg_rtx (Pmode);
1943
1944   /* Load the value into an arg reg and call a helper.  */
1945   emit_move_insn (gen_rtx_REG (SImode, 4), operands[1]);
1946   sprintf (func, "__ashiftrt_r4_%d", value);
1947   func_name = get_identifier (func);
1948   sym = function_symbol (IDENTIFIER_POINTER (func_name));
1949   emit_move_insn (wrk, sym);
1950   emit_insn (gen_ashrsi3_n (GEN_INT (value), wrk));
1951   emit_move_insn (operands[0], gen_rtx_REG (SImode, 4));
1952   return 1;
1953 }
1954
1955 int
1956 sh_dynamicalize_shift_p (rtx count)
1957 {
1958   return shift_insns[INTVAL (count)] > 1 + SH_DYNAMIC_SHIFT_COST;
1959 }
1960
1961 /* Try to find a good way to implement the combiner pattern
1962   [(set (match_operand:SI 0 "register_operand" "r")
1963         (and:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
1964                            (match_operand:SI 2 "const_int_operand" "n"))
1965                 (match_operand:SI 3 "const_int_operand" "n"))) .
1966   LEFT_RTX is operand 2 in the above pattern, and MASK_RTX is operand 3.
1967   return 0 for simple right / left or left/right shift combination.
1968   return 1 for a combination of shifts with zero_extend.
1969   return 2 for a combination of shifts with an AND that needs r0.
1970   return 3 for a combination of shifts with an AND that needs an extra
1971     scratch register, when the three highmost bits of the AND mask are clear.
1972   return 4 for a combination of shifts with an AND that needs an extra
1973     scratch register, when any of the three highmost bits of the AND mask
1974     is set.
1975   If ATTRP is set, store an initial right shift width in ATTRP[0],
1976   and the instruction length in ATTRP[1] .  These values are not valid
1977   when returning 0.
1978   When ATTRP is set and returning 1, ATTRP[2] gets set to the index into
1979   shift_amounts for the last shift value that is to be used before the
1980   sign extend.  */
1981 int
1982 shl_and_kind (rtx left_rtx, rtx mask_rtx, int *attrp)
1983 {
1984   unsigned HOST_WIDE_INT mask, lsb, mask2, lsb2;
1985   int left = INTVAL (left_rtx), right;
1986   int best = 0;
1987   int cost, best_cost = 10000;
1988   int best_right = 0, best_len = 0;
1989   int i;
1990   int can_ext;
1991
1992   if (left < 0 || left > 31)
1993     return 0;
1994   if (GET_CODE (mask_rtx) == CONST_INT)
1995     mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> left;
1996   else
1997     mask = (unsigned HOST_WIDE_INT) GET_MODE_MASK (SImode) >> left;
1998   /* Can this be expressed as a right shift / left shift pair ? */
1999   lsb = ((mask ^ (mask - 1)) >> 1) + 1;
2000   right = exact_log2 (lsb);
2001   mask2 = ~(mask + lsb - 1);
2002   lsb2 = ((mask2 ^ (mask2 - 1)) >> 1) + 1;
2003   /* mask has no zeroes but trailing zeroes <==> ! mask2 */
2004   if (! mask2)
2005     best_cost = shift_insns[right] + shift_insns[right + left];
2006   /* mask has no trailing zeroes <==> ! right */
2007   else if (! right && mask2 == ~(lsb2 - 1))
2008     {
2009       int late_right = exact_log2 (lsb2);
2010       best_cost = shift_insns[left + late_right] + shift_insns[late_right];
2011     }
2012   /* Try to use zero extend */
2013   if (mask2 == ~(lsb2 - 1))
2014     {
2015       int width, first;
2016
2017       for (width = 8; width <= 16; width += 8)
2018         {
2019           /* Can we zero-extend right away? */
2020           if (lsb2 == (unsigned HOST_WIDE_INT)1 << width)
2021             {
2022               cost
2023                 = 1 + ext_shift_insns[right] + ext_shift_insns[left + right];
2024               if (cost < best_cost)
2025                 {
2026                   best = 1;
2027                   best_cost = cost;
2028                   best_right = right;
2029                   best_len = cost;
2030                   if (attrp)
2031                     attrp[2] = -1;
2032                 }
2033               continue;
2034             }
2035           /* ??? Could try to put zero extend into initial right shift,
2036              or even shift a bit left before the right shift.  */
2037           /* Determine value of first part of left shift, to get to the
2038              zero extend cut-off point.  */
2039           first = width - exact_log2 (lsb2) + right;
2040           if (first >= 0 && right + left - first >= 0)
2041             {
2042               cost = ext_shift_insns[right] + ext_shift_insns[first] + 1
2043                 + ext_shift_insns[right + left - first];
2044               if (cost < best_cost)
2045                 {
2046                   best = 1;
2047                   best_cost = cost;
2048                   best_right = right;
2049                   best_len = cost;
2050                   if (attrp)
2051                     attrp[2] = first;
2052                   }
2053             }
2054         }
2055     }
2056   /* Try to use r0 AND pattern */
2057   for (i = 0; i <= 2; i++)
2058     {
2059       if (i > right)
2060         break;
2061       if (! CONST_OK_FOR_K08 (mask >> i))
2062         continue;
2063       cost = (i != 0) + 2 + ext_shift_insns[left + i];
2064       if (cost < best_cost)
2065         {
2066           best = 2;
2067           best_cost = cost;
2068           best_right = i;
2069           best_len = cost - 1;
2070         }
2071     }
2072   /* Try to use a scratch register to hold the AND operand.  */
2073   can_ext = ((mask << left) & ((unsigned HOST_WIDE_INT)3 << 30)) == 0;
2074   for (i = 0; i <= 2; i++)
2075     {
2076       if (i > right)
2077         break;
2078       cost = (i != 0) + (CONST_OK_FOR_I08 (mask >> i) ? 2 : 3)
2079         + (can_ext ? ext_shift_insns : shift_insns)[left + i];
2080       if (cost < best_cost)
2081         {
2082           best = 4 - can_ext;
2083           best_cost = cost;
2084           best_right = i;
2085           best_len = cost - 1 - ! CONST_OK_FOR_I08 (mask >> i);
2086         }
2087     }
2088
2089   if (attrp)
2090     {
2091       attrp[0] = best_right;
2092       attrp[1] = best_len;
2093     }
2094   return best;
2095 }
2096
2097 /* This is used in length attributes of the unnamed instructions
2098    corresponding to shl_and_kind return values of 1 and 2.  */
2099 int
2100 shl_and_length (rtx insn)
2101 {
2102   rtx set_src, left_rtx, mask_rtx;
2103   int attributes[3];
2104
2105   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2106   left_rtx = XEXP (XEXP (set_src, 0), 1);
2107   mask_rtx = XEXP (set_src, 1);
2108   shl_and_kind (left_rtx, mask_rtx, attributes);
2109   return attributes[1];
2110 }
2111
2112 /* This is used in length attribute of the and_shl_scratch instruction.  */
2113
2114 int
2115 shl_and_scr_length (rtx insn)
2116 {
2117   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2118   int len = shift_insns[INTVAL (XEXP (set_src, 1))];
2119   rtx op = XEXP (set_src, 0);
2120   len += shift_insns[INTVAL (XEXP (op, 1))] + 1;
2121   op = XEXP (XEXP (op, 0), 0);
2122   return len + shift_insns[INTVAL (XEXP (op, 1))];
2123 }
2124
2125 /* Generating rtl? */
2126 extern int rtx_equal_function_value_matters;
2127
2128 /* Generate rtl for instructions for which shl_and_kind advised a particular
2129    method of generating them, i.e. returned zero.  */
2130
2131 int
2132 gen_shl_and (rtx dest, rtx left_rtx, rtx mask_rtx, rtx source)
2133 {
2134   int attributes[3];
2135   unsigned HOST_WIDE_INT mask;
2136   int kind = shl_and_kind (left_rtx, mask_rtx, attributes);
2137   int right, total_shift;
2138   void (*shift_gen_fun) (int, rtx*) = gen_shifty_hi_op;
2139
2140   right = attributes[0];
2141   total_shift = INTVAL (left_rtx) + right;
2142   mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> total_shift;
2143   switch (kind)
2144     {
2145     default:
2146       return -1;
2147     case 1:
2148       {
2149         int first = attributes[2];
2150         rtx operands[3];
2151
2152         if (first < 0)
2153           {
2154             emit_insn ((mask << right) <= 0xff
2155                        ? gen_zero_extendqisi2(dest,
2156                                               gen_lowpart (QImode, source))
2157                        : gen_zero_extendhisi2(dest,
2158                                               gen_lowpart (HImode, source)));
2159             source = dest;
2160           }
2161         if (source != dest)
2162           emit_insn (gen_movsi (dest, source));
2163         operands[0] = dest;
2164         if (right)
2165           {
2166             operands[2] = GEN_INT (right);
2167             gen_shifty_hi_op (LSHIFTRT, operands);
2168           }
2169         if (first > 0)
2170           {
2171             operands[2] = GEN_INT (first);
2172             gen_shifty_hi_op (ASHIFT, operands);
2173             total_shift -= first;
2174             mask <<= first;
2175           }
2176         if (first >= 0)
2177           emit_insn (mask <= 0xff
2178                      ? gen_zero_extendqisi2(dest, gen_lowpart (QImode, dest))
2179                      : gen_zero_extendhisi2(dest, gen_lowpart (HImode, dest)));
2180         if (total_shift > 0)
2181           {
2182             operands[2] = GEN_INT (total_shift);
2183             gen_shifty_hi_op (ASHIFT, operands);
2184           }
2185         break;
2186       }
2187     case 4:
2188       shift_gen_fun = gen_shifty_op;
2189     case 3:
2190       /* If the topmost bit that matters is set, set the topmost bits
2191          that don't matter.  This way, we might be able to get a shorter
2192          signed constant.  */
2193       if (mask & ((HOST_WIDE_INT)1 << (31 - total_shift)))
2194         mask |= (HOST_WIDE_INT)~0 << (31 - total_shift);
2195     case 2:
2196       /* Don't expand fine-grained when combining, because that will
2197          make the pattern fail.  */
2198       if (rtx_equal_function_value_matters
2199           || reload_in_progress || reload_completed)
2200         {
2201           rtx operands[3];
2202   
2203           /* Cases 3 and 4 should be handled by this split
2204              only while combining  */
2205           if (kind > 2)
2206             abort ();
2207           if (right)
2208             {
2209               emit_insn (gen_lshrsi3 (dest, source, GEN_INT (right)));
2210               source = dest;
2211             }
2212           emit_insn (gen_andsi3 (dest, source, GEN_INT (mask)));
2213           if (total_shift)
2214             {
2215               operands[0] = dest;
2216               operands[1] = dest;
2217               operands[2] = GEN_INT (total_shift);
2218               shift_gen_fun (ASHIFT, operands);
2219             }
2220           break;
2221         }
2222       else
2223         {
2224           int neg = 0;
2225           if (kind != 4 && total_shift < 16)
2226             {
2227               neg = -ext_shift_amounts[total_shift][1];
2228               if (neg > 0)
2229                 neg -= ext_shift_amounts[total_shift][2];
2230               else
2231                 neg = 0;
2232             }
2233           emit_insn (gen_and_shl_scratch (dest, source,
2234                                           GEN_INT (right),
2235                                           GEN_INT (mask),
2236                                           GEN_INT (total_shift + neg),
2237                                           GEN_INT (neg)));
2238           emit_insn (gen_movsi (dest, dest));
2239           break;
2240         }
2241     }
2242   return 0;
2243 }
2244
2245 /* Try to find a good way to implement the combiner pattern
2246   [(set (match_operand:SI 0 "register_operand" "=r")
2247         (sign_extract:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
2248                                     (match_operand:SI 2 "const_int_operand" "n")
2249                          (match_operand:SI 3 "const_int_operand" "n")
2250                          (const_int 0)))
2251    (clobber (reg:SI T_REG))]
2252   LEFT_RTX is operand 2 in the above pattern, and SIZE_RTX is operand 3.
2253   return 0 for simple left / right shift combination.
2254   return 1 for left shift / 8 bit sign extend / left shift.
2255   return 2 for left shift / 16 bit sign extend / left shift.
2256   return 3 for left shift / 8 bit sign extend / shift / sign extend.
2257   return 4 for left shift / 16 bit sign extend / shift / sign extend.
2258   return 5 for left shift / 16 bit sign extend / right shift
2259   return 6 for < 8 bit sign extend / left shift.
2260   return 7 for < 8 bit sign extend / left shift / single right shift.
2261   If COSTP is nonzero, assign the calculated cost to *COSTP.  */
2262
2263 int
2264 shl_sext_kind (rtx left_rtx, rtx size_rtx, int *costp)
2265 {
2266   int left, size, insize, ext;
2267   int cost = 0, best_cost;
2268   int kind;
2269
2270   left = INTVAL (left_rtx);
2271   size = INTVAL (size_rtx);
2272   insize = size - left;
2273   if (insize <= 0)
2274     abort ();
2275   /* Default to left / right shift.  */
2276   kind = 0;
2277   best_cost = shift_insns[32 - insize] + ashiftrt_insns[32 - size];
2278   if (size <= 16)
2279     {
2280       /* 16 bit shift / sign extend / 16 bit shift */
2281       cost = shift_insns[16 - insize] + 1 + ashiftrt_insns[16 - size];
2282       /* If ashiftrt_insns[16 - size] is 8, this choice will be overridden
2283          below, by alternative 3 or something even better.  */
2284       if (cost < best_cost)
2285         {
2286           kind = 5;
2287           best_cost = cost;
2288         }
2289     }
2290   /* Try a plain sign extend between two shifts.  */
2291   for (ext = 16; ext >= insize; ext -= 8)
2292     {
2293       if (ext <= size)
2294         {
2295           cost = ext_shift_insns[ext - insize] + 1 + shift_insns[size - ext];
2296           if (cost < best_cost)
2297             {
2298               kind = ext / (unsigned) 8;
2299               best_cost = cost;
2300             }
2301         }
2302       /* Check if we can do a sloppy shift with a final signed shift
2303          restoring the sign.  */
2304       if (EXT_SHIFT_SIGNED (size - ext))
2305         cost = ext_shift_insns[ext - insize] + ext_shift_insns[size - ext] + 1;
2306       /* If not, maybe it's still cheaper to do the second shift sloppy,
2307          and do a final sign extend?  */
2308       else if (size <= 16)
2309         cost = ext_shift_insns[ext - insize] + 1
2310           + ext_shift_insns[size > ext ? size - ext : ext - size] + 1;
2311       else
2312         continue;
2313       if (cost < best_cost)
2314         {
2315           kind = ext / (unsigned) 8 + 2;
2316           best_cost = cost;
2317         }
2318     }
2319   /* Check if we can sign extend in r0 */
2320   if (insize < 8)
2321     {
2322       cost = 3 + shift_insns[left];
2323       if (cost < best_cost)
2324         {
2325           kind = 6;
2326           best_cost = cost;
2327         }
2328       /* Try the same with a final signed shift.  */
2329       if (left < 31)
2330         {
2331           cost = 3 + ext_shift_insns[left + 1] + 1;
2332           if (cost < best_cost)
2333             {
2334               kind = 7;
2335               best_cost = cost;
2336             }
2337         }
2338     }
2339   if (TARGET_SH3)
2340     {
2341       /* Try to use a dynamic shift.  */
2342       cost = shift_insns[32 - insize] + 1 + SH_DYNAMIC_SHIFT_COST;
2343       if (cost < best_cost)
2344         {
2345           kind = 0;
2346           best_cost = cost;
2347         }
2348     }
2349   if (costp)
2350     *costp = cost;
2351   return kind;
2352 }
2353
2354 /* Function to be used in the length attribute of the instructions
2355    implementing this pattern.  */
2356
2357 int
2358 shl_sext_length (rtx insn)
2359 {
2360   rtx set_src, left_rtx, size_rtx;
2361   int cost;
2362
2363   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
2364   left_rtx = XEXP (XEXP (set_src, 0), 1);
2365   size_rtx = XEXP (set_src, 1);
2366   shl_sext_kind (left_rtx, size_rtx, &cost);
2367   return cost;
2368 }
2369
2370 /* Generate rtl for this pattern */
2371
2372 int
2373 gen_shl_sext (rtx dest, rtx left_rtx, rtx size_rtx, rtx source)
2374 {
2375   int kind;
2376   int left, size, insize, cost;
2377   rtx operands[3];
2378
2379   kind = shl_sext_kind (left_rtx, size_rtx, &cost);
2380   left = INTVAL (left_rtx);
2381   size = INTVAL (size_rtx);
2382   insize = size - left;
2383   switch (kind)
2384     {
2385     case 1:
2386     case 2:
2387     case 3:
2388     case 4:
2389       {
2390         int ext = kind & 1 ? 8 : 16;
2391         int shift2 = size - ext;
2392
2393         /* Don't expand fine-grained when combining, because that will
2394            make the pattern fail.  */
2395         if (! rtx_equal_function_value_matters
2396             && ! reload_in_progress && ! reload_completed)
2397           {
2398             emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2399             emit_insn (gen_movsi (dest, source));
2400             break;
2401           }
2402         if (dest != source)
2403           emit_insn (gen_movsi (dest, source));
2404         operands[0] = dest;
2405         if (ext - insize)
2406           {
2407             operands[2] = GEN_INT (ext - insize);
2408             gen_shifty_hi_op (ASHIFT, operands);
2409           }
2410         emit_insn (kind & 1
2411                    ? gen_extendqisi2(dest, gen_lowpart (QImode, dest))
2412                    : gen_extendhisi2(dest, gen_lowpart (HImode, dest)));
2413         if (kind <= 2)
2414           {
2415             if (shift2)
2416               {
2417                 operands[2] = GEN_INT (shift2);
2418                 gen_shifty_op (ASHIFT, operands);
2419               }
2420           }
2421         else
2422           {
2423             if (shift2 > 0)
2424               {
2425                 if (EXT_SHIFT_SIGNED (shift2))
2426                   {
2427                     operands[2] = GEN_INT (shift2 + 1);
2428                     gen_shifty_op (ASHIFT, operands);
2429                     operands[2] = GEN_INT (1);
2430                     gen_shifty_op (ASHIFTRT, operands);
2431                     break;
2432                   }
2433                 operands[2] = GEN_INT (shift2);
2434                 gen_shifty_hi_op (ASHIFT, operands);
2435               }
2436             else if (shift2)
2437               {
2438                 operands[2] = GEN_INT (-shift2);
2439                 gen_shifty_hi_op (LSHIFTRT, operands);
2440               }
2441             emit_insn (size <= 8
2442                        ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
2443                        : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2444           }
2445         break;
2446       }
2447     case 5:
2448       {
2449         int i = 16 - size;
2450         if (! rtx_equal_function_value_matters
2451             && ! reload_in_progress && ! reload_completed)
2452           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2453         else
2454           {
2455             operands[0] = dest;
2456             operands[2] = GEN_INT (16 - insize);
2457             gen_shifty_hi_op (ASHIFT, operands);
2458             emit_insn (gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
2459           }
2460         /* Don't use gen_ashrsi3 because it generates new pseudos.  */
2461         while (--i >= 0)
2462           gen_ashift (ASHIFTRT, 1, dest);
2463         break;
2464       }
2465     case 6:
2466     case 7:
2467       /* Don't expand fine-grained when combining, because that will
2468          make the pattern fail.  */
2469       if (! rtx_equal_function_value_matters
2470           && ! reload_in_progress && ! reload_completed)
2471         {
2472           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
2473           emit_insn (gen_movsi (dest, source));
2474           break;
2475         }
2476       emit_insn (gen_andsi3 (dest, source, GEN_INT ((1 << insize) - 1)));
2477       emit_insn (gen_xorsi3 (dest, dest, GEN_INT (1 << (insize - 1))));
2478       emit_insn (gen_addsi3 (dest, dest, GEN_INT (-1 << (insize - 1))));
2479       operands[0] = dest;
2480       operands[2] = kind == 7 ? GEN_INT (left + 1) : left_rtx;
2481       gen_shifty_op (ASHIFT, operands);
2482       if (kind == 7)
2483         emit_insn (gen_ashrsi3_k (dest, dest, GEN_INT (1)));
2484       break;
2485     default:
2486       return -1;
2487     }
2488   return 0;
2489 }
2490
2491 /* Prefix a symbol_ref name with "datalabel".  */
2492
2493 rtx
2494 gen_datalabel_ref (rtx sym)
2495 {
2496   if (GET_CODE (sym) == LABEL_REF)
2497     return gen_rtx_CONST (GET_MODE (sym),
2498                           gen_rtx_UNSPEC (GET_MODE (sym),
2499                                           gen_rtvec (1, sym),
2500                                           UNSPEC_DATALABEL));
2501     
2502   if (GET_CODE (sym) != SYMBOL_REF)
2503     abort ();
2504
2505   return sym;
2506 }
2507
2508 \f
2509 /* The SH cannot load a large constant into a register, constants have to
2510    come from a pc relative load.  The reference of a pc relative load
2511    instruction must be less than 1k infront of the instruction.  This
2512    means that we often have to dump a constant inside a function, and
2513    generate code to branch around it.
2514
2515    It is important to minimize this, since the branches will slow things
2516    down and make things bigger.
2517
2518    Worst case code looks like:
2519
2520    mov.l L1,rn
2521    bra   L2
2522    nop
2523    align
2524    L1:   .long value
2525    L2:
2526    ..
2527
2528    mov.l L3,rn
2529    bra   L4
2530    nop
2531    align
2532    L3:   .long value
2533    L4:
2534    ..
2535
2536    We fix this by performing a scan before scheduling, which notices which
2537    instructions need to have their operands fetched from the constant table
2538    and builds the table.
2539
2540    The algorithm is:
2541
2542    scan, find an instruction which needs a pcrel move.  Look forward, find the
2543    last barrier which is within MAX_COUNT bytes of the requirement.
2544    If there isn't one, make one.  Process all the instructions between
2545    the find and the barrier.
2546
2547    In the above example, we can tell that L3 is within 1k of L1, so
2548    the first move can be shrunk from the 3 insn+constant sequence into
2549    just 1 insn, and the constant moved to L3 to make:
2550
2551    mov.l        L1,rn
2552    ..
2553    mov.l        L3,rn
2554    bra          L4
2555    nop
2556    align
2557    L3:.long value
2558    L4:.long value
2559
2560    Then the second move becomes the target for the shortening process.  */
2561
2562 typedef struct
2563 {
2564   rtx value;                    /* Value in table.  */
2565   rtx label;                    /* Label of value.  */
2566   rtx wend;                     /* End of window.  */
2567   enum machine_mode mode;       /* Mode of value.  */
2568
2569   /* True if this constant is accessed as part of a post-increment
2570      sequence.  Note that HImode constants are never accessed in this way.  */
2571   bool part_of_sequence_p;
2572 } pool_node;
2573
2574 /* The maximum number of constants that can fit into one pool, since
2575    the pc relative range is 0...1020 bytes and constants are at least 4
2576    bytes long.  */
2577
2578 #define MAX_POOL_SIZE (1020/4)
2579 static pool_node pool_vector[MAX_POOL_SIZE];
2580 static int pool_size;
2581 static rtx pool_window_label;
2582 static int pool_window_last;
2583
2584 /* ??? If we need a constant in HImode which is the truncated value of a
2585    constant we need in SImode, we could combine the two entries thus saving
2586    two bytes.  Is this common enough to be worth the effort of implementing
2587    it?  */
2588
2589 /* ??? This stuff should be done at the same time that we shorten branches.
2590    As it is now, we must assume that all branches are the maximum size, and
2591    this causes us to almost always output constant pools sooner than
2592    necessary.  */
2593
2594 /* Add a constant to the pool and return its label.  */
2595
2596 static rtx
2597 add_constant (rtx x, enum machine_mode mode, rtx last_value)
2598 {
2599   int i;
2600   rtx lab, new, ref, newref;
2601
2602   /* First see if we've already got it.  */
2603   for (i = 0; i < pool_size; i++)
2604     {
2605       if (x->code == pool_vector[i].value->code
2606           && mode == pool_vector[i].mode)
2607         {
2608           if (x->code == CODE_LABEL)
2609             {
2610               if (XINT (x, 3) != XINT (pool_vector[i].value, 3))
2611                 continue;
2612             }
2613           if (rtx_equal_p (x, pool_vector[i].value))
2614             {
2615               lab = new = 0;
2616               if (! last_value
2617                   || ! i
2618                   || ! rtx_equal_p (last_value, pool_vector[i-1].value))
2619                 {
2620                   new = gen_label_rtx ();
2621                   LABEL_REFS (new) = pool_vector[i].label;
2622                   pool_vector[i].label = lab = new;
2623                 }
2624               if (lab && pool_window_label)
2625                 {
2626                   newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2627                   ref = pool_vector[pool_window_last].wend;
2628                   LABEL_NEXTREF (newref) = ref;
2629                   pool_vector[pool_window_last].wend = newref;
2630                 }
2631               if (new)
2632                 pool_window_label = new;
2633               pool_window_last = i;
2634               return lab;
2635             }
2636         }
2637     }
2638
2639   /* Need a new one.  */
2640   pool_vector[pool_size].value = x;
2641   if (last_value && rtx_equal_p (last_value, pool_vector[pool_size - 1].value))
2642     {
2643       lab = 0;
2644       pool_vector[pool_size - 1].part_of_sequence_p = true;
2645     }
2646   else
2647     lab = gen_label_rtx ();
2648   pool_vector[pool_size].mode = mode;
2649   pool_vector[pool_size].label = lab;
2650   pool_vector[pool_size].wend = NULL_RTX;
2651   pool_vector[pool_size].part_of_sequence_p = (lab == 0);
2652   if (lab && pool_window_label)
2653     {
2654       newref = gen_rtx_LABEL_REF (VOIDmode, pool_window_label);
2655       ref = pool_vector[pool_window_last].wend;
2656       LABEL_NEXTREF (newref) = ref;
2657       pool_vector[pool_window_last].wend = newref;
2658     }
2659   if (lab)
2660     pool_window_label = lab;
2661   pool_window_last = pool_size;
2662   pool_size++;
2663   return lab;
2664 }
2665
2666 /* Output the literal table.  */
2667
2668 static void
2669 dump_table (rtx scan)
2670 {
2671   int i;
2672   int need_align = 1;
2673   rtx lab, ref;
2674   int have_df = 0;
2675
2676   /* Do two passes, first time dump out the HI sized constants.  */
2677
2678   for (i = 0; i < pool_size; i++)
2679     {
2680       pool_node *p = &pool_vector[i];
2681
2682       if (p->mode == HImode)
2683         {
2684           if (need_align)
2685             {
2686               scan = emit_insn_after (gen_align_2 (), scan);
2687               need_align = 0;
2688             }
2689           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2690             scan = emit_label_after (lab, scan);
2691           scan = emit_insn_after (gen_consttable_2 (p->value, const0_rtx),
2692                                   scan);
2693           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2694             {
2695               lab = XEXP (ref, 0);
2696               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2697             }
2698         }
2699       else if (p->mode == DFmode)
2700         have_df = 1;
2701     }
2702
2703   need_align = 1;
2704
2705   if (TARGET_FMOVD && TARGET_ALIGN_DOUBLE && have_df)
2706     {
2707       rtx align_insn = NULL_RTX;
2708
2709       scan = emit_label_after (gen_label_rtx (), scan);
2710       scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2711       need_align = 0;
2712
2713       for (i = 0; i < pool_size; i++)
2714         {
2715           pool_node *p = &pool_vector[i];
2716
2717           switch (p->mode)
2718             {
2719             case HImode:
2720               break;
2721             case SImode:
2722             case SFmode:
2723               if (align_insn && !p->part_of_sequence_p)
2724                 {
2725                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2726                     emit_label_before (lab, align_insn);
2727                   emit_insn_before (gen_consttable_4 (p->value, const0_rtx),
2728                                     align_insn);
2729                   for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2730                     {
2731                       lab = XEXP (ref, 0);
2732                       emit_insn_before (gen_consttable_window_end (lab),
2733                                        align_insn);
2734                     }
2735                   delete_insn (align_insn);
2736                   align_insn = NULL_RTX;
2737                   continue;
2738                 }
2739               else
2740                 {
2741                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
2742                     scan = emit_label_after (lab, scan);
2743                   scan = emit_insn_after (gen_consttable_4 (p->value,
2744                                                             const0_rtx), scan);
2745                   need_align = ! need_align;
2746                 }
2747               break;
2748             case DFmode:
2749               if (need_align)
2750                 {
2751                   scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
2752                   align_insn = scan;
2753                   need_align = 0;
2754                 }
2755             case DImode:
2756               for (lab = p->label; lab; lab = LABEL_REFS (lab))
2757                 scan = emit_label_after (lab, scan);
2758               scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2759                                       scan);
2760               break;
2761             default:
2762               abort ();
2763               break;
2764             }
2765
2766           if (p->mode != HImode)
2767             {
2768               for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2769                 {
2770                   lab = XEXP (ref, 0);
2771                   scan = emit_insn_after (gen_consttable_window_end (lab),
2772                                           scan);
2773                 }
2774             }
2775         }
2776
2777       pool_size = 0;
2778     }
2779   
2780   for (i = 0; i < pool_size; i++)
2781     {
2782       pool_node *p = &pool_vector[i];
2783
2784       switch (p->mode)
2785         {
2786         case HImode:
2787           break;
2788         case SImode:
2789         case SFmode:
2790           if (need_align)
2791             {
2792               need_align = 0;
2793               scan = emit_label_after (gen_label_rtx (), scan);
2794               scan = emit_insn_after (gen_align_4 (), scan);
2795             }
2796           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2797             scan = emit_label_after (lab, scan);
2798           scan = emit_insn_after (gen_consttable_4 (p->value, const0_rtx),
2799                                   scan);
2800           break;
2801         case DFmode:
2802         case DImode:
2803           if (need_align)
2804             {
2805               need_align = 0;
2806               scan = emit_label_after (gen_label_rtx (), scan);
2807               scan = emit_insn_after (gen_align_4 (), scan);
2808             }
2809           for (lab = p->label; lab; lab = LABEL_REFS (lab))
2810             scan = emit_label_after (lab, scan);
2811           scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
2812                                   scan);
2813           break;
2814         default:
2815           abort ();
2816           break;
2817         }
2818
2819       if (p->mode != HImode)
2820         {
2821           for (ref = p->wend; ref; ref = LABEL_NEXTREF (ref))
2822             {
2823               lab = XEXP (ref, 0);
2824               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
2825             }
2826         }
2827     }
2828
2829   scan = emit_insn_after (gen_consttable_end (), scan);
2830   scan = emit_barrier_after (scan);
2831   pool_size = 0;
2832   pool_window_label = NULL_RTX;
2833   pool_window_last = 0;
2834 }
2835
2836 /* Return nonzero if constant would be an ok source for a
2837    mov.w instead of a mov.l.  */
2838
2839 static int
2840 hi_const (rtx src)
2841 {
2842   return (GET_CODE (src) == CONST_INT
2843           && INTVAL (src) >= -32768
2844           && INTVAL (src) <= 32767);
2845 }
2846
2847 /* Nonzero if the insn is a move instruction which needs to be fixed.  */
2848
2849 /* ??? For a DImode/DFmode moves, we don't need to fix it if each half of the
2850    CONST_DOUBLE input value is CONST_OK_FOR_I08.  For a SFmode move, we don't
2851    need to fix it if the input value is CONST_OK_FOR_I08.  */
2852
2853 static int
2854 broken_move (rtx insn)
2855 {
2856   if (GET_CODE (insn) == INSN)
2857     {
2858       rtx pat = PATTERN (insn);
2859       if (GET_CODE (pat) == PARALLEL)
2860         pat = XVECEXP (pat, 0, 0);
2861       if (GET_CODE (pat) == SET
2862           /* We can load any 8 bit value if we don't care what the high
2863              order bits end up as.  */
2864           && GET_MODE (SET_DEST (pat)) != QImode
2865           && (CONSTANT_P (SET_SRC (pat))
2866               /* Match mova_const.  */
2867               || (GET_CODE (SET_SRC (pat)) == UNSPEC
2868                   && XINT (SET_SRC (pat), 1) == UNSPEC_MOVA
2869                   && GET_CODE (XVECEXP (SET_SRC (pat), 0, 0)) == CONST))
2870           && ! (TARGET_SH2E
2871                 && GET_CODE (SET_SRC (pat)) == CONST_DOUBLE
2872                 && (fp_zero_operand (SET_SRC (pat))
2873                     || fp_one_operand (SET_SRC (pat)))
2874                 /* ??? If this is a -m4 or -m4-single compilation, in general
2875                    we don't know the current setting of fpscr, so disable fldi.
2876                    There is an exception if this was a register-register move
2877                    before reload - and hence it was ascertained that we have
2878                    single precision setting - and in a post-reload optimization
2879                    we changed this to do a constant load.  In that case
2880                    we don't have an r0 clobber, hence we must use fldi.  */
2881                 && (! TARGET_SH4 || TARGET_FMOVD
2882                     || (GET_CODE (XEXP (XVECEXP (PATTERN (insn), 0, 2), 0))
2883                         == SCRATCH))
2884                 && GET_CODE (SET_DEST (pat)) == REG
2885                 && FP_REGISTER_P (REGNO (SET_DEST (pat))))
2886           && (GET_CODE (SET_SRC (pat)) != CONST_INT
2887               || ! CONST_OK_FOR_I08 (INTVAL (SET_SRC (pat)))))
2888         return 1;
2889     }
2890
2891   return 0;
2892 }
2893
2894 static int
2895 mova_p (rtx insn)
2896 {
2897   return (GET_CODE (insn) == INSN
2898           && GET_CODE (PATTERN (insn)) == SET
2899           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
2900           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_MOVA
2901           /* Don't match mova_const.  */
2902           && GET_CODE (XVECEXP (SET_SRC (PATTERN (insn)), 0, 0)) == LABEL_REF);
2903 }
2904
2905 /* Find the last barrier from insn FROM which is close enough to hold the
2906    constant pool.  If we can't find one, then create one near the end of
2907    the range.  */
2908
2909 static rtx
2910 find_barrier (int num_mova, rtx mova, rtx from)
2911 {
2912   int count_si = 0;
2913   int count_hi = 0;
2914   int found_hi = 0;
2915   int found_si = 0;
2916   int found_di = 0;
2917   int hi_align = 2;
2918   int si_align = 2;
2919   int leading_mova = num_mova;
2920   rtx barrier_before_mova = 0, found_barrier = 0, good_barrier = 0;
2921   int si_limit;
2922   int hi_limit;
2923
2924   /* For HImode: range is 510, add 4 because pc counts from address of
2925      second instruction after this one, subtract 2 for the jump instruction
2926      that we may need to emit before the table, subtract 2 for the instruction
2927      that fills the jump delay slot (in very rare cases, reorg will take an
2928      instruction from after the constant pool or will leave the delay slot
2929      empty).  This gives 510.
2930      For SImode: range is 1020, add 4 because pc counts from address of
2931      second instruction after this one, subtract 2 in case pc is 2 byte
2932      aligned, subtract 2 for the jump instruction that we may need to emit
2933      before the table, subtract 2 for the instruction that fills the jump
2934      delay slot.  This gives 1018.  */
2935
2936   /* The branch will always be shortened now that the reference address for
2937      forward branches is the successor address, thus we need no longer make
2938      adjustments to the [sh]i_limit for -O0.  */
2939
2940   si_limit = 1018;
2941   hi_limit = 510;
2942
2943   while (from && count_si < si_limit && count_hi < hi_limit)
2944     {
2945       int inc = get_attr_length (from);
2946       int new_align = 1;
2947
2948       if (GET_CODE (from) == CODE_LABEL)
2949         {
2950           if (optimize)
2951             new_align = 1 << label_to_alignment (from);
2952           else if (GET_CODE (prev_nonnote_insn (from)) == BARRIER)
2953             new_align = 1 << barrier_align (from);
2954           else
2955             new_align = 1;
2956           inc = 0;
2957         }
2958
2959       if (GET_CODE (from) == BARRIER)
2960         {
2961
2962           found_barrier = from;
2963
2964           /* If we are at the end of the function, or in front of an alignment
2965              instruction, we need not insert an extra alignment.  We prefer
2966              this kind of barrier.  */
2967           if (barrier_align (from) > 2)
2968             good_barrier = from;
2969         }
2970
2971       if (broken_move (from))
2972         {
2973           rtx pat, src, dst;
2974           enum machine_mode mode;
2975
2976           pat = PATTERN (from);
2977           if (GET_CODE (pat) == PARALLEL)
2978             pat = XVECEXP (pat, 0, 0);
2979           src = SET_SRC (pat);
2980           dst = SET_DEST (pat);
2981           mode = GET_MODE (dst);
2982
2983           /* We must explicitly check the mode, because sometimes the
2984              front end will generate code to load unsigned constants into
2985              HImode targets without properly sign extending them.  */
2986           if (mode == HImode
2987               || (mode == SImode && hi_const (src) && REGNO (dst) != FPUL_REG))
2988             {
2989               found_hi += 2;
2990               /* We put the short constants before the long constants, so
2991                  we must count the length of short constants in the range
2992                  for the long constants.  */
2993               /* ??? This isn't optimal, but is easy to do.  */
2994               si_limit -= 2;
2995             }
2996           else
2997             {
2998               /* We dump DF/DI constants before SF/SI ones, because
2999                  the limit is the same, but the alignment requirements
3000                  are higher.  We may waste up to 4 additional bytes
3001                  for alignment, and the DF/DI constant may have
3002                  another SF/SI constant placed before it.  */
3003               if (TARGET_SHCOMPACT
3004                   && ! found_di
3005                   && (mode == DFmode || mode == DImode))
3006                 {
3007                   found_di = 1;
3008                   si_limit -= 8;
3009                 }
3010               while (si_align > 2 && found_si + si_align - 2 > count_si)
3011                 si_align >>= 1;
3012               if (found_si > count_si)
3013                 count_si = found_si;
3014               found_si += GET_MODE_SIZE (mode);
3015               if (num_mova)
3016                 si_limit -= GET_MODE_SIZE (mode);
3017             }
3018
3019           /* See the code in machine_dependent_reorg, which has a similar if
3020              statement that generates a new mova insn in many cases.  */
3021           if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
3022             inc += 2;
3023         }
3024
3025       if (mova_p (from))
3026         {
3027           if (! num_mova++)
3028             {
3029               leading_mova = 0;
3030               mova = from;
3031               barrier_before_mova = good_barrier ? good_barrier : found_barrier;
3032             }
3033           if (found_si > count_si)
3034             count_si = found_si;
3035         }
3036       else if (GET_CODE (from) == JUMP_INSN
3037                && (GET_CODE (PATTERN (from)) == ADDR_VEC
3038                    || GET_CODE (PATTERN (from)) == ADDR_DIFF_VEC))
3039         {
3040           if (num_mova)
3041             num_mova--;
3042           if (barrier_align (next_real_insn (from)) == align_jumps_log)
3043             {
3044               /* We have just passed the barrier in front of the
3045                  ADDR_DIFF_VEC, which is stored in found_barrier.  Since
3046                  the ADDR_DIFF_VEC is accessed as data, just like our pool
3047                  constants, this is a good opportunity to accommodate what
3048                  we have gathered so far.
3049                  If we waited any longer, we could end up at a barrier in
3050                  front of code, which gives worse cache usage for separated
3051                  instruction / data caches.  */
3052               good_barrier = found_barrier;
3053               break;
3054             }
3055           else
3056             {
3057               rtx body = PATTERN (from);
3058               inc = XVECLEN (body, 1) * GET_MODE_SIZE (GET_MODE (body));
3059             }
3060         }
3061       /* For the SH1, we generate alignments even after jumps-around-jumps.  */
3062       else if (GET_CODE (from) == JUMP_INSN
3063                && ! TARGET_SH2
3064                && ! TARGET_SMALLCODE)
3065         new_align = 4;
3066
3067       if (found_si)
3068         {
3069           count_si += inc;
3070           if (new_align > si_align)
3071             {
3072               si_limit -= (count_si - 1) & (new_align - si_align);
3073               si_align = new_align;
3074             }
3075           count_si = (count_si + new_align - 1) & -new_align;
3076         }
3077       if (found_hi)
3078         {
3079           count_hi += inc;
3080           if (new_align > hi_align)
3081             {
3082               hi_limit -= (count_hi - 1) & (new_align - hi_align);
3083               hi_align = new_align;
3084             }
3085           count_hi = (count_hi + new_align - 1) & -new_align;
3086         }
3087       from = NEXT_INSN (from);
3088     }
3089
3090   if (num_mova)
3091     {
3092       if (leading_mova)
3093         {
3094           /* Try as we might, the leading mova is out of range.  Change
3095              it into a load (which will become a pcload) and retry.  */
3096           SET_SRC (PATTERN (mova)) = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
3097           INSN_CODE (mova) = -1;
3098           return find_barrier (0, 0, mova);
3099         }
3100       else
3101         {
3102           /* Insert the constant pool table before the mova instruction,
3103              to prevent the mova label reference from going out of range.  */
3104           from = mova;
3105           good_barrier = found_barrier = barrier_before_mova;
3106         }
3107     }
3108
3109   if (found_barrier)
3110     {
3111       if (good_barrier && next_real_insn (found_barrier))
3112         found_barrier = good_barrier;
3113     }
3114   else
3115     {
3116       /* We didn't find a barrier in time to dump our stuff,
3117          so we'll make one.  */
3118       rtx label = gen_label_rtx ();
3119
3120       /* If we exceeded the range, then we must back up over the last
3121          instruction we looked at.  Otherwise, we just need to undo the
3122          NEXT_INSN at the end of the loop.  */
3123       if (count_hi > hi_limit || count_si > si_limit)
3124         from = PREV_INSN (PREV_INSN (from));
3125       else
3126         from = PREV_INSN (from);
3127
3128       /* Walk back to be just before any jump or label.
3129          Putting it before a label reduces the number of times the branch
3130          around the constant pool table will be hit.  Putting it before
3131          a jump makes it more likely that the bra delay slot will be
3132          filled.  */
3133       while (GET_CODE (from) == JUMP_INSN || GET_CODE (from) == NOTE
3134              || GET_CODE (from) == CODE_LABEL)
3135         from = PREV_INSN (from);
3136
3137       from = emit_jump_insn_after (gen_jump (label), from);
3138       JUMP_LABEL (from) = label;
3139       LABEL_NUSES (label) = 1;
3140       found_barrier = emit_barrier_after (from);
3141       emit_label_after (label, found_barrier);
3142     }
3143
3144   return found_barrier;
3145 }
3146
3147 /* If the instruction INSN is implemented by a special function, and we can
3148    positively find the register that is used to call the sfunc, and this
3149    register is not used anywhere else in this instruction - except as the
3150    destination of a set, return this register; else, return 0.  */
3151 rtx
3152 sfunc_uses_reg (rtx insn)
3153 {
3154   int i;
3155   rtx pattern, part, reg_part, reg;
3156
3157   if (GET_CODE (insn) != INSN)
3158     return 0;
3159   pattern = PATTERN (insn);
3160   if (GET_CODE (pattern) != PARALLEL || get_attr_type (insn) != TYPE_SFUNC)
3161     return 0;
3162
3163   for (reg_part = 0, i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
3164     {
3165       part = XVECEXP (pattern, 0, i);
3166       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == SImode)
3167         reg_part = part;
3168     }
3169   if (! reg_part)
3170     return 0;
3171   reg = XEXP (reg_part, 0);
3172   for (i = XVECLEN (pattern, 0) - 1; i >= 0; i--)
3173     {
3174       part = XVECEXP (pattern, 0, i);
3175       if (part == reg_part || GET_CODE (part) == CLOBBER)
3176         continue;
3177       if (reg_mentioned_p (reg, ((GET_CODE (part) == SET
3178                                   && GET_CODE (SET_DEST (part)) == REG)
3179                                  ? SET_SRC (part) : part)))
3180         return 0;
3181     }
3182   return reg;
3183 }
3184
3185 /* See if the only way in which INSN uses REG is by calling it, or by
3186    setting it while calling it.  Set *SET to a SET rtx if the register
3187    is set by INSN.  */
3188
3189 static int
3190 noncall_uses_reg (rtx reg, rtx insn, rtx *set)
3191 {
3192   rtx pattern, reg2;
3193
3194   *set = NULL_RTX;
3195
3196   reg2 = sfunc_uses_reg (insn);
3197   if (reg2 && REGNO (reg2) == REGNO (reg))
3198     {
3199       pattern = single_set (insn);
3200       if (pattern
3201           && GET_CODE (SET_DEST (pattern)) == REG
3202           && REGNO (reg) == REGNO (SET_DEST (pattern)))
3203         *set = pattern;
3204       return 0;
3205     }
3206   if (GET_CODE (insn) != CALL_INSN)
3207     {
3208       /* We don't use rtx_equal_p because we don't care if the mode is
3209          different.  */
3210       pattern = single_set (insn);
3211       if (pattern
3212           && GET_CODE (SET_DEST (pattern)) == REG
3213           && REGNO (reg) == REGNO (SET_DEST (pattern)))
3214         {
3215           rtx par, part;
3216           int i;
3217
3218           *set = pattern;
3219           par = PATTERN (insn);
3220           if (GET_CODE (par) == PARALLEL)
3221             for (i = XVECLEN (par, 0) - 1; i >= 0; i--)
3222               {
3223                 part = XVECEXP (par, 0, i);
3224                 if (GET_CODE (part) != SET && reg_mentioned_p (reg, part))
3225                   return 1;
3226               }
3227           return reg_mentioned_p (reg, SET_SRC (pattern));
3228         }
3229
3230       return 1;
3231     }
3232
3233   pattern = PATTERN (insn);
3234
3235   if (GET_CODE (pattern) == PARALLEL)
3236     {
3237       int i;
3238
3239       for (i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
3240         if (reg_mentioned_p (reg, XVECEXP (pattern, 0, i)))
3241           return 1;
3242       pattern = XVECEXP (pattern, 0, 0);
3243     }
3244
3245   if (GET_CODE (pattern) == SET)
3246     {
3247       if (reg_mentioned_p (reg, SET_DEST (pattern)))
3248         {
3249           /* We don't use rtx_equal_p, because we don't care if the
3250              mode is different.  */
3251           if (GET_CODE (SET_DEST (pattern)) != REG
3252               || REGNO (reg) != REGNO (SET_DEST (pattern)))
3253             return 1;
3254
3255           *set = pattern;
3256         }
3257
3258       pattern = SET_SRC (pattern);
3259     }
3260
3261   if (GET_CODE (pattern) != CALL
3262       || GET_CODE (XEXP (pattern, 0)) != MEM
3263       || ! rtx_equal_p (reg, XEXP (XEXP (pattern, 0), 0)))
3264     return 1;
3265
3266   return 0;
3267 }
3268
3269 /* Given a X, a pattern of an insn or a part of it, return a mask of used
3270    general registers.  Bits 0..15 mean that the respective registers
3271    are used as inputs in the instruction.  Bits 16..31 mean that the
3272    registers 0..15, respectively, are used as outputs, or are clobbered.
3273    IS_DEST should be set to 16 if X is the destination of a SET, else to 0.  */
3274 int
3275 regs_used (rtx x, int is_dest)
3276 {
3277   enum rtx_code code;
3278   const char *fmt;
3279   int i, used = 0;
3280
3281   if (! x)
3282     return used;
3283   code = GET_CODE (x);
3284   switch (code)
3285     {
3286     case REG:
3287       if (REGNO (x) < 16)
3288         return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
3289                 << (REGNO (x) + is_dest));
3290       return 0;
3291     case SUBREG:
3292       {
3293         rtx y = SUBREG_REG (x);
3294      
3295         if (GET_CODE (y) != REG)
3296           break;
3297         if (REGNO (y) < 16)
3298           return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
3299                   << (REGNO (y) +
3300                       subreg_regno_offset (REGNO (y),
3301                                            GET_MODE (y),
3302                                            SUBREG_BYTE (x),
3303                                            GET_MODE (x)) + is_dest));
3304         return 0;
3305       }
3306     case SET:
3307       return regs_used (SET_SRC (x), 0) | regs_used (SET_DEST (x), 16);
3308     case RETURN:
3309       /* If there was a return value, it must have been indicated with USE.  */
3310       return 0x00ffff00;
3311     case CLOBBER:
3312       is_dest = 1;
3313       break;
3314     case MEM:
3315       is_dest = 0;
3316       break;
3317     case CALL:
3318       used |= 0x00ff00f0;
3319       break;
3320     default:
3321       break;
3322     }
3323
3324   fmt = GET_RTX_FORMAT (code);
3325
3326   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3327     {
3328       if (fmt[i] == 'E')
3329         {
3330           register int j;
3331           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3332             used |= regs_used (XVECEXP (x, i, j), is_dest);
3333         }
3334       else if (fmt[i] == 'e')
3335         used |= regs_used (XEXP (x, i), is_dest);
3336     }
3337   return used;
3338 }
3339
3340 /* Create an instruction that prevents redirection of a conditional branch
3341    to the destination of the JUMP with address ADDR.
3342    If the branch needs to be implemented as an indirect jump, try to find
3343    a scratch register for it.
3344    If NEED_BLOCK is 0, don't do anything unless we need a scratch register.
3345    If any preceding insn that doesn't fit into a delay slot is good enough,
3346    pass 1.  Pass 2 if a definite blocking insn is needed.
3347    -1 is used internally to avoid deep recursion.
3348    If a blocking instruction is made or recognized, return it.  */
3349    
3350 static rtx
3351 gen_block_redirect (rtx jump, int addr, int need_block)
3352 {
3353   int dead = 0;
3354   rtx prev = prev_nonnote_insn (jump);
3355   rtx dest;
3356
3357   /* First, check if we already have an instruction that satisfies our need.  */
3358   if (prev && GET_CODE (prev) == INSN && ! INSN_DELETED_P (prev))
3359     {
3360       if (INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
3361         return prev;
3362       if (GET_CODE (PATTERN (prev)) == USE
3363           || GET_CODE (PATTERN (prev)) == CLOBBER
3364           || get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3365         prev = jump;
3366       else if ((need_block &= ~1) < 0)
3367         return prev;
3368       else if (recog_memoized (prev) == CODE_FOR_block_branch_redirect)
3369         need_block = 0;
3370     }
3371   if (GET_CODE (PATTERN (jump)) == RETURN)
3372     {
3373       if (! need_block)
3374         return prev;
3375       /* Reorg even does nasty things with return insns that cause branches
3376          to go out of range - see find_end_label and callers.  */
3377       return emit_insn_before (gen_block_branch_redirect (GEN_INT (0)) , jump);
3378     }
3379   /* We can't use JUMP_LABEL here because it might be undefined
3380      when not optimizing.  */
3381   dest = XEXP (SET_SRC (PATTERN (jump)), 0);
3382   /* If the branch is out of range, try to find a scratch register for it.  */
3383   if (optimize
3384       && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3385           > 4092 + 4098))
3386     {
3387       rtx scan;
3388       /* Don't look for the stack pointer as a scratch register,
3389          it would cause trouble if an interrupt occurred.  */
3390       unsigned try = 0x7fff, used;
3391       int jump_left = flag_expensive_optimizations + 1;
3392     
3393       /* It is likely that the most recent eligible instruction is wanted for
3394          the delay slot.  Therefore, find out which registers it uses, and
3395          try to avoid using them.  */
3396          
3397       for (scan = jump; (scan = PREV_INSN (scan)); )
3398         {
3399           enum rtx_code code;
3400
3401           if (INSN_DELETED_P (scan))
3402             continue;
3403           code = GET_CODE (scan);
3404           if (code == CODE_LABEL || code == JUMP_INSN)
3405             break;
3406           if (code == INSN
3407               && GET_CODE (PATTERN (scan)) != USE
3408               && GET_CODE (PATTERN (scan)) != CLOBBER
3409               && get_attr_in_delay_slot (scan) == IN_DELAY_SLOT_YES)
3410             {
3411               try &= ~regs_used (PATTERN (scan), 0);
3412               break;
3413             }
3414         }
3415       for (used = dead = 0, scan = JUMP_LABEL (jump);
3416            (scan = NEXT_INSN (scan)); )
3417         {
3418           enum rtx_code code;
3419
3420           if (INSN_DELETED_P (scan))
3421             continue;
3422           code = GET_CODE (scan);
3423           if (GET_RTX_CLASS (code) == 'i')
3424             {
3425               used |= regs_used (PATTERN (scan), 0);
3426               if (code == CALL_INSN)
3427                 used |= regs_used (CALL_INSN_FUNCTION_USAGE (scan), 0);
3428               dead |= (used >> 16) & ~used;
3429               if (dead & try)
3430                 {
3431                   dead &= try;
3432                   break;
3433                 }
3434               if (code == JUMP_INSN)
3435                 {
3436                   if (jump_left-- && simplejump_p (scan))
3437                     scan = JUMP_LABEL (scan);
3438                   else
3439                     break;
3440                 }
3441             }
3442         }
3443       /* Mask out the stack pointer again, in case it was
3444          the only 'free' register we have found.  */
3445       dead &= 0x7fff;
3446     }
3447   /* If the immediate destination is still in range, check for possible
3448      threading with a jump beyond the delay slot insn.
3449      Don't check if we are called recursively; the jump has been or will be
3450      checked in a different invocation then.  */
3451         
3452   else if (optimize && need_block >= 0)
3453     {
3454       rtx next = next_active_insn (next_active_insn (dest));
3455       if (next && GET_CODE (next) == JUMP_INSN
3456           && GET_CODE (PATTERN (next)) == SET
3457           && recog_memoized (next) == CODE_FOR_jump_compact)
3458         {
3459           dest = JUMP_LABEL (next);
3460           if (dest
3461               && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
3462                   > 4092 + 4098))
3463             gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), -1);
3464         }
3465     }
3466
3467   if (dead)
3468     {
3469       rtx reg = gen_rtx_REG (SImode, exact_log2 (dead & -dead));
3470
3471       /* It would be nice if we could convert the jump into an indirect
3472          jump / far branch right now, and thus exposing all constituent
3473          instructions to further optimization.  However, reorg uses
3474          simplejump_p to determine if there is an unconditional jump where
3475          it should try to schedule instructions from the target of the
3476          branch; simplejump_p fails for indirect jumps even if they have
3477          a JUMP_LABEL.  */
3478       rtx insn = emit_insn_before (gen_indirect_jump_scratch
3479                                    (reg, GEN_INT (INSN_UID (JUMP_LABEL (jump))))
3480                                    , jump);
3481       /* ??? We would like this to have the scope of the jump, but that
3482          scope will change when a delay slot insn of an inner scope is added.
3483          Hence, after delay slot scheduling, we'll have to expect
3484          NOTE_INSN_BLOCK_END notes between the indirect_jump_scratch and
3485          the jump.  */
3486          
3487       INSN_LOCATOR (insn) = INSN_LOCATOR (jump);
3488       INSN_CODE (insn) = CODE_FOR_indirect_jump_scratch;
3489       return insn;
3490     }
3491   else if (need_block)
3492     /* We can't use JUMP_LABEL here because it might be undefined
3493        when not optimizing.  */
3494     return emit_insn_before (gen_block_branch_redirect
3495                       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))))
3496                       , jump);
3497   return prev;
3498 }
3499
3500 #define CONDJUMP_MIN -252
3501 #define CONDJUMP_MAX 262
3502 struct far_branch
3503 {
3504   /* A label (to be placed) in front of the jump
3505      that jumps to our ultimate destination.  */
3506   rtx near_label;
3507   /* Where we are going to insert it if we cannot move the jump any farther,
3508      or the jump itself if we have picked up an existing jump.  */
3509   rtx insert_place;
3510   /* The ultimate destination.  */
3511   rtx far_label;
3512   struct far_branch *prev;
3513   /* If the branch has already been created, its address;
3514      else the address of its first prospective user.  */
3515   int address;
3516 };
3517
3518 static void gen_far_branch (struct far_branch *);
3519 enum mdep_reorg_phase_e mdep_reorg_phase;
3520 static void
3521 gen_far_branch (struct far_branch *bp)
3522 {
3523   rtx insn = bp->insert_place;
3524   rtx jump;
3525   rtx label = gen_label_rtx ();
3526
3527   emit_label_after (label, insn);
3528   if (bp->far_label)
3529     {
3530       jump = emit_jump_insn_after (gen_jump (bp->far_label), insn);
3531       LABEL_NUSES (bp->far_label)++;
3532     }
3533   else
3534     jump = emit_jump_insn_after (gen_return (), insn);
3535   /* Emit a barrier so that reorg knows that any following instructions
3536      are not reachable via a fall-through path.
3537      But don't do this when not optimizing, since we wouldn't suppress the
3538      alignment for the barrier then, and could end up with out-of-range
3539      pc-relative loads.  */
3540   if (optimize)
3541     emit_barrier_after (jump);
3542   emit_label_after (bp->near_label, insn);
3543   JUMP_LABEL (jump) = bp->far_label;
3544   if (! invert_jump (insn, label, 1))
3545     abort ();
3546   /* If we are branching around a jump (rather than a return), prevent
3547      reorg from using an insn from the jump target as the delay slot insn -
3548      when reorg did this, it pessimized code (we rather hide the delay slot)
3549      and it could cause branches to go out of range.  */
3550   if (bp->far_label)
3551     (emit_insn_after
3552      (gen_stuff_delay_slot
3553       (GEN_INT (INSN_UID (XEXP (SET_SRC (PATTERN (jump)), 0))),
3554        GEN_INT (recog_memoized (insn) == CODE_FOR_branch_false)),
3555       insn));
3556   /* Prevent reorg from undoing our splits.  */
3557   gen_block_redirect (jump, bp->address += 2, 2);
3558 }
3559
3560 /* Fix up ADDR_DIFF_VECs.  */
3561 void
3562 fixup_addr_diff_vecs (rtx first)
3563 {
3564   rtx insn;
3565
3566   for (insn = first; insn; insn = NEXT_INSN (insn))
3567     {
3568       rtx vec_lab, pat, prev, prevpat, x, braf_label;
3569
3570       if (GET_CODE (insn) != JUMP_INSN
3571           || GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
3572         continue;
3573       pat = PATTERN (insn);
3574       vec_lab = XEXP (XEXP (pat, 0), 0);
3575
3576       /* Search the matching casesi_jump_2.  */
3577       for (prev = vec_lab; ; prev = PREV_INSN (prev))
3578         {
3579           if (GET_CODE (prev) != JUMP_INSN)
3580             continue;
3581           prevpat = PATTERN (prev);
3582           if (GET_CODE (prevpat) != PARALLEL || XVECLEN (prevpat, 0) != 2)
3583             continue;
3584           x = XVECEXP (prevpat, 0, 1);
3585           if (GET_CODE (x) != USE)
3586             continue;
3587           x = XEXP (x, 0);
3588           if (GET_CODE (x) == LABEL_REF && XEXP (x, 0) == vec_lab)
3589             break;
3590         }
3591
3592       /* Emit the reference label of the braf where it belongs, right after
3593          the casesi_jump_2 (i.e. braf).  */
3594       braf_label = XEXP (XEXP (SET_SRC (XVECEXP (prevpat, 0, 0)), 1), 0);
3595       emit_label_after (braf_label, prev);
3596
3597       /* Fix up the ADDR_DIF_VEC to be relative
3598          to the reference address of the braf.  */
3599       XEXP (XEXP (pat, 0), 0) = braf_label;
3600     }
3601 }
3602
3603 /* BARRIER_OR_LABEL is either a BARRIER or a CODE_LABEL immediately following
3604    a barrier.  Return the base 2 logarithm of the desired alignment.  */
3605 int
3606 barrier_align (rtx barrier_or_label)
3607 {
3608   rtx next = next_real_insn (barrier_or_label), pat, prev;
3609   int slot, credit, jump_to_next = 0;
3610  
3611   if (! next)
3612     return 0;
3613
3614   pat = PATTERN (next);
3615
3616   if (GET_CODE (pat) == ADDR_DIFF_VEC)
3617     return 2;
3618
3619   if (GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_ALIGN)
3620     /* This is a barrier in front of a constant table.  */
3621     return 0;
3622
3623   prev = prev_real_insn (barrier_or_label);
3624   if (GET_CODE (PATTERN (prev)) == ADDR_DIFF_VEC)
3625     {
3626       pat = PATTERN (prev);
3627       /* If this is a very small table, we want to keep the alignment after
3628          the table to the minimum for proper code alignment.  */
3629       return ((TARGET_SMALLCODE
3630                || ((unsigned) XVECLEN (pat, 1) * GET_MODE_SIZE (GET_MODE (pat))
3631                    <= (unsigned)1 << (CACHE_LOG - 2)))
3632               ? 1 << TARGET_SHMEDIA : align_jumps_log);
3633     }
3634
3635   if (TARGET_SMALLCODE)
3636     return 0;
3637
3638   if (! TARGET_SH2 || ! optimize)
3639     return align_jumps_log;
3640
3641   /* When fixing up pcloads, a constant table might be inserted just before
3642      the basic block that ends with the barrier.  Thus, we can't trust the
3643      instruction lengths before that.  */
3644   if (mdep_reorg_phase > SH_FIXUP_PCLOAD)
3645     {
3646       /* Check if there is an immediately preceding branch to the insn beyond
3647          the barrier.  We must weight the cost of discarding useful information
3648          from the current cache line when executing this branch and there is
3649          an alignment, against that of fetching unneeded insn in front of the
3650          branch target when there is no alignment.  */
3651
3652       /* There are two delay_slot cases to consider.  One is the simple case 
3653          where the preceding branch is to the insn beyond the barrier (simple 
3654          delay slot filling), and the other is where the preceding branch has 
3655          a delay slot that is a duplicate of the insn after the barrier 
3656          (fill_eager_delay_slots) and the branch is to the insn after the insn 
3657          after the barrier.  */
3658
3659       /* PREV is presumed to be the JUMP_INSN for the barrier under
3660          investigation.  Skip to the insn before it.  */
3661       prev = prev_real_insn (prev);
3662
3663       for (slot = 2, credit = (1 << (CACHE_LOG - 2)) + 2;
3664            credit >= 0 && prev && GET_CODE (prev) == INSN;
3665            prev = prev_real_insn (prev))
3666         {
3667           jump_to_next = 0;
3668           if (GET_CODE (PATTERN (prev)) == USE
3669               || GET_CODE (PATTERN (prev)) == CLOBBER)
3670             continue;
3671           if (GET_CODE (PATTERN (prev)) == SEQUENCE)
3672             {
3673               prev = XVECEXP (PATTERN (prev), 0, 1);
3674               if (INSN_UID (prev) == INSN_UID (next)) 
3675                 {
3676                   /* Delay slot was filled with insn at jump target.  */
3677                   jump_to_next = 1;
3678                   continue;
3679                 }
3680             }
3681
3682           if (slot &&
3683               get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
3684             slot = 0;
3685           credit -= get_attr_length (prev);
3686         }
3687       if (prev
3688           && GET_CODE (prev) == JUMP_INSN
3689           && JUMP_LABEL (prev))
3690         {
3691           rtx x;
3692           if (jump_to_next
3693               || next_real_insn (JUMP_LABEL (prev)) == next
3694               /* If relax_delay_slots() decides NEXT was redundant
3695                  with some previous instruction, it will have
3696                  redirected PREV's jump to the following insn.  */
3697               || JUMP_LABEL (prev) == next_nonnote_insn (next)
3698               /* There is no upper bound on redundant instructions
3699                  that might have been skipped, but we must not put an
3700                  alignment where none had been before.  */
3701               || (x = (NEXT_INSN (NEXT_INSN (PREV_INSN (prev)))),           
3702                   (INSN_P (x) 
3703                    && (INSN_CODE (x) == CODE_FOR_block_branch_redirect
3704                        || INSN_CODE (x) == CODE_FOR_indirect_jump_scratch
3705                        || INSN_CODE (x) == CODE_FOR_stuff_delay_slot))))
3706             {
3707               rtx pat = PATTERN (prev);
3708               if (GET_CODE (pat) == PARALLEL)
3709                 pat = XVECEXP (pat, 0, 0);
3710               if (credit - slot >= (GET_CODE (SET_SRC (pat)) == PC ? 2 : 0))
3711                 return 0;
3712             }
3713         }
3714     }
3715   
3716   return align_jumps_log;
3717 }
3718
3719 /* If we are inside a phony loop, almost any kind of label can turn up as the
3720    first one in the loop.  Aligning a braf label causes incorrect switch
3721    destination addresses; we can detect braf labels because they are
3722    followed by a BARRIER.
3723    Applying loop alignment to small constant or switch tables is a waste
3724    of space, so we suppress this too.  */
3725 int
3726 sh_loop_align (rtx label)
3727 {
3728   rtx next = label;
3729
3730   do
3731     next = next_nonnote_insn (next);
3732   while (next && GET_CODE (next) == CODE_LABEL);
3733
3734   if (! next
3735       || ! INSN_P (next)
3736       || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC
3737       || recog_memoized (next) == CODE_FOR_consttable_2)
3738     return 0;
3739
3740   return align_loops_log;
3741 }
3742
3743 /* Do a final pass over the function, just before delayed branch
3744    scheduling.  */
3745
3746 static void
3747 sh_reorg (void)
3748 {
3749   rtx first, insn, mova = NULL_RTX;
3750   int num_mova;
3751   rtx r0_rtx = gen_rtx_REG (Pmode, 0);
3752   rtx r0_inc_rtx = gen_rtx_POST_INC (Pmode, r0_rtx);
3753
3754   first = get_insns ();
3755
3756   /* We must split call insns before introducing `mova's.  If we're
3757      optimizing, they'll have already been split.  Otherwise, make
3758      sure we don't split them too late.  */
3759   if (! optimize)
3760     split_all_insns_noflow ();
3761
3762   if (TARGET_SHMEDIA)
3763     return;
3764
3765   /* If relaxing, generate pseudo-ops to associate function calls with
3766      the symbols they call.  It does no harm to not generate these
3767      pseudo-ops.  However, when we can generate them, it enables to
3768      linker to potentially relax the jsr to a bsr, and eliminate the
3769      register load and, possibly, the constant pool entry.  */
3770
3771   mdep_reorg_phase = SH_INSERT_USES_LABELS;
3772   if (TARGET_RELAX)
3773     {
3774       /* Remove all REG_LABEL notes.  We want to use them for our own
3775          purposes.  This works because none of the remaining passes
3776          need to look at them.
3777
3778          ??? But it may break in the future.  We should use a machine
3779          dependent REG_NOTE, or some other approach entirely.  */
3780       for (insn = first; insn; insn = NEXT_INSN (insn))
3781         {
3782           if (INSN_P (insn))
3783             {
3784               rtx note;
3785
3786               while ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)) != 0)
3787                 remove_note (insn, note);
3788             }
3789         }
3790
3791       for (insn = first; insn; insn = NEXT_INSN (insn))
3792         {
3793           rtx pattern, reg, link, set, scan, dies, label;
3794           int rescan = 0, foundinsn = 0;
3795
3796           if (GET_CODE (insn) == CALL_INSN)
3797             {
3798               pattern = PATTERN (insn);
3799
3800               if (GET_CODE (pattern) == PARALLEL)
3801                 pattern = XVECEXP (pattern, 0, 0);
3802               if (GET_CODE (pattern) == SET)
3803                 pattern = SET_SRC (pattern);
3804
3805               if (GET_CODE (pattern) != CALL
3806                   || GET_CODE (XEXP (pattern, 0)) != MEM)
3807                 continue;
3808
3809               reg = XEXP (XEXP (pattern, 0), 0);
3810             }
3811           else
3812             {
3813               reg = sfunc_uses_reg (insn);
3814               if (! reg)
3815                 continue;
3816             }
3817
3818           if (GET_CODE (reg) != REG)
3819             continue;
3820
3821           /* This is a function call via REG.  If the only uses of REG
3822              between the time that it is set and the time that it dies
3823              are in function calls, then we can associate all the
3824              function calls with the setting of REG.  */
3825
3826           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
3827             {
3828               if (REG_NOTE_KIND (link) != 0)
3829                 continue;
3830               set = single_set (XEXP (link, 0));
3831               if (set && rtx_equal_p (reg, SET_DEST (set)))
3832                 {
3833                   link = XEXP (link, 0);
3834                   break;
3835                 }
3836             }
3837
3838           if (! link)
3839             {
3840               /* ??? Sometimes global register allocation will have
3841                  deleted the insn pointed to by LOG_LINKS.  Try
3842                  scanning backward to find where the register is set.  */
3843               for (scan = PREV_INSN (insn);
3844                    scan && GET_CODE (scan) != CODE_LABEL;
3845                    scan = PREV_INSN (scan))
3846                 {
3847                   if (! INSN_P (scan))
3848                     continue;
3849
3850                   if (! reg_mentioned_p (reg, scan))
3851                     continue;
3852
3853                   if (noncall_uses_reg (reg, scan, &set))
3854                     break;
3855
3856                   if (set)
3857                     {
3858                       link = scan;
3859                       break;
3860                     }
3861                 }
3862             }
3863
3864           if (! link)
3865             continue;
3866
3867           /* The register is set at LINK.  */
3868
3869           /* We can only optimize the function call if the register is
3870              being set to a symbol.  In theory, we could sometimes
3871              optimize calls to a constant location, but the assembler
3872              and linker do not support that at present.  */
3873           if (GET_CODE (SET_SRC (set)) != SYMBOL_REF
3874               && GET_CODE (SET_SRC (set)) != LABEL_REF)
3875             continue;
3876
3877           /* Scan forward from LINK to the place where REG dies, and
3878              make sure that the only insns which use REG are
3879              themselves function calls.  */
3880
3881           /* ??? This doesn't work for call targets that were allocated
3882              by reload, since there may not be a REG_DEAD note for the
3883              register.  */
3884
3885           dies = NULL_RTX;
3886           for (scan = NEXT_INSN (link); scan; scan = NEXT_INSN (scan))
3887             {
3888               rtx scanset;
3889
3890               /* Don't try to trace forward past a CODE_LABEL if we haven't
3891                  seen INSN yet.  Ordinarily, we will only find the setting insn
3892                  in LOG_LINKS if it is in the same basic block.  However,
3893                  cross-jumping can insert code labels in between the load and
3894                  the call, and can result in situations where a single call
3895                  insn may have two targets depending on where we came from.  */
3896
3897               if (GET_CODE (scan) == CODE_LABEL && ! foundinsn)
3898                 break;
3899
3900               if (! INSN_P (scan))
3901                 continue;
3902
3903               /* Don't try to trace forward past a JUMP.  To optimize
3904                  safely, we would have to check that all the
3905                  instructions at the jump destination did not use REG.  */
3906
3907               if (GET_CODE (scan) == JUMP_INSN)
3908                 break;
3909
3910               if (! reg_mentioned_p (reg, scan))
3911                 continue;
3912
3913               if (noncall_uses_reg (reg, scan, &scanset))
3914                 break;
3915
3916               if (scan == insn)
3917                 foundinsn = 1;
3918
3919               if (scan != insn
3920                   && (GET_CODE (scan) == CALL_INSN || sfunc_uses_reg (scan)))
3921                 {
3922                   /* There is a function call to this register other
3923                      than the one we are checking.  If we optimize
3924                      this call, we need to rescan again below.  */
3925                   rescan = 1;
3926                 }
3927
3928               /* ??? We shouldn't have to worry about SCANSET here.
3929                  We should just be able to check for a REG_DEAD note
3930                  on a function call.  However, the REG_DEAD notes are
3931                  apparently not dependable around libcalls; c-torture
3932                  execute/920501-2 is a test case.  If SCANSET is set,
3933                  then this insn sets the register, so it must have
3934                  died earlier.  Unfortunately, this will only handle
3935                  the cases in which the register is, in fact, set in a
3936                  later insn.  */
3937
3938               /* ??? We shouldn't have to use FOUNDINSN here.
3939                  However, the LOG_LINKS fields are apparently not
3940                  entirely reliable around libcalls;
3941                  newlib/libm/math/e_pow.c is a test case.  Sometimes
3942                  an insn will appear in LOG_LINKS even though it is
3943                  not the most recent insn which sets the register.  */
3944
3945               if (foundinsn
3946                   && (scanset
3947                       || find_reg_note (scan, REG_DEAD, reg)))
3948                 {
3949                   dies = scan;
3950                   break;
3951                 }
3952             }
3953
3954           if (! dies)
3955             {
3956               /* Either there was a branch, or some insn used REG
3957                  other than as a function call address.  */
3958               continue;
3959             }
3960
3961           /* Create a code label, and put it in a REG_LABEL note on
3962              the insn which sets the register, and on each call insn
3963              which uses the register.  In final_prescan_insn we look
3964              for the REG_LABEL notes, and output the appropriate label
3965              or pseudo-op.  */
3966
3967           label = gen_label_rtx ();
3968           REG_NOTES (link) = gen_rtx_INSN_LIST (REG_LABEL, label,
3969                                                 REG_NOTES (link));
3970           REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, label,
3971                                                 REG_NOTES (insn));
3972           if (rescan)
3973             {
3974               scan = link;
3975               do
3976                 {
3977                   rtx reg2;
3978
3979                   scan = NEXT_INSN (scan);
3980                   if (scan != insn
3981                       && ((GET_CODE (scan) == CALL_INSN
3982                            && reg_mentioned_p (reg, scan))
3983                           || ((reg2 = sfunc_uses_reg (scan))
3984                               && REGNO (reg2) == REGNO (reg))))
3985                     REG_NOTES (scan)
3986                       = gen_rtx_INSN_LIST (REG_LABEL, label, REG_NOTES (scan));
3987                 }
3988               while (scan != dies);
3989             }
3990         }
3991     }
3992
3993   if (TARGET_SH2)
3994     fixup_addr_diff_vecs (first);
3995
3996   if (optimize)
3997     {
3998       mdep_reorg_phase = SH_SHORTEN_BRANCHES0;
3999       shorten_branches (first);
4000     }
4001   /* Scan the function looking for move instructions which have to be
4002      changed to pc-relative loads and insert the literal tables.  */
4003
4004   mdep_reorg_phase = SH_FIXUP_PCLOAD;
4005   for (insn = first, num_mova = 0; insn; insn = NEXT_INSN (insn))
4006     {
4007       if (mova_p (insn))
4008         {
4009           if (! num_mova++)
4010             mova = insn;
4011         }
4012       else if (GET_CODE (insn) == JUMP_INSN
4013                && GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
4014                && num_mova)
4015         {
4016           rtx scan;
4017           int total;
4018
4019           num_mova--;
4020
4021           /* Some code might have been inserted between the mova and
4022              its ADDR_DIFF_VEC.  Check if the mova is still in range.  */
4023           for (scan = mova, total = 0; scan != insn; scan = NEXT_INSN (scan))
4024             total += get_attr_length (scan);
4025
4026           /* range of mova is 1020, add 4 because pc counts from address of
4027              second instruction after this one, subtract 2 in case pc is 2
4028              byte aligned.  Possible alignment needed for the ADDR_DIFF_VEC
4029              cancels out with alignment effects of the mova itself.  */
4030           if (total > 1022)
4031             {
4032               /* Change the mova into a load, and restart scanning
4033                  there.  broken_move will then return true for mova.  */
4034               SET_SRC (PATTERN (mova))
4035                 = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
4036               INSN_CODE (mova) = -1;
4037               insn = mova;
4038             }
4039         }
4040       if (broken_move (insn))
4041         {
4042           rtx scan;
4043           /* Scan ahead looking for a barrier to stick the constant table
4044              behind.  */
4045           rtx barrier = find_barrier (num_mova, mova, insn);
4046           rtx last_float_move = NULL_RTX, last_float = 0, *last_float_addr = NULL;
4047
4048           if (num_mova && ! mova_p (mova))
4049             {
4050               /* find_barrier had to change the first mova into a
4051                  pcload; thus, we have to start with this new pcload.  */
4052               insn = mova;
4053               num_mova = 0;
4054             }
4055           /* Now find all the moves between the points and modify them.  */
4056           for (scan = insn; scan != barrier; scan = NEXT_INSN (scan))
4057             {
4058               if (GET_CODE (scan) == CODE_LABEL)
4059                 last_float = 0;
4060               if (broken_move (scan))
4061                 {
4062                   rtx *patp = &PATTERN (scan), pat = *patp;
4063                   rtx src, dst;
4064                   rtx lab;
4065                   rtx newsrc;
4066                   enum machine_mode mode;
4067
4068                   if (GET_CODE (pat) == PARALLEL)
4069                     patp = &XVECEXP (pat, 0, 0), pat = *patp;
4070                   src = SET_SRC (pat);
4071                   dst = SET_DEST (pat);
4072                   mode = GET_MODE (dst);
4073
4074                   if (mode == SImode && hi_const (src)
4075                       && REGNO (dst) != FPUL_REG)
4076                     {
4077                       int offset = 0;
4078
4079                       mode = HImode;
4080                       while (GET_CODE (dst) == SUBREG)
4081                         {
4082                           offset += subreg_regno_offset (REGNO (SUBREG_REG (dst)),
4083                                                          GET_MODE (SUBREG_REG (dst)),
4084                                                          SUBREG_BYTE (dst),
4085                                                          GET_MODE (dst));
4086                           dst = SUBREG_REG (dst);
4087                         }
4088                       dst = gen_rtx_REG (HImode, REGNO (dst) + offset);
4089                     }
4090
4091                   if (GET_CODE (dst) == REG && FP_ANY_REGISTER_P (REGNO (dst)))
4092                     {
4093                       /* This must be an insn that clobbers r0.  */
4094                       rtx clobber = XVECEXP (PATTERN (scan), 0,
4095                                              XVECLEN (PATTERN (scan), 0) - 1);
4096
4097                       if (GET_CODE (clobber) != CLOBBER
4098                           || ! rtx_equal_p (XEXP (clobber, 0), r0_rtx))
4099                         abort ();
4100
4101                       if (last_float
4102                           && reg_set_between_p (r0_rtx, last_float_move, scan))
4103                         last_float = 0;
4104                       if (last_float
4105                           && TARGET_SHCOMPACT
4106                           && GET_MODE_SIZE (mode) != 4
4107                           && GET_MODE_SIZE (GET_MODE (last_float)) == 4)
4108                         last_float = 0;
4109                       lab = add_constant (src, mode, last_float);
4110                       if (lab)
4111                         emit_insn_before (gen_mova (lab), scan);
4112                       else
4113                         {
4114                           /* There will be a REG_UNUSED note for r0 on
4115                              LAST_FLOAT_MOVE; we have to change it to REG_INC,
4116                              lest reorg:mark_target_live_regs will not
4117                              consider r0 to be used, and we end up with delay
4118                              slot insn in front of SCAN that clobbers r0.  */
4119                           rtx note
4120                             = find_regno_note (last_float_move, REG_UNUSED, 0);
4121
4122                           /* If we are not optimizing, then there may not be
4123                              a note.  */
4124                           if (note)
4125                             PUT_MODE (note, REG_INC);
4126
4127                           *last_float_addr = r0_inc_rtx;
4128                         }
4129                       last_float_move = scan;
4130                       last_float = src;
4131                       newsrc = gen_rtx (MEM, mode,
4132                                         (((TARGET_SH4 && ! TARGET_FMOVD)
4133                                           || REGNO (dst) == FPUL_REG)
4134                                          ? r0_inc_rtx
4135                                          : r0_rtx));
4136                       last_float_addr = &XEXP (newsrc, 0);
4137
4138                       /* Remove the clobber of r0.  */
4139                       XEXP (clobber, 0) = gen_rtx_SCRATCH (Pmode);
4140                       RTX_UNCHANGING_P (newsrc) = 1;
4141                     }
4142                   /* This is a mova needing a label.  Create it.  */
4143                   else if (GET_CODE (src) == UNSPEC
4144                            && XINT (src, 1) == UNSPEC_MOVA
4145                            && GET_CODE (XVECEXP (src, 0, 0)) == CONST)
4146                     {
4147                       lab = add_constant (XVECEXP (src, 0, 0), mode, 0);
4148                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
4149                       newsrc = gen_rtx_UNSPEC (SImode,
4150                                                gen_rtvec (1, newsrc),
4151                                                UNSPEC_MOVA);
4152                     }
4153                   else
4154                     {
4155                       lab = add_constant (src, mode, 0);
4156                       newsrc = gen_rtx_MEM (mode,
4157                                             gen_rtx_LABEL_REF (VOIDmode, lab));
4158                       RTX_UNCHANGING_P (newsrc) = 1;
4159                     }
4160                   *patp = gen_rtx_SET (VOIDmode, dst, newsrc);
4161                   INSN_CODE (scan) = -1;
4162                 }
4163             }
4164           dump_table (barrier);
4165           insn = barrier;
4166         }
4167     }
4168
4169   mdep_reorg_phase = SH_SHORTEN_BRANCHES1;
4170   INSN_ADDRESSES_FREE ();
4171   split_branches (first);
4172
4173   /* The INSN_REFERENCES_ARE_DELAYED in sh.h is problematic because it
4174      also has an effect on the register that holds the address of the sfunc.
4175      Insert an extra dummy insn in front of each sfunc that pretends to
4176      use this register.  */
4177   if (flag_delayed_branch)
4178     {
4179       for (insn = first; insn; insn = NEXT_INSN (insn))
4180         {
4181           rtx reg = sfunc_uses_reg (insn);
4182
4183           if (! reg)
4184             continue;
4185           emit_insn_before (gen_use_sfunc_addr (reg), insn);
4186         }
4187     }
4188 #if 0
4189   /* fpscr is not actually a user variable, but we pretend it is for the
4190      sake of the previous optimization passes, since we want it handled like
4191      one.  However, we don't have any debugging information for it, so turn
4192      it into a non-user variable now.  */
4193   if (TARGET_SH4)
4194     REG_USERVAR_P (get_fpscr_rtx ()) = 0;
4195 #endif
4196   mdep_reorg_phase = SH_AFTER_MDEP_REORG;
4197 }
4198
4199 int
4200 get_dest_uid (rtx label, int max_uid)
4201 {
4202   rtx dest = next_real_insn (label);
4203   int dest_uid;
4204   if (! dest)
4205     /* This can happen for an undefined label.  */
4206     return 0;
4207   dest_uid = INSN_UID (dest);
4208   /* If this is a newly created branch redirection blocking instruction,
4209      we cannot index the branch_uid or insn_addresses arrays with its
4210      uid.  But then, we won't need to, because the actual destination is
4211      the following branch.  */
4212   while (dest_uid >= max_uid)
4213     {
4214       dest = NEXT_INSN (dest);
4215       dest_uid = INSN_UID (dest);
4216     }
4217   if (GET_CODE (dest) == JUMP_INSN && GET_CODE (PATTERN (dest)) == RETURN)
4218     return 0;
4219   return dest_uid;
4220 }
4221
4222 /* Split condbranches that are out of range.  Also add clobbers for
4223    scratch registers that are needed in far jumps.
4224    We do this before delay slot scheduling, so that it can take our
4225    newly created instructions into account.  It also allows us to
4226    find branches with common targets more easily.  */
4227
4228 static void
4229 split_branches (rtx first)
4230 {
4231   rtx insn;
4232   struct far_branch **uid_branch, *far_branch_list = 0;
4233   int max_uid = get_max_uid ();
4234
4235   /* Find out which branches are out of range.  */
4236   shorten_branches (first);
4237
4238   uid_branch = (struct far_branch **) alloca (max_uid * sizeof *uid_branch);
4239   memset ((char *) uid_branch, 0, max_uid * sizeof *uid_branch);
4240
4241   for (insn = first; insn; insn = NEXT_INSN (insn))
4242     if (! INSN_P (insn))
4243       continue;
4244     else if (INSN_DELETED_P (insn))
4245       {
4246         /* Shorten_branches would split this instruction again,
4247            so transform it into a note.  */
4248         PUT_CODE (insn, NOTE);
4249         NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
4250         NOTE_SOURCE_FILE (insn) = 0;
4251       }
4252     else if (GET_CODE (insn) == JUMP_INSN
4253              /* Don't mess with ADDR_DIFF_VEC */
4254              && (GET_CODE (PATTERN (insn)) == SET
4255                  || GET_CODE (PATTERN (insn)) == RETURN))
4256       {
4257         enum attr_type type = get_attr_type (insn);
4258         if (type == TYPE_CBRANCH)
4259           {
4260             rtx next, beyond;
4261     
4262             if (get_attr_length (insn) > 4)
4263               {
4264                 rtx src = SET_SRC (PATTERN (insn));
4265                 rtx olabel = XEXP (XEXP (src, 1), 0);
4266                 int addr = INSN_ADDRESSES (INSN_UID (insn));
4267                 rtx label = 0;
4268                 int dest_uid = get_dest_uid (olabel, max_uid);
4269                 struct far_branch *bp = uid_branch[dest_uid];
4270     
4271                 /* redirect_jump needs a valid JUMP_LABEL, and it might delete
4272                    the label if the LABEL_NUSES count drops to zero.  There is
4273                    always a jump_optimize pass that sets these values, but it
4274                    proceeds to delete unreferenced code, and then if not
4275                    optimizing, to un-delete the deleted instructions, thus
4276                    leaving labels with too low uses counts.  */
4277                 if (! optimize)
4278                   {
4279                     JUMP_LABEL (insn) = olabel;
4280                     LABEL_NUSES (olabel)++;
4281                   }
4282                 if (! bp)
4283                   {
4284                     bp = (struct far_branch *) alloca (sizeof *bp);
4285                     uid_branch[dest_uid] = bp;
4286                     bp->prev = far_branch_list;
4287                     far_branch_list = bp;
4288                     bp->far_label
4289                       = XEXP (XEXP (SET_SRC (PATTERN (insn)), 1), 0);
4290                     LABEL_NUSES (bp->far_label)++;
4291                   }
4292                 else
4293                   {
4294                     label = bp->near_label;
4295                     if (! label && bp->address - addr >= CONDJUMP_MIN)
4296                       {
4297                         rtx block = bp->insert_place;
4298
4299                         if (GET_CODE (PATTERN (block)) == RETURN)
4300                           block = PREV_INSN (block);
4301                         else
4302                           block = gen_block_redirect (block,
4303                                                       bp->address, 2);
4304                         label = emit_label_after (gen_label_rtx (),
4305                                                   PREV_INSN (block));
4306                         bp->near_label = label;
4307                       }
4308                     else if (label && ! NEXT_INSN (label))
4309                       {
4310                         if (addr + 2 - bp->address <= CONDJUMP_MAX)
4311                           bp->insert_place = insn;
4312                         else
4313                           gen_far_branch (bp);
4314                       }
4315                   }
4316                 if (! label
4317                     || (NEXT_INSN (label) && bp->address - addr < CONDJUMP_MIN))
4318                   {
4319                     bp->near_label = label = gen_label_rtx ();
4320                     bp->insert_place = insn;
4321                     bp->address = addr;
4322                   }
4323                 if (! redirect_jump (insn, label, 1))
4324                   abort ();
4325               }
4326             else
4327               {
4328                 /* get_attr_length (insn) == 2 */
4329                 /* Check if we have a pattern where reorg wants to redirect
4330                    the branch to a label from an unconditional branch that
4331                    is too far away.  */
4332                 /* We can't use JUMP_LABEL here because it might be undefined
4333                    when not optimizing.  */
4334                 /* A syntax error might cause beyond to be NULL_RTX.  */
4335                 beyond
4336                   = next_active_insn (XEXP (XEXP (SET_SRC (PATTERN (insn)), 1),
4337                                             0));
4338         
4339                 if (beyond
4340                     && (GET_CODE (beyond) == JUMP_INSN
4341                         || ((beyond = next_active_insn (beyond))
4342                             && GET_CODE (beyond) == JUMP_INSN))
4343                     && GET_CODE (PATTERN (beyond)) == SET
4344                     && recog_memoized (beyond) == CODE_FOR_jump_compact
4345                     && ((INSN_ADDRESSES
4346                          (INSN_UID (XEXP (SET_SRC (PATTERN (beyond)), 0)))
4347                          - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4348                         > 252 + 258 + 2))
4349                   gen_block_redirect (beyond,
4350                                       INSN_ADDRESSES (INSN_UID (beyond)), 1);
4351               }
4352     
4353             next = next_active_insn (insn);
4354
4355             if ((GET_CODE (next) == JUMP_INSN
4356                  || GET_CODE (next = next_active_insn (next)) == JUMP_INSN)
4357                 && GET_CODE (PATTERN (next)) == SET
4358                 && recog_memoized (next) == CODE_FOR_jump_compact
4359                 && ((INSN_ADDRESSES
4360                      (INSN_UID (XEXP (SET_SRC (PATTERN (next)), 0)))
4361                      - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
4362                     > 252 + 258 + 2))
4363               gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), 1);
4364           }
4365         else if (type == TYPE_JUMP || type == TYPE_RETURN)
4366           {
4367             int addr = INSN_ADDRESSES (INSN_UID (insn));
4368             rtx far_label = 0;
4369             int dest_uid = 0;
4370             struct far_branch *bp;
4371
4372             if (type == TYPE_JUMP)
4373               {
4374                 far_label = XEXP (SET_SRC (PATTERN (insn)), 0);
4375                 dest_uid = get_dest_uid (far_label, max_uid);
4376                 if (! dest_uid)
4377                   {
4378                     /* Parse errors can lead to labels outside
4379                       the insn stream.  */
4380                     if (! NEXT_INSN (far_label))
4381                       continue;
4382
4383                     if (! optimize)
4384                       {
4385                         JUMP_LABEL (insn) = far_label;
4386                         LABEL_NUSES (far_label)++;
4387                       }
4388                     redirect_jump (insn, NULL_RTX, 1);
4389                     far_label = 0;
4390                   }
4391               }
4392             bp = uid_branch[dest_uid];
4393             if (! bp)
4394               {
4395                 bp = (struct far_branch *) alloca (sizeof *bp);
4396                 uid_branch[dest_uid] = bp;
4397                 bp->prev = far_branch_list;
4398                 far_branch_list = bp;
4399                 bp->near_label = 0;
4400                 bp->far_label = far_label;
4401                 if (far_label)
4402                   LABEL_NUSES (far_label)++;
4403               }
4404             else if (bp->near_label && ! NEXT_INSN (bp->near_label))
4405               if (addr - bp->address <= CONDJUMP_MAX)
4406                 emit_label_after (bp->near_label, PREV_INSN (insn));
4407               else
4408                 {
4409                   gen_far_branch (bp);
4410                   bp->near_label = 0;
4411                 }
4412             else
4413               bp->near_label = 0;
4414             bp->address = addr;
4415             bp->insert_place = insn;
4416             if (! far_label)
4417               emit_insn_before (gen_block_branch_redirect (const0_rtx), insn);
4418             else
4419               gen_block_redirect (insn, addr, bp->near_label ? 2 : 0);
4420           }
4421       }
4422   /* Generate all pending far branches,
4423      and free our references to the far labels.  */
4424   while (far_branch_list)
4425     {
4426       if (far_branch_list->near_label
4427           && ! NEXT_INSN (far_branch_list->near_label))
4428         gen_far_branch (far_branch_list);
4429       if (optimize
4430           && far_branch_list->far_label
4431           && ! --LABEL_NUSES (far_branch_list->far_label))
4432         delete_insn (far_branch_list->far_label);
4433       far_branch_list = far_branch_list->prev;
4434     }
4435
4436   /* Instruction length information is no longer valid due to the new
4437      instructions that have been generated.  */
4438   init_insn_lengths ();
4439 }
4440
4441 /* Dump out instruction addresses, which is useful for debugging the
4442    constant pool table stuff.
4443
4444    If relaxing, output the label and pseudo-ops used to link together
4445    calls and the instruction which set the registers.  */
4446
4447 /* ??? The addresses printed by this routine for insns are nonsense for
4448    insns which are inside of a sequence where none of the inner insns have
4449    variable length.  This is because the second pass of shorten_branches
4450    does not bother to update them.  */
4451
4452 void
4453 final_prescan_insn (rtx insn, rtx *opvec ATTRIBUTE_UNUSED,
4454                     int noperands ATTRIBUTE_UNUSED)
4455 {
4456   if (TARGET_DUMPISIZE)
4457     fprintf (asm_out_file, "\n! at %04x\n", INSN_ADDRESSES (INSN_UID (insn)));
4458
4459   if (TARGET_RELAX)
4460     {
4461       rtx note;
4462
4463       note = find_reg_note (insn, REG_LABEL, NULL_RTX);
4464       if (note)
4465         {
4466           rtx pattern;
4467
4468           pattern = PATTERN (insn);
4469           if (GET_CODE (pattern) == PARALLEL)
4470             pattern = XVECEXP (pattern, 0, 0);
4471           if (GET_CODE (pattern) == CALL
4472               || (GET_CODE (pattern) == SET
4473                   && (GET_CODE (SET_SRC (pattern)) == CALL
4474                       || get_attr_type (insn) == TYPE_SFUNC)))
4475             asm_fprintf (asm_out_file, "\t.uses %LL%d\n",
4476                          CODE_LABEL_NUMBER (XEXP (note, 0)));
4477           else if (GET_CODE (pattern) == SET)
4478             (*targetm.asm_out.internal_label) (asm_out_file, "L",
4479                                        CODE_LABEL_NUMBER (XEXP (note, 0)));
4480           else
4481             abort ();
4482         }
4483     }
4484 }
4485
4486 /* Dump out any constants accumulated in the final pass.  These will
4487    only be labels.  */
4488
4489 const char *
4490 output_jump_label_table (void)
4491 {
4492   int i;
4493
4494   if (pool_size)
4495     {
4496       fprintf (asm_out_file, "\t.align 2\n");
4497       for (i = 0; i < pool_size; i++)
4498         {
4499           pool_node *p = &pool_vector[i];
4500
4501           (*targetm.asm_out.internal_label) (asm_out_file, "L",
4502                                      CODE_LABEL_NUMBER (p->label));
4503           output_asm_insn (".long       %O0", &p->value);
4504         }
4505       pool_size = 0;
4506     }
4507
4508   return "";
4509 }
4510 \f
4511 /* A full frame looks like:
4512
4513    arg-5
4514    arg-4
4515    [ if current_function_anonymous_args
4516    arg-3
4517    arg-2
4518    arg-1
4519    arg-0 ]
4520    saved-fp
4521    saved-r10
4522    saved-r11
4523    saved-r12
4524    saved-pr
4525    local-n
4526    ..
4527    local-1
4528    local-0        <- fp points here.  */
4529
4530 /* Number of bytes pushed for anonymous args, used to pass information
4531    between expand_prologue and expand_epilogue.  */
4532
4533 static int extra_push;
4534
4535 /* Adjust the stack by SIZE bytes.  REG holds the rtl of the register to be
4536    adjusted.  If epilogue_p is zero, this is for a prologue; otherwise, it's
4537    for an epilogue.  If LIVE_REGS_MASK is nonzero, it points to a HARD_REG_SET
4538    of all the registers that are about to be restored, and hence dead.  */
4539
4540 static void
4541 output_stack_adjust (int size, rtx reg, int epilogue_p,
4542                      HARD_REG_SET *live_regs_mask)
4543 {
4544   rtx (*emit_fn) (rtx) = epilogue_p ? &emit_insn : &frame_insn;
4545   if (size)
4546     {
4547       HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4548
4549       if (size % align)
4550         abort ();
4551
4552       if (CONST_OK_FOR_ADD (size))
4553         emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size)));
4554       /* Try to do it with two partial adjustments; however, we must make
4555          sure that the stack is properly aligned at all times, in case
4556          an interrupt occurs between the two partial adjustments.  */
4557       else if (CONST_OK_FOR_ADD (size / 2 & -align)
4558                && CONST_OK_FOR_ADD (size - (size / 2 & -align)))
4559         {
4560           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size / 2 & -align)));
4561           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size - (size / 2 & -align))));
4562         }
4563       else
4564         {
4565           rtx const_reg;
4566           rtx insn;
4567           int temp = epilogue_p ? 7 : (TARGET_SH5 ? 0 : 1);
4568           int i;
4569
4570           /* If TEMP is invalid, we could temporarily save a general
4571              register to MACL.  However, there is currently no need
4572              to handle this case, so just abort when we see it.  */
4573           if (current_function_interrupt
4574               || ! call_used_regs[temp] || fixed_regs[temp])
4575             temp = -1;
4576           if (temp < 0 && ! current_function_interrupt)
4577             {
4578               HARD_REG_SET temps;
4579               COPY_HARD_REG_SET (temps, call_used_reg_set);
4580               AND_COMPL_HARD_REG_SET (temps, call_fixed_reg_set);
4581               if (epilogue_p)
4582                 {
4583                   for (i = 0; i < HARD_REGNO_NREGS (FIRST_RET_REG, DImode); i++)
4584                     CLEAR_HARD_REG_BIT (temps, FIRST_RET_REG + i);
4585                   if (current_function_calls_eh_return)
4586                     {
4587                       CLEAR_HARD_REG_BIT (temps, EH_RETURN_STACKADJ_REGNO);
4588                       for (i = 0; i <= 3; i++)
4589                         CLEAR_HARD_REG_BIT (temps, EH_RETURN_DATA_REGNO (i));
4590                     }
4591                 }
4592               else
4593                 {
4594                   for (i = FIRST_PARM_REG;
4595                        i < FIRST_PARM_REG + NPARM_REGS (SImode); i++)
4596                     CLEAR_HARD_REG_BIT (temps, i);
4597                   if (current_function_needs_context)
4598                     CLEAR_HARD_REG_BIT (temps, STATIC_CHAIN_REGNUM);
4599                 }
4600               temp = scavenge_reg (&temps);
4601             }
4602           if (temp < 0 && live_regs_mask)
4603             temp = scavenge_reg (live_regs_mask);
4604           if (temp < 0)
4605             abort ();
4606           const_reg = gen_rtx_REG (GET_MODE (reg), temp);
4607
4608           /* If SIZE is negative, subtract the positive value.
4609              This sometimes allows a constant pool entry to be shared
4610              between prologue and epilogue code.  */
4611           if (size < 0)
4612             {
4613               emit_insn (GEN_MOV (const_reg, GEN_INT (-size)));
4614               insn = emit_fn (GEN_SUB3 (reg, reg, const_reg));
4615             }
4616           else
4617             {
4618               emit_insn (GEN_MOV (const_reg, GEN_INT (size)));
4619               insn = emit_fn (GEN_ADD3 (reg, reg, const_reg));
4620             }
4621           if (! epilogue_p)
4622             REG_NOTES (insn)
4623               = (gen_rtx_EXPR_LIST
4624                  (REG_FRAME_RELATED_EXPR,
4625                   gen_rtx_SET (VOIDmode, reg,
4626                                gen_rtx_PLUS (SImode, reg, GEN_INT (size))),
4627                   REG_NOTES (insn)));
4628         }
4629     }
4630 }
4631
4632 static rtx
4633 frame_insn (rtx x)
4634 {
4635   x = emit_insn (x);
4636   RTX_FRAME_RELATED_P (x) = 1;
4637   return x;
4638 }
4639
4640 /* Output RTL to push register RN onto the stack.  */
4641
4642 static rtx
4643 push (int rn)
4644 {
4645   rtx x;
4646   if (rn == FPUL_REG)
4647     x = gen_push_fpul ();
4648   else if (rn == FPSCR_REG)
4649     x = gen_push_fpscr ();
4650   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4651            && FP_OR_XD_REGISTER_P (rn))
4652     {
4653       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4654         return NULL_RTX;
4655       x = gen_push_4 (gen_rtx_REG (DFmode, rn));
4656     }
4657   else if (TARGET_SH2E && FP_REGISTER_P (rn))
4658     x = gen_push_e (gen_rtx_REG (SFmode, rn));
4659   else
4660     x = gen_push (gen_rtx_REG (SImode, rn));
4661
4662   x = frame_insn (x);
4663   REG_NOTES (x)
4664     = gen_rtx_EXPR_LIST (REG_INC,
4665                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4666   return x;
4667 }
4668
4669 /* Output RTL to pop register RN from the stack.  */
4670
4671 static void
4672 pop (int rn)
4673 {
4674   rtx x;
4675   if (rn == FPUL_REG)
4676     x = gen_pop_fpul ();
4677   else if (rn == FPSCR_REG)
4678     x = gen_pop_fpscr ();
4679   else if (TARGET_SH4 && TARGET_FMOVD && ! TARGET_FPU_SINGLE
4680            && FP_OR_XD_REGISTER_P (rn))
4681     {
4682       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
4683         return;
4684       x = gen_pop_4 (gen_rtx_REG (DFmode, rn));
4685     }
4686   else if (TARGET_SH2E && FP_REGISTER_P (rn))
4687     x = gen_pop_e (gen_rtx_REG (SFmode, rn));
4688   else
4689     x = gen_pop (gen_rtx_REG (SImode, rn));
4690     
4691   x = emit_insn (x);
4692   REG_NOTES (x)
4693     = gen_rtx_EXPR_LIST (REG_INC,
4694                          gen_rtx_REG (SImode, STACK_POINTER_REGNUM), 0);
4695 }
4696
4697 /* Generate code to push the regs specified in the mask.  */
4698
4699 static void
4700 push_regs (HARD_REG_SET *mask, int interrupt_handler)
4701 {
4702   int i;
4703   int skip_fpscr = 0;
4704
4705   /* Push PR last; this gives better latencies after the prologue, and
4706      candidates for the return delay slot when there are no general
4707      registers pushed.  */
4708   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4709     {
4710       /* If this is an interrupt handler, and the SZ bit varies,
4711          and we have to push any floating point register, we need
4712          to switch to the correct precision first.  */
4713       if (i == FIRST_FP_REG && interrupt_handler && TARGET_FMOVD
4714           && hard_regs_intersect_p (mask, &reg_class_contents[DF_REGS]))
4715         {
4716           HARD_REG_SET unsaved;
4717
4718           push (FPSCR_REG);
4719           COMPL_HARD_REG_SET(unsaved, *mask);
4720           fpscr_set_from_mem (NORMAL_MODE (FP_MODE), unsaved);
4721           skip_fpscr = 1;
4722         }
4723       if (i != PR_REG
4724           && (i != FPSCR_REG || ! skip_fpscr)
4725           && TEST_HARD_REG_BIT (*mask, i))
4726         push (i);
4727     }
4728   if (TEST_HARD_REG_BIT (*mask, PR_REG))
4729     push (PR_REG);
4730 }
4731
4732 /* Calculate how much extra space is needed to save all callee-saved
4733    target registers.
4734    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
4735
4736 static int
4737 shmedia_target_regs_stack_space (HARD_REG_SET *live_regs_mask)
4738 {
4739   int reg;
4740   int stack_space = 0;
4741   int interrupt_handler = sh_cfun_interrupt_handler_p ();
4742
4743   for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
4744     if ((! call_used_regs[reg] || interrupt_handler)
4745         && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
4746       /* Leave space to save this target register on the stack,
4747          in case target register allocation wants to use it.  */
4748       stack_space += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
4749   return stack_space;
4750 }
4751    
4752 /* Decide whether we should reserve space for callee-save target registers,
4753    in case target register allocation wants to use them.  REGS_SAVED is
4754    the space, in bytes, that is already required for register saves.
4755    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
4756
4757 static int
4758 shmedia_reserve_space_for_target_registers_p (int regs_saved,
4759                                               HARD_REG_SET *live_regs_mask)
4760 {
4761   if (optimize_size)
4762     return 0;
4763   return shmedia_target_regs_stack_space (live_regs_mask) <= regs_saved;
4764 }
4765
4766 /* Decide how much space to reserve for callee-save target registers
4767    in case target register allocation wants to use them.
4768    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
4769
4770 static int
4771 shmedia_target_regs_stack_adjust (HARD_REG_SET *live_regs_mask)
4772 {
4773   if (shmedia_space_reserved_for_target_registers)
4774     return shmedia_target_regs_stack_space (live_regs_mask);
4775   else
4776     return 0;
4777 }
4778
4779 /* Work out the registers which need to be saved, both as a mask and a
4780    count of saved words.  Return the count.
4781
4782    If doing a pragma interrupt function, then push all regs used by the
4783    function, and if we call another function (we can tell by looking at PR),
4784    make sure that all the regs it clobbers are safe too.  */
4785
4786 static int
4787 calc_live_regs (HARD_REG_SET *live_regs_mask)
4788 {
4789   int reg;
4790   int count;
4791   int interrupt_handler;
4792   int pr_live, has_call;
4793
4794   interrupt_handler = sh_cfun_interrupt_handler_p ();
4795
4796   CLEAR_HARD_REG_SET (*live_regs_mask);
4797   if (TARGET_SH4 && TARGET_FMOVD && interrupt_handler
4798       && regs_ever_live[FPSCR_REG])
4799     target_flags &= ~FPU_SINGLE_BIT;
4800   /* If we can save a lot of saves by switching to double mode, do that.  */
4801   else if (TARGET_SH4 && TARGET_FMOVD && TARGET_FPU_SINGLE)
4802     for (count = 0, reg = FIRST_FP_REG; reg <= LAST_FP_REG; reg += 2)
4803       if (regs_ever_live[reg] && regs_ever_live[reg+1]
4804           && (! call_used_regs[reg] || (interrupt_handler && ! pragma_trapa))
4805           && ++count > 2)
4806         {
4807           target_flags &= ~FPU_SINGLE_BIT;
4808           break;
4809         }
4810   /* PR_MEDIA_REG is a general purpose register, thus global_alloc already
4811      knows how to use it.  That means the pseudo originally allocated for
4812      the initial value can become the PR_MEDIA_REG hard register, as seen for
4813      execute/20010122-1.c:test9.  */
4814   if (TARGET_SHMEDIA)
4815     /* ??? this function is called from initial_elimination_offset, hence we
4816        can't use the result of sh_media_register_for_return here.  */
4817     pr_live = sh_pr_n_sets ();
4818   else
4819     {
4820       rtx pr_initial = has_hard_reg_initial_val (Pmode, PR_REG);
4821       pr_live = (pr_initial
4822                  ? (GET_CODE (pr_initial) != REG
4823                     || REGNO (pr_initial) != (PR_REG))
4824                  : regs_ever_live[PR_REG]);
4825       /* For Shcompact, if not optimizing, we end up with a memory reference
4826          using the return address pointer for __builtin_return_address even
4827          though there is no actual need to put the PR register on the stack.  */
4828       pr_live |= regs_ever_live[RETURN_ADDRESS_POINTER_REGNUM];
4829     }
4830   /* Force PR to be live if the prologue has to call the SHmedia
4831      argument decoder or register saver.  */
4832   if (TARGET_SHCOMPACT
4833       && ((current_function_args_info.call_cookie
4834            & ~ CALL_COOKIE_RET_TRAMP (1))
4835           || current_function_has_nonlocal_label))
4836     pr_live = 1;
4837   has_call = TARGET_SHMEDIA ? ! leaf_function_p () : pr_live;
4838   for (count = 0, reg = FIRST_PSEUDO_REGISTER - 1; reg >= 0; reg--)
4839     {
4840       if (reg == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
4841           ? pr_live
4842           : (interrupt_handler && ! pragma_trapa)
4843           ? (/* Need to save all the regs ever live.  */
4844              (regs_ever_live[reg]
4845               || (call_used_regs[reg]
4846                   && (! fixed_regs[reg] || reg == MACH_REG || reg == MACL_REG)
4847                   && has_call)
4848               || (has_call && REGISTER_NATURAL_MODE (reg) == SImode
4849                   && (GENERAL_REGISTER_P (reg) || TARGET_REGISTER_P (reg))))
4850              && reg != STACK_POINTER_REGNUM && reg != ARG_POINTER_REGNUM
4851              && reg != RETURN_ADDRESS_POINTER_REGNUM
4852              && reg != T_REG && reg != GBR_REG
4853              /* Push fpscr only on targets which have FPU */
4854              && (reg != FPSCR_REG || TARGET_FPU_ANY))
4855           : (/* Only push those regs which are used and need to be saved.  */
4856              (TARGET_SHCOMPACT
4857               && flag_pic
4858               && current_function_args_info.call_cookie
4859               && reg == (int) PIC_OFFSET_TABLE_REGNUM)
4860              || (regs_ever_live[reg] && ! call_used_regs[reg])
4861              || (current_function_calls_eh_return
4862                  && (reg == (int) EH_RETURN_DATA_REGNO (0)
4863                      || reg == (int) EH_RETURN_DATA_REGNO (1)
4864                      || reg == (int) EH_RETURN_DATA_REGNO (2)
4865                      || reg == (int) EH_RETURN_DATA_REGNO (3)))
4866              || ((reg == MACL_REG || reg == MACH_REG)
4867                  && regs_ever_live[reg]
4868                  && sh_cfun_attr_renesas_p ())
4869              ))
4870         {
4871           SET_HARD_REG_BIT (*live_regs_mask, reg);
4872           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
4873
4874           if ((TARGET_SH4 || TARGET_SH5) && TARGET_FMOVD
4875               && GET_MODE_CLASS (REGISTER_NATURAL_MODE (reg)) == MODE_FLOAT)
4876             {
4877               if (FP_REGISTER_P (reg))
4878                 {
4879                   if (! TARGET_FPU_SINGLE && ! regs_ever_live[reg ^ 1])
4880                     {
4881                       SET_HARD_REG_BIT (*live_regs_mask, (reg ^ 1));
4882                       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg ^ 1));
4883                     }
4884                 }
4885               else if (XD_REGISTER_P (reg))
4886                 {
4887                   /* Must switch to double mode to access these registers.  */
4888                   target_flags &= ~FPU_SINGLE_BIT;
4889                 }
4890             }
4891         }
4892     }
4893   /* If we have a target register optimization pass after prologue / epilogue
4894      threading, we need to assume all target registers will be live even if
4895      they aren't now.  */
4896   if (flag_branch_target_load_optimize2
4897       && TARGET_SAVE_ALL_TARGET_REGS
4898       && shmedia_space_reserved_for_target_registers)
4899     for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
4900       if ((! call_used_regs[reg] || interrupt_handler)
4901           && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
4902         {
4903           SET_HARD_REG_BIT (*live_regs_mask, reg);
4904           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
4905         }
4906   /* If this is an interrupt handler, we don't have any call-clobbered
4907      registers we can conveniently use for target register save/restore.
4908      Make sure we save at least one general purpose register when we need
4909      to save target registers.  */
4910   if (interrupt_handler
4911       && hard_regs_intersect_p (live_regs_mask,
4912                                 &reg_class_contents[TARGET_REGS])
4913       && ! hard_regs_intersect_p (live_regs_mask,
4914                                   &reg_class_contents[GENERAL_REGS]))
4915     {
4916       SET_HARD_REG_BIT (*live_regs_mask, R0_REG);
4917       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (R0_REG));
4918     }
4919
4920   return count;
4921 }
4922
4923 /* Code to generate prologue and epilogue sequences */
4924
4925 /* PUSHED is the number of bytes that are being pushed on the
4926    stack for register saves.  Return the frame size, padded
4927    appropriately so that the stack stays properly aligned.  */
4928 static HOST_WIDE_INT
4929 rounded_frame_size (int pushed)
4930 {
4931   HOST_WIDE_INT size = get_frame_size ();
4932   HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
4933
4934   return ((size + pushed + align - 1) & -align) - pushed;
4935 }
4936
4937 /* Choose a call-clobbered target-branch register that remains
4938    unchanged along the whole function.  We set it up as the return
4939    value in the prologue.  */
4940 int
4941 sh_media_register_for_return (void)
4942 {
4943   int regno;
4944   int tr0_used;
4945
4946   if (! current_function_is_leaf)
4947     return -1;
4948   if (lookup_attribute ("interrupt_handler",
4949                         DECL_ATTRIBUTES (current_function_decl)))
4950     return -1;
4951
4952   tr0_used = flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM];
4953
4954   for (regno = FIRST_TARGET_REG + tr0_used; regno <= LAST_TARGET_REG; regno++)
4955     if (call_used_regs[regno] && ! regs_ever_live[regno])
4956       return regno;
4957
4958   return -1;
4959 }
4960
4961 /* The maximum registers we need to save are:
4962    - 62 general purpose registers (r15 is stack pointer, r63 is zero)
4963    - 32 floating point registers (for each pair, we save none,
4964          one single precision value, or a double precision value).
4965    -  8 target registers
4966    -  add 1 entry for a delimiter.  */
4967 #define MAX_SAVED_REGS (62+32+8)
4968
4969 typedef struct save_entry_s
4970 {
4971   unsigned char reg;
4972   unsigned char mode;
4973   short offset;
4974 } save_entry;
4975
4976 #define MAX_TEMPS 4
4977
4978 /* There will be a delimiter entry with VOIDmode both at the start and the
4979    end of a filled in schedule.  The end delimiter has the offset of the
4980    save with the smallest (i.e. most negative) offset.  */
4981 typedef struct save_schedule_s
4982 {
4983   save_entry entries[MAX_SAVED_REGS + 2];
4984   int temps[MAX_TEMPS+1];
4985 } save_schedule;
4986
4987 /* Fill in SCHEDULE according to LIVE_REGS_MASK.  If RESTORE is nonzero,
4988    use reverse order.  Returns the last entry written to (not counting
4989    the delimiter).  OFFSET_BASE is a number to be added to all offset
4990    entries.  */
4991    
4992 static save_entry *
4993 sh5_schedule_saves (HARD_REG_SET *live_regs_mask, save_schedule *schedule,
4994                     int offset_base)
4995 {
4996   int align, i;
4997   save_entry *entry = schedule->entries;
4998   int tmpx = 0;
4999   int offset;
5000
5001   if (! current_function_interrupt)
5002     for (i = FIRST_GENERAL_REG; tmpx < MAX_TEMPS && i <= LAST_GENERAL_REG; i++)
5003       if (call_used_regs[i] && ! fixed_regs[i] && i != PR_MEDIA_REG
5004           && ! FUNCTION_ARG_REGNO_P (i)
5005           && i != FIRST_RET_REG
5006           && ! (current_function_needs_context && i == STATIC_CHAIN_REGNUM)
5007           && ! (current_function_calls_eh_return
5008                 && (i == EH_RETURN_STACKADJ_REGNO
5009                     || ((unsigned)i <= EH_RETURN_DATA_REGNO (0)
5010                         && (unsigned)i >= EH_RETURN_DATA_REGNO (3)))))
5011         schedule->temps[tmpx++] = i;
5012   entry->reg = -1;
5013   entry->mode = VOIDmode;
5014   entry->offset = offset_base;
5015   entry++;
5016   /* We loop twice: first, we save 8-byte aligned registers in the
5017      higher addresses, that are known to be aligned.  Then, we
5018      proceed to saving 32-bit registers that don't need 8-byte
5019      alignment.
5020      If this is an interrupt function, all registers that need saving
5021      need to be saved in full.  moreover, we need to postpone saving
5022      target registers till we have saved some general purpose registers
5023      we can then use as scratch registers.  */
5024   offset = offset_base;
5025   for (align = 1; align >= 0; align--)
5026     {
5027       for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
5028         if (TEST_HARD_REG_BIT (*live_regs_mask, i))
5029           {
5030             enum machine_mode mode = REGISTER_NATURAL_MODE (i);
5031             int reg = i;
5032
5033             if (current_function_interrupt)
5034               {
5035                 if (TARGET_REGISTER_P (i))
5036                   continue;
5037                 if (GENERAL_REGISTER_P (i))
5038                   mode = DImode;
5039               }
5040             if (mode == SFmode && (i % 2) == 1
5041                 && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
5042                 && (TEST_HARD_REG_BIT (*live_regs_mask, (i ^ 1))))
5043               {
5044                 mode = DFmode;
5045                 i--;
5046                 reg--;
5047               }
5048
5049             /* If we're doing the aligned pass and this is not aligned,
5050                or we're doing the unaligned pass and this is aligned,
5051                skip it.  */
5052             if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT) == 0)
5053                 != align)
5054               continue;
5055
5056             if (current_function_interrupt
5057                 && GENERAL_REGISTER_P (i)
5058                 && tmpx < MAX_TEMPS)
5059               schedule->temps[tmpx++] = i;
5060
5061             offset -= GET_MODE_SIZE (mode);
5062             entry->reg = i;
5063             entry->mode = mode;
5064             entry->offset = offset;
5065             entry++;
5066           }
5067       if (align && current_function_interrupt)
5068         for (i = LAST_TARGET_REG; i >= FIRST_TARGET_REG; i--)
5069           if (TEST_HARD_REG_BIT (*live_regs_mask, i))
5070             {
5071               offset -= GET_MODE_SIZE (DImode);
5072               entry->reg = i;
5073               entry->mode = DImode;
5074               entry->offset = offset;
5075               entry++;
5076             }
5077     }
5078   entry->reg = -1;
5079   entry->mode = VOIDmode;
5080   entry->offset = offset;
5081   schedule->temps[tmpx] = -1;
5082   return entry - 1;
5083 }
5084
5085 void
5086 sh_expand_prologue (void)
5087 {
5088   HARD_REG_SET live_regs_mask;
5089   int d, i;
5090   int d_rounding = 0;
5091   int save_flags = target_flags;
5092
5093   current_function_interrupt = sh_cfun_interrupt_handler_p ();
5094
5095   /* We have pretend args if we had an object sent partially in registers
5096      and partially on the stack, e.g. a large structure.  */
5097   output_stack_adjust (-current_function_pretend_args_size
5098                        - current_function_args_info.stack_regs * 8,
5099                        stack_pointer_rtx, 0, NULL);
5100
5101   extra_push = 0;
5102
5103   if (TARGET_SHCOMPACT && flag_pic && current_function_args_info.call_cookie)
5104     /* We're going to use the PIC register to load the address of the
5105        incoming-argument decoder and/or of the return trampoline from
5106        the GOT, so make sure the PIC register is preserved and
5107        initialized.  */
5108     regs_ever_live[PIC_OFFSET_TABLE_REGNUM] = 1;
5109
5110   if (TARGET_SHCOMPACT
5111       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
5112     {
5113       int reg;
5114
5115       /* First, make all registers with incoming arguments that will
5116          be pushed onto the stack live, so that register renaming
5117          doesn't overwrite them.  */
5118       for (reg = 0; reg < NPARM_REGS (SImode); reg++)
5119         if (CALL_COOKIE_STACKSEQ_GET (current_function_args_info.call_cookie)
5120             >= NPARM_REGS (SImode) - reg)
5121           for (; reg < NPARM_REGS (SImode); reg++)
5122             emit_insn (gen_shcompact_preserve_incoming_args
5123                        (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
5124         else if (CALL_COOKIE_INT_REG_GET
5125                  (current_function_args_info.call_cookie, reg) == 1)
5126           emit_insn (gen_shcompact_preserve_incoming_args
5127                      (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
5128
5129       emit_move_insn (gen_rtx_REG (Pmode, MACL_REG),
5130                       stack_pointer_rtx);
5131       emit_move_insn (gen_rtx_REG (SImode, R0_REG),
5132                       GEN_INT (current_function_args_info.call_cookie));
5133       emit_move_insn (gen_rtx_REG (SImode, MACH_REG),
5134                       gen_rtx_REG (SImode, R0_REG));
5135     }
5136   else if (TARGET_SHMEDIA)
5137     {
5138       int tr = sh_media_register_for_return ();
5139
5140       if (tr >= 0)
5141         {
5142           rtx insn = emit_move_insn (gen_rtx_REG (DImode, tr),
5143                                      gen_rtx_REG (DImode, PR_MEDIA_REG));
5144
5145           /* ??? We should suppress saving pr when we don't need it, but this
5146              is tricky because of builtin_return_address.  */
5147
5148           /* If this function only exits with sibcalls, this copy
5149              will be flagged as dead.  */
5150           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5151                                                 const0_rtx,
5152                                                 REG_NOTES (insn));
5153         }
5154     }
5155
5156   /* Emit the code for SETUP_VARARGS.  */
5157   if (current_function_stdarg)
5158     {
5159       /* This is not used by the SH2E calling convention  */
5160       if (TARGET_SH1 && ! TARGET_SH2E && ! TARGET_SH5
5161           && ! (TARGET_HITACHI || sh_cfun_attr_renesas_p ()))
5162         {
5163           /* Push arg regs as if they'd been provided by caller in stack.  */
5164           for (i = 0; i < NPARM_REGS(SImode); i++)
5165             {
5166               int rn = NPARM_REGS(SImode) + FIRST_PARM_REG - i - 1;
5167               rtx insn;
5168
5169               if (i >= (NPARM_REGS(SImode) 
5170                         - current_function_args_info.arg_count[(int) SH_ARG_INT]
5171                         ))
5172                 break;
5173               insn = push (rn);
5174               RTX_FRAME_RELATED_P (insn) = 0;
5175               extra_push += 4;
5176             }
5177         }
5178     }
5179
5180   /* If we're supposed to switch stacks at function entry, do so now.  */
5181   if (sp_switch)
5182     emit_insn (gen_sp_switch_1 ());
5183
5184   d = calc_live_regs (&live_regs_mask);
5185   /* ??? Maybe we could save some switching if we can move a mode switch
5186      that already happens to be at the function start into the prologue.  */
5187   if (target_flags != save_flags && ! current_function_interrupt)
5188     emit_insn (gen_toggle_sz ());
5189     
5190   if (TARGET_SH5)
5191     {
5192       int offset_base, offset;
5193       rtx r0 = NULL_RTX;
5194       int offset_in_r0 = -1;
5195       int sp_in_r0 = 0;
5196       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
5197       int total_size, save_size;
5198       save_schedule schedule;
5199       save_entry *entry;
5200       int *tmp_pnt;
5201
5202       if (call_used_regs[R0_REG] && ! fixed_regs[R0_REG]
5203           && ! current_function_interrupt)
5204         r0 = gen_rtx_REG (Pmode, R0_REG);
5205
5206       /* D is the actual number of bytes that we need for saving registers,
5207          however, in initial_elimination_offset we have committed to using
5208          an additional TREGS_SPACE amount of bytes - in order to keep both
5209          addresses to arguments supplied by the caller and local variables
5210          valid, we must keep this gap.  Place it between the incoming
5211          arguments and the actually saved registers in a bid to optimize
5212          locality of reference.  */
5213       total_size = d + tregs_space;
5214       total_size += rounded_frame_size (total_size);
5215       save_size = total_size - rounded_frame_size (d);
5216       if (save_size % (STACK_BOUNDARY / BITS_PER_UNIT))
5217         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5218                         - save_size % (STACK_BOUNDARY / BITS_PER_UNIT));
5219
5220       /* If adjusting the stack in a single step costs nothing extra, do so.
5221          I.e. either if a single addi is enough, or we need a movi anyway,
5222          and we don't exceed the maximum offset range (the test for the
5223          latter is conservative for simplicity).  */
5224       if (TARGET_SHMEDIA
5225           && (CONST_OK_FOR_I10 (-total_size)
5226               || (! CONST_OK_FOR_I10 (-(save_size + d_rounding))
5227                   && total_size <= 2044)))
5228         d_rounding = total_size - save_size;
5229
5230       offset_base = d + d_rounding;
5231
5232       output_stack_adjust (-(save_size + d_rounding), stack_pointer_rtx,
5233                            0, NULL);
5234
5235       sh5_schedule_saves (&live_regs_mask, &schedule, offset_base);
5236       tmp_pnt = schedule.temps;
5237       for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
5238         {
5239           enum machine_mode mode = entry->mode;
5240           int reg = entry->reg;
5241           rtx reg_rtx, mem_rtx, pre_dec = NULL_RTX;
5242
5243           offset = entry->offset;
5244
5245           reg_rtx = gen_rtx_REG (mode, reg);
5246
5247           mem_rtx = gen_rtx_MEM (mode,
5248                                  gen_rtx_PLUS (Pmode,
5249                                                stack_pointer_rtx,
5250                                                GEN_INT (offset)));
5251
5252           GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_pre_dec);
5253
5254           if (! r0)
5255             abort ();
5256           mem_rtx = NULL_RTX;
5257
5258         try_pre_dec:
5259           do
5260             if (HAVE_PRE_DECREMENT
5261                 && (offset_in_r0 - offset == GET_MODE_SIZE (mode)
5262                     || mem_rtx == NULL_RTX
5263                     || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
5264               {
5265                 pre_dec = gen_rtx_MEM (mode,
5266                                        gen_rtx_PRE_DEC (Pmode, r0));
5267
5268                 GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (pre_dec, 0),
5269                                           pre_dec_ok);
5270
5271                 pre_dec = NULL_RTX;
5272
5273                 break;
5274
5275               pre_dec_ok:
5276                 mem_rtx = NULL_RTX;
5277                 offset += GET_MODE_SIZE (mode);
5278               }
5279           while (0);
5280
5281           if (mem_rtx != NULL_RTX)
5282             goto addr_ok;
5283
5284           if (offset_in_r0 == -1)
5285             {
5286               emit_move_insn (r0, GEN_INT (offset));
5287               offset_in_r0 = offset;
5288             }
5289           else if (offset != offset_in_r0)
5290             {
5291               emit_move_insn (r0,
5292                               gen_rtx_PLUS
5293                               (Pmode, r0,
5294                                GEN_INT (offset - offset_in_r0)));
5295               offset_in_r0 += offset - offset_in_r0;
5296             }
5297                                               
5298           if (pre_dec != NULL_RTX)
5299             {
5300               if (! sp_in_r0)
5301                 {
5302                   emit_move_insn (r0,
5303                                   gen_rtx_PLUS
5304                                   (Pmode, r0, stack_pointer_rtx));
5305                   sp_in_r0 = 1;
5306                 }
5307
5308               offset -= GET_MODE_SIZE (mode);
5309               offset_in_r0 -= GET_MODE_SIZE (mode);
5310
5311               mem_rtx = pre_dec;
5312             }
5313           else if (sp_in_r0)
5314             mem_rtx = gen_rtx_MEM (mode, r0);
5315           else
5316             mem_rtx = gen_rtx_MEM (mode,
5317                                    gen_rtx_PLUS (Pmode,
5318                                                  stack_pointer_rtx,
5319                                                  r0));
5320
5321           /* We must not use an r0-based address for target-branch
5322              registers or for special registers without pre-dec
5323              memory addresses, since we store their values in r0
5324              first.  */
5325           if (TARGET_REGISTER_P (reg)
5326               || ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
5327                   && mem_rtx != pre_dec))
5328             abort ();
5329
5330         addr_ok:
5331           if (TARGET_REGISTER_P (reg)
5332               || ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
5333                   && mem_rtx != pre_dec))
5334             {
5335               rtx tmp_reg = gen_rtx_REG (GET_MODE (reg_rtx), *tmp_pnt);
5336
5337               emit_move_insn (tmp_reg, reg_rtx);
5338
5339               if (REGNO (tmp_reg) == R0_REG)
5340                 {
5341                   offset_in_r0 = -1;
5342                   sp_in_r0 = 0;
5343                   if (refers_to_regno_p (R0_REG, R0_REG+1, mem_rtx, (rtx *) 0))
5344                     abort ();
5345                 }
5346
5347               if (*++tmp_pnt <= 0)
5348                 tmp_pnt = schedule.temps;
5349
5350               reg_rtx = tmp_reg;
5351             }
5352           {
5353             rtx insn;
5354
5355             /* Mark as interesting for dwarf cfi generator */
5356             insn = emit_move_insn (mem_rtx, reg_rtx);
5357             RTX_FRAME_RELATED_P (insn) = 1;
5358
5359             if (TARGET_SHCOMPACT && (offset_in_r0 != -1)) 
5360               {
5361                 rtx reg_rtx = gen_rtx_REG (mode, reg);
5362                 rtx set, note_rtx;
5363                 rtx mem_rtx = gen_rtx_MEM (mode,
5364                                            gen_rtx_PLUS (Pmode,
5365                                                          stack_pointer_rtx,
5366                                                          GEN_INT (offset)));
5367
5368                 set = gen_rtx_SET (VOIDmode, mem_rtx, reg_rtx);
5369                 note_rtx = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR, set,
5370                                               REG_NOTES (insn));
5371                 REG_NOTES (insn) = note_rtx;
5372               }
5373           }
5374         }
5375
5376       if (entry->offset != d_rounding)
5377         abort ();
5378     }
5379   else
5380     push_regs (&live_regs_mask, current_function_interrupt);
5381
5382   if (flag_pic && regs_ever_live[PIC_OFFSET_TABLE_REGNUM])
5383     {
5384       rtx insn = get_last_insn ();
5385       rtx last = emit_insn (gen_GOTaddr2picreg ());
5386
5387       /* Mark these insns as possibly dead.  Sometimes, flow2 may
5388          delete all uses of the PIC register.  In this case, let it
5389          delete the initialization too.  */
5390       do
5391         {
5392           insn = NEXT_INSN (insn);
5393
5394           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5395                                                 const0_rtx,
5396                                                 REG_NOTES (insn));
5397         }
5398       while (insn != last);
5399     }
5400
5401   if (SHMEDIA_REGS_STACK_ADJUST ())
5402     {
5403       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5404                       function_symbol (TARGET_FPU_ANY
5405                                        ? "__GCC_push_shmedia_regs"
5406                                        : "__GCC_push_shmedia_regs_nofpu"));
5407       /* This must NOT go through the PLT, otherwise mach and macl
5408          may be clobbered.  */
5409       emit_insn (gen_shmedia_save_restore_regs_compact
5410                  (GEN_INT (-SHMEDIA_REGS_STACK_ADJUST ())));
5411     }
5412
5413   if (target_flags != save_flags && ! current_function_interrupt)
5414     {
5415       rtx insn = emit_insn (gen_toggle_sz ());
5416
5417       /* If we're lucky, a mode switch in the function body will
5418          overwrite fpscr, turning this insn dead.  Tell flow this
5419          insn is ok to delete.  */
5420       REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5421                                             const0_rtx,
5422                                             REG_NOTES (insn));
5423     }
5424
5425   target_flags = save_flags;
5426
5427   output_stack_adjust (-rounded_frame_size (d) + d_rounding,
5428                        stack_pointer_rtx, 0, NULL);
5429
5430   if (frame_pointer_needed)
5431     frame_insn (GEN_MOV (frame_pointer_rtx, stack_pointer_rtx));
5432
5433   if (TARGET_SHCOMPACT
5434       && (current_function_args_info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
5435     {
5436       /* This must NOT go through the PLT, otherwise mach and macl
5437          may be clobbered.  */
5438       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5439                       function_symbol ("__GCC_shcompact_incoming_args"));
5440       emit_insn (gen_shcompact_incoming_args ());
5441     }
5442 }
5443
5444 void
5445 sh_expand_epilogue (void)
5446 {
5447   HARD_REG_SET live_regs_mask;
5448   int d, i;
5449   int d_rounding = 0;
5450
5451   int save_flags = target_flags;
5452   int frame_size, save_size;
5453   int fpscr_deferred = 0;
5454
5455   d = calc_live_regs (&live_regs_mask);
5456
5457   save_size = d;
5458   frame_size = rounded_frame_size (d);
5459
5460   if (TARGET_SH5)
5461     {
5462       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
5463       int total_size;
5464       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
5465       d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
5466                     - d % (STACK_BOUNDARY / BITS_PER_UNIT));
5467
5468       total_size = d + tregs_space;
5469       total_size += rounded_frame_size (total_size);
5470       save_size = total_size - frame_size;
5471
5472       /* If adjusting the stack in a single step costs nothing extra, do so.
5473          I.e. either if a single addi is enough, or we need a movi anyway,
5474          and we don't exceed the maximum offset range (the test for the
5475          latter is conservative for simplicity).  */
5476       if (TARGET_SHMEDIA
5477           && ! frame_pointer_needed
5478           && (CONST_OK_FOR_I10 (total_size)
5479               || (! CONST_OK_FOR_I10 (save_size + d_rounding)
5480                   && total_size <= 2044)))
5481         d_rounding = frame_size;
5482
5483       frame_size -= d_rounding;
5484     }
5485
5486   if (frame_pointer_needed)
5487     {
5488       output_stack_adjust (frame_size, frame_pointer_rtx, 1, &live_regs_mask);
5489
5490       /* We must avoid moving the stack pointer adjustment past code
5491          which reads from the local frame, else an interrupt could
5492          occur after the SP adjustment and clobber data in the local
5493          frame.  */
5494       emit_insn (gen_blockage ());
5495       emit_insn (GEN_MOV (stack_pointer_rtx, frame_pointer_rtx));
5496     }
5497   else if (frame_size)
5498     {
5499       /* We must avoid moving the stack pointer adjustment past code
5500          which reads from the local frame, else an interrupt could
5501          occur after the SP adjustment and clobber data in the local
5502          frame.  */
5503       emit_insn (gen_blockage ());
5504       output_stack_adjust (frame_size, stack_pointer_rtx, 1, &live_regs_mask);
5505     }
5506
5507   if (SHMEDIA_REGS_STACK_ADJUST ())
5508     {
5509       emit_move_insn (gen_rtx_REG (Pmode, R0_REG),
5510                       function_symbol (TARGET_FPU_ANY
5511                                        ? "__GCC_pop_shmedia_regs"
5512                                        : "__GCC_pop_shmedia_regs_nofpu"));
5513       /* This must NOT go through the PLT, otherwise mach and macl
5514          may be clobbered.  */
5515       emit_insn (gen_shmedia_save_restore_regs_compact
5516                  (GEN_INT (SHMEDIA_REGS_STACK_ADJUST ())));
5517     }
5518
5519   /* Pop all the registers.  */
5520
5521   if (target_flags != save_flags && ! current_function_interrupt)
5522     emit_insn (gen_toggle_sz ());
5523   if (TARGET_SH5)
5524     {
5525       int offset_base, offset;
5526       int offset_in_r0 = -1;
5527       int sp_in_r0 = 0;
5528       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
5529       save_schedule schedule;
5530       save_entry *entry;
5531       int *tmp_pnt;
5532
5533       entry = sh5_schedule_saves (&live_regs_mask, &schedule, d_rounding);
5534       offset_base = -entry[1].offset + d_rounding;
5535       tmp_pnt = schedule.temps;
5536       for (; entry->mode != VOIDmode; entry--)
5537         {
5538           enum machine_mode mode = entry->mode;
5539           int reg = entry->reg;
5540           rtx reg_rtx, mem_rtx, post_inc = NULL_RTX, insn;
5541
5542           offset = offset_base + entry->offset;
5543           reg_rtx = gen_rtx_REG (mode, reg);
5544
5545           mem_rtx = gen_rtx_MEM (mode,
5546                                  gen_rtx_PLUS (Pmode,
5547                                                stack_pointer_rtx,
5548                                                GEN_INT (offset)));
5549
5550           GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (mem_rtx, 0), try_post_inc);
5551
5552           mem_rtx = NULL_RTX;
5553
5554         try_post_inc:
5555           do
5556             if (HAVE_POST_INCREMENT
5557                 && (offset == offset_in_r0
5558                     || (offset + GET_MODE_SIZE (mode) != d + d_rounding
5559                         && mem_rtx == NULL_RTX)
5560                     || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
5561               {
5562                 post_inc = gen_rtx_MEM (mode,
5563                                         gen_rtx_POST_INC (Pmode, r0));
5564
5565                 GO_IF_LEGITIMATE_ADDRESS (mode, XEXP (post_inc, 0),
5566                                           post_inc_ok);
5567
5568                 post_inc = NULL_RTX;
5569
5570                 break;
5571                 
5572               post_inc_ok:
5573                 mem_rtx = NULL_RTX;
5574               }
5575           while (0);
5576           
5577           if (mem_rtx != NULL_RTX)
5578             goto addr_ok;
5579
5580           if (offset_in_r0 == -1)
5581             {
5582               emit_move_insn (r0, GEN_INT (offset));
5583               offset_in_r0 = offset;
5584             }
5585           else if (offset != offset_in_r0)
5586             {
5587               emit_move_insn (r0,
5588                               gen_rtx_PLUS
5589                               (Pmode, r0,
5590                                GEN_INT (offset - offset_in_r0)));
5591               offset_in_r0 += offset - offset_in_r0;
5592             }
5593               
5594           if (post_inc != NULL_RTX)
5595             {
5596               if (! sp_in_r0)
5597                 {
5598                   emit_move_insn (r0,
5599                                   gen_rtx_PLUS
5600                                   (Pmode, r0, stack_pointer_rtx));
5601                   sp_in_r0 = 1;
5602                 }
5603               
5604               mem_rtx = post_inc;
5605
5606               offset_in_r0 += GET_MODE_SIZE (mode);
5607             }
5608           else if (sp_in_r0)
5609             mem_rtx = gen_rtx_MEM (mode, r0);
5610           else
5611             mem_rtx = gen_rtx_MEM (mode,
5612                                    gen_rtx_PLUS (Pmode,
5613                                                  stack_pointer_rtx,
5614                                                  r0));
5615
5616           if ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
5617               && mem_rtx != post_inc)
5618             abort ();
5619
5620         addr_ok:
5621           if ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
5622               && mem_rtx != post_inc)
5623             {
5624               insn = emit_move_insn (r0, mem_rtx);
5625               mem_rtx = r0;
5626             }
5627           else if (TARGET_REGISTER_P (reg))
5628             {
5629               rtx tmp_reg = gen_rtx_REG (mode, *tmp_pnt);
5630
5631               /* Give the scheduler a bit of freedom by using up to
5632                  MAX_TEMPS registers in a round-robin fashion.  */
5633               insn = emit_move_insn (tmp_reg, mem_rtx);
5634               mem_rtx = tmp_reg;
5635               if (*++tmp_pnt < 0)
5636                 tmp_pnt = schedule.temps;
5637             }
5638
5639           insn = emit_move_insn (reg_rtx, mem_rtx);
5640           if (reg == PR_MEDIA_REG && sh_media_register_for_return () >= 0)
5641             /* This is dead, unless we return with a sibcall.  */
5642             REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD,
5643                                                   const0_rtx,
5644                                                   REG_NOTES (insn));
5645         }
5646
5647       if (entry->offset + offset_base != d + d_rounding)
5648         abort ();
5649     }
5650   else /* ! TARGET_SH5 */
5651     {
5652       save_size = 0;
5653       if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
5654         pop (PR_REG);
5655       for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5656         {
5657           int j = (FIRST_PSEUDO_REGISTER - 1) - i;
5658   
5659           if (j == FPSCR_REG && current_function_interrupt && TARGET_FMOVD
5660               && hard_regs_intersect_p (&live_regs_mask,
5661                                         &reg_class_contents[DF_REGS]))
5662             fpscr_deferred = 1;
5663           else if (j != PR_REG && TEST_HARD_REG_BIT (live_regs_mask, j))
5664             pop (j);
5665           if (j == FIRST_FP_REG && fpscr_deferred)
5666             pop (FPSCR_REG);
5667
5668         }
5669     }
5670   if (target_flags != save_flags && ! current_function_interrupt)
5671     emit_insn (gen_toggle_sz ());
5672   target_flags = save_flags;
5673
5674   output_stack_adjust (extra_push + current_function_pretend_args_size
5675                        + save_size + d_rounding
5676                        + current_function_args_info.stack_regs * 8,
5677                        stack_pointer_rtx, 1, NULL);
5678
5679   if (current_function_calls_eh_return)
5680     emit_insn (GEN_ADD3 (stack_pointer_rtx, stack_pointer_rtx,
5681                          EH_RETURN_STACKADJ_RTX));
5682
5683   /* Switch back to the normal stack if necessary.  */
5684   if (sp_switch)
5685     emit_insn (gen_sp_switch_2 ());
5686
5687   /* Tell flow the insn that pops PR isn't dead.  */
5688   /* PR_REG will never be live in SHmedia mode, and we don't need to
5689      USE PR_MEDIA_REG, since it will be explicitly copied to TR0_REG
5690      by the return pattern.  */
5691   if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
5692     emit_insn (gen_rtx_USE (VOIDmode, gen_rtx_REG (SImode, PR_REG)));
5693 }
5694
5695 static int sh_need_epilogue_known = 0;
5696
5697 int
5698 sh_need_epilogue (void)
5699 {
5700   if (! sh_need_epilogue_known)
5701     {
5702       rtx epilogue;
5703
5704       start_sequence ();
5705       sh_expand_epilogue ();
5706       epilogue = get_insns ();
5707       end_sequence ();
5708       sh_need_epilogue_known = (epilogue == NULL ? -1 : 1);
5709     }
5710   return sh_need_epilogue_known > 0;
5711 }
5712
5713 /* Emit code to change the current function's return address to RA.
5714    TEMP is available as a scratch register, if needed.  */
5715
5716 void
5717 sh_set_return_address (rtx ra, rtx tmp)
5718 {
5719   HARD_REG_SET live_regs_mask;
5720   int d;
5721   int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
5722   int pr_offset;
5723
5724   d = calc_live_regs (&live_regs_mask);
5725
5726   /* If pr_reg isn't life, we can set it (or the register given in
5727      sh_media_register_for_return) directly.  */
5728   if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
5729     {
5730       rtx rr;
5731
5732       if (TARGET_SHMEDIA)
5733         {
5734           int rr_regno = sh_media_register_for_return ();
5735
5736           if (rr_regno < 0)
5737             rr_regno = pr_reg;
5738
5739           rr = gen_rtx_REG (DImode, rr_regno);
5740         }
5741       else
5742         rr = gen_rtx_REG (SImode, pr_reg);
5743
5744       emit_insn (GEN_MOV (rr, ra));
5745       /* Tell flow the register for return isn't dead.  */
5746       emit_insn (gen_rtx_USE (VOIDmode, rr));
5747       return;
5748     }
5749
5750   if (TARGET_SH5)
5751     {
5752       int offset;
5753       save_schedule schedule;
5754       save_entry *entry;
5755       
5756       entry = sh5_schedule_saves (&live_regs_mask, &schedule, 0);
5757       offset = entry[1].offset;
5758       for (; entry->mode != VOIDmode; entry--)
5759         if (entry->reg == pr_reg)
5760           goto found;
5761
5762       /* We can't find pr register.  */
5763       abort ();
5764
5765     found:
5766       offset = entry->offset - offset;
5767       pr_offset = (rounded_frame_size (d) + offset
5768                    + SHMEDIA_REGS_STACK_ADJUST ());
5769     }
5770   else
5771     pr_offset = rounded_frame_size (d);
5772
5773   emit_insn (GEN_MOV (tmp, GEN_INT (pr_offset)));
5774   emit_insn (GEN_ADD3 (tmp, tmp, frame_pointer_rtx));
5775
5776   tmp = gen_rtx_MEM (Pmode, tmp);
5777   emit_insn (GEN_MOV (tmp, ra));
5778 }
5779
5780 /* Clear variables at function end.  */
5781
5782 static void
5783 sh_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
5784                              HOST_WIDE_INT size ATTRIBUTE_UNUSED)
5785 {
5786   trap_exit = pragma_interrupt = pragma_trapa = pragma_nosave_low_regs = 0;
5787   sh_need_epilogue_known = 0;
5788   sp_switch = NULL_RTX;
5789 }
5790
5791 static rtx
5792 sh_builtin_saveregs (void)
5793 {
5794   /* First unnamed integer register.  */
5795   int first_intreg = current_function_args_info.arg_count[(int) SH_ARG_INT];
5796   /* Number of integer registers we need to save.  */
5797   int n_intregs = MAX (0, NPARM_REGS (SImode) - first_intreg);
5798   /* First unnamed SFmode float reg */
5799   int first_floatreg = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
5800   /* Number of SFmode float regs to save.  */
5801   int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
5802   rtx regbuf, fpregs;
5803   int bufsize, regno;
5804   HOST_WIDE_INT alias_set;
5805
5806   if (TARGET_SH5)
5807     {
5808       if (n_intregs)
5809         {
5810           int pushregs = n_intregs;
5811
5812           while (pushregs < NPARM_REGS (SImode) - 1
5813                  && (CALL_COOKIE_INT_REG_GET
5814                         (current_function_args_info.call_cookie,
5815                          NPARM_REGS (SImode) - pushregs)
5816                      == 1))
5817             {
5818               current_function_args_info.call_cookie
5819                 &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
5820                                           - pushregs, 1);
5821               pushregs++;
5822             }
5823
5824           if (pushregs == NPARM_REGS (SImode))
5825             current_function_args_info.call_cookie
5826               |= (CALL_COOKIE_INT_REG (0, 1)
5827                   | CALL_COOKIE_STACKSEQ (pushregs - 1));
5828           else
5829             current_function_args_info.call_cookie
5830               |= CALL_COOKIE_STACKSEQ (pushregs);
5831
5832           current_function_pretend_args_size += 8 * n_intregs;
5833         }
5834       if (TARGET_SHCOMPACT)
5835         return const0_rtx;
5836     }
5837   
5838   if (! TARGET_SH2E && ! TARGET_SH4 && ! TARGET_SH5)
5839     {
5840       error ("__builtin_saveregs not supported by this subtarget");
5841       return const0_rtx;
5842     }
5843
5844   if (TARGET_SHMEDIA)
5845     n_floatregs = 0;
5846
5847   /* Allocate block of memory for the regs.  */
5848   /* ??? If n_intregs + n_floatregs == 0, should we allocate at least 1 byte?
5849      Or can assign_stack_local accept a 0 SIZE argument?  */
5850   bufsize = (n_intregs * UNITS_PER_WORD) + (n_floatregs * UNITS_PER_WORD);
5851
5852   if (TARGET_SHMEDIA)
5853     regbuf = gen_rtx_MEM (BLKmode,
5854                           gen_rtx_REG (Pmode, ARG_POINTER_REGNUM));
5855   else if (n_floatregs & 1)
5856     {
5857       rtx addr;
5858
5859       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
5860       addr = copy_to_mode_reg (Pmode, XEXP (regbuf, 0));
5861       emit_insn (gen_iorsi3 (addr, addr, GEN_INT (UNITS_PER_WORD)));
5862       regbuf = change_address (regbuf, BLKmode, addr);
5863     }
5864   else
5865     regbuf = assign_stack_local (BLKmode, bufsize, 0);
5866   alias_set = get_varargs_alias_set ();
5867   set_mem_alias_set (regbuf, alias_set);
5868
5869   /* Save int args.
5870      This is optimized to only save the regs that are necessary.  Explicitly
5871      named args need not be saved.  */
5872   if (n_intregs > 0)
5873     move_block_from_reg (BASE_ARG_REG (SImode) + first_intreg,
5874                          adjust_address (regbuf, BLKmode,
5875                                          n_floatregs * UNITS_PER_WORD),
5876                          n_intregs);
5877
5878   if (TARGET_SHMEDIA)
5879     /* Return the address of the regbuf.  */
5880     return XEXP (regbuf, 0);
5881
5882   /* Save float args.
5883      This is optimized to only save the regs that are necessary.  Explicitly
5884      named args need not be saved.
5885      We explicitly build a pointer to the buffer because it halves the insn
5886      count when not optimizing (otherwise the pointer is built for each reg
5887      saved).
5888      We emit the moves in reverse order so that we can use predecrement.  */
5889
5890   fpregs = gen_reg_rtx (Pmode);
5891   emit_move_insn (fpregs, XEXP (regbuf, 0));
5892   emit_insn (gen_addsi3 (fpregs, fpregs,
5893                          GEN_INT (n_floatregs * UNITS_PER_WORD)));
5894   if (TARGET_SH4)
5895     {
5896       rtx mem;
5897       for (regno = NPARM_REGS (DFmode) - 2; regno >= first_floatreg; regno -= 2)
5898         {
5899           emit_insn (gen_addsi3 (fpregs, fpregs,
5900                                  GEN_INT (-2 * UNITS_PER_WORD)));
5901           mem = gen_rtx_MEM (DFmode, fpregs);
5902           set_mem_alias_set (mem, alias_set);
5903           emit_move_insn (mem, 
5904                           gen_rtx (REG, DFmode, BASE_ARG_REG (DFmode) + regno));
5905         }
5906       regno = first_floatreg;
5907       if (regno & 1)
5908         {
5909           emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5910           mem = gen_rtx_MEM (SFmode, fpregs);
5911           set_mem_alias_set (mem, alias_set);
5912           emit_move_insn (mem,
5913                           gen_rtx (REG, SFmode, BASE_ARG_REG (SFmode) + regno
5914                                                 - (TARGET_LITTLE_ENDIAN != 0)));
5915         }
5916     }
5917   else
5918     for (regno = NPARM_REGS (SFmode) - 1; regno >= first_floatreg; regno--)
5919       {
5920         rtx mem;
5921
5922         emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (- UNITS_PER_WORD)));
5923         mem = gen_rtx_MEM (SFmode, fpregs);
5924         set_mem_alias_set (mem, alias_set);
5925         emit_move_insn (mem,
5926                         gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno));
5927       }
5928
5929   /* Return the address of the regbuf.  */
5930   return XEXP (regbuf, 0);
5931 }
5932
5933 /* Define the `__builtin_va_list' type for the ABI.  */
5934
5935 static tree
5936 sh_build_builtin_va_list (void)
5937 {
5938   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5939   tree record;
5940
5941   if (TARGET_SH5 || (! TARGET_SH2E && ! TARGET_SH4)
5942       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
5943     return ptr_type_node;
5944
5945   record = (*lang_hooks.types.make_type) (RECORD_TYPE);
5946
5947   f_next_o = build_decl (FIELD_DECL, get_identifier ("__va_next_o"),
5948                          ptr_type_node);
5949   f_next_o_limit = build_decl (FIELD_DECL,
5950                                get_identifier ("__va_next_o_limit"),
5951                                ptr_type_node);
5952   f_next_fp = build_decl (FIELD_DECL, get_identifier ("__va_next_fp"),
5953                           ptr_type_node);
5954   f_next_fp_limit = build_decl (FIELD_DECL,
5955                                 get_identifier ("__va_next_fp_limit"),
5956                                 ptr_type_node);
5957   f_next_stack = build_decl (FIELD_DECL, get_identifier ("__va_next_stack"),
5958                              ptr_type_node);
5959
5960   DECL_FIELD_CONTEXT (f_next_o) = record;
5961   DECL_FIELD_CONTEXT (f_next_o_limit) = record;
5962   DECL_FIELD_CONTEXT (f_next_fp) = record;
5963   DECL_FIELD_CONTEXT (f_next_fp_limit) = record;
5964   DECL_FIELD_CONTEXT (f_next_stack) = record;
5965
5966   TYPE_FIELDS (record) = f_next_o;
5967   TREE_CHAIN (f_next_o) = f_next_o_limit;
5968   TREE_CHAIN (f_next_o_limit) = f_next_fp;
5969   TREE_CHAIN (f_next_fp) = f_next_fp_limit;
5970   TREE_CHAIN (f_next_fp_limit) = f_next_stack;
5971
5972   layout_type (record);
5973
5974   return record;
5975 }
5976
5977 /* Implement `va_start' for varargs and stdarg.  */
5978
5979 void
5980 sh_va_start (tree valist, rtx nextarg)
5981 {
5982   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
5983   tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
5984   tree t, u;
5985   int nfp, nint;
5986
5987   if (TARGET_SH5)
5988     {
5989       expand_builtin_saveregs ();
5990       std_expand_builtin_va_start (valist, nextarg);
5991       return;
5992     }
5993
5994   if ((! TARGET_SH2E && ! TARGET_SH4)
5995       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
5996     {
5997       std_expand_builtin_va_start (valist, nextarg);
5998       return;
5999     }
6000
6001   f_next_o = TYPE_FIELDS (va_list_type_node);
6002   f_next_o_limit = TREE_CHAIN (f_next_o);
6003   f_next_fp = TREE_CHAIN (f_next_o_limit);
6004   f_next_fp_limit = TREE_CHAIN (f_next_fp);
6005   f_next_stack = TREE_CHAIN (f_next_fp_limit);
6006
6007   next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
6008   next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
6009                         valist, f_next_o_limit);
6010   next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp), valist, f_next_fp);
6011   next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
6012                          valist, f_next_fp_limit);
6013   next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
6014                       valist, f_next_stack);
6015
6016   /* Call __builtin_saveregs.  */
6017   u = make_tree (ptr_type_node, expand_builtin_saveregs ());
6018   t = build (MODIFY_EXPR, ptr_type_node, next_fp, u);
6019   TREE_SIDE_EFFECTS (t) = 1;
6020   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
6021
6022   nfp = current_function_args_info.arg_count[SH_ARG_FLOAT];
6023   if (nfp < 8)
6024     nfp = 8 - nfp;
6025   else
6026     nfp = 0;
6027   u = fold (build (PLUS_EXPR, ptr_type_node, u,
6028                    build_int_2 (UNITS_PER_WORD * nfp, 0)));
6029   t = build (MODIFY_EXPR, ptr_type_node, next_fp_limit, u);
6030   TREE_SIDE_EFFECTS (t) = 1;
6031   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
6032
6033   t = build (MODIFY_EXPR, ptr_type_node, next_o, u);
6034   TREE_SIDE_EFFECTS (t) = 1;
6035   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
6036
6037   nint = current_function_args_info.arg_count[SH_ARG_INT];
6038   if (nint < 4)
6039     nint = 4 - nint;
6040   else
6041     nint = 0;
6042   u = fold (build (PLUS_EXPR, ptr_type_node, u,
6043                    build_int_2 (UNITS_PER_WORD * nint, 0)));
6044   t = build (MODIFY_EXPR, ptr_type_node, next_o_limit, u);
6045   TREE_SIDE_EFFECTS (t) = 1;
6046   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
6047
6048   u = make_tree (ptr_type_node, nextarg);
6049   t = build (MODIFY_EXPR, ptr_type_node, next_stack, u);
6050   TREE_SIDE_EFFECTS (t) = 1;
6051   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
6052 }
6053
6054 /* Implement `va_arg'.  */
6055
6056 rtx
6057 sh_va_arg (tree valist, tree type)
6058 {
6059   HOST_WIDE_INT size, rsize;
6060   tree tmp, pptr_type_node;
6061   rtx addr_rtx, r;
6062   rtx result_ptr, result = NULL_RTX;
6063   int pass_by_ref = MUST_PASS_IN_STACK (TYPE_MODE (type), type);
6064   rtx lab_over;
6065
6066   size = int_size_in_bytes (type);
6067   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
6068   pptr_type_node = build_pointer_type (ptr_type_node);
6069
6070   if (pass_by_ref)
6071     type = build_pointer_type (type);
6072
6073   if (! TARGET_SH5 && (TARGET_SH2E || TARGET_SH4)
6074       && ! (TARGET_HITACHI || sh_cfun_attr_renesas_p ()))
6075     {
6076       tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
6077       tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
6078       int pass_as_float;
6079       rtx lab_false;
6080
6081       f_next_o = TYPE_FIELDS (va_list_type_node);
6082       f_next_o_limit = TREE_CHAIN (f_next_o);
6083       f_next_fp = TREE_CHAIN (f_next_o_limit);
6084       f_next_fp_limit = TREE_CHAIN (f_next_fp);
6085       f_next_stack = TREE_CHAIN (f_next_fp_limit);
6086
6087       next_o = build (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o);
6088       next_o_limit = build (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
6089                             valist, f_next_o_limit);
6090       next_fp = build (COMPONENT_REF, TREE_TYPE (f_next_fp),
6091                        valist, f_next_fp);
6092       next_fp_limit = build (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
6093                              valist, f_next_fp_limit);
6094       next_stack = build (COMPONENT_REF, TREE_TYPE (f_next_stack),
6095                           valist, f_next_stack);
6096
6097       /* Structures with a single member with a distinct mode are passed
6098          like their member.  This is relevant if the latter has a REAL_TYPE
6099          or COMPLEX_TYPE type.  */
6100       if (TREE_CODE (type) == RECORD_TYPE
6101           && TYPE_FIELDS (type)
6102           && TREE_CODE (TYPE_FIELDS (type)) == FIELD_DECL
6103           && (TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == REAL_TYPE
6104               || TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == COMPLEX_TYPE)
6105           && TREE_CHAIN (TYPE_FIELDS (type)) == NULL_TREE)
6106         type = TREE_TYPE (TYPE_FIELDS (type));
6107       if (TARGET_SH4)
6108         {
6109           pass_as_float = ((TREE_CODE (type) == REAL_TYPE && size <= 8)
6110                            || (TREE_CODE (type) == COMPLEX_TYPE
6111                                && TREE_CODE (TREE_TYPE (type)) == REAL_TYPE
6112                                && size <= 16));
6113         }
6114       else
6115         {
6116           pass_as_float = (TREE_CODE (type) == REAL_TYPE && size == 4);
6117         }
6118
6119       addr_rtx = gen_reg_rtx (Pmode);
6120       lab_false = gen_label_rtx ();
6121       lab_over = gen_label_rtx ();
6122
6123       tmp = make_tree (pptr_type_node, addr_rtx);
6124       valist = build1 (INDIRECT_REF, ptr_type_node, tmp);
6125
6126       if (pass_as_float)
6127         {
6128           int first_floatreg
6129             = current_function_args_info.arg_count[(int) SH_ARG_FLOAT];
6130           int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
6131
6132           emit_cmp_and_jump_insns (expand_expr (next_fp, NULL_RTX, Pmode,
6133                                                 EXPAND_NORMAL),
6134                                    expand_expr (next_fp_limit, NULL_RTX,
6135                                                 Pmode, EXPAND_NORMAL),
6136                                    GE, const1_rtx, Pmode, 1, lab_false);
6137
6138           if (TYPE_ALIGN (type) > BITS_PER_WORD
6139               || (((TREE_CODE (type) == REAL_TYPE && size == 8) || size == 16)
6140                   && (n_floatregs & 1)))
6141             {
6142               tmp = build (BIT_AND_EXPR, ptr_type_node, next_fp,
6143                            build_int_2 (UNITS_PER_WORD, 0));
6144               tmp = build (PLUS_EXPR, ptr_type_node, next_fp, tmp);
6145               tmp = build (MODIFY_EXPR, ptr_type_node, next_fp, tmp);
6146               TREE_SIDE_EFFECTS (tmp) = 1;
6147               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
6148             }
6149
6150           tmp = build1 (ADDR_EXPR, pptr_type_node, next_fp);
6151           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
6152           if (r != addr_rtx)
6153             emit_move_insn (addr_rtx, r);
6154
6155 #ifdef FUNCTION_ARG_SCmode_WART
6156           if (TYPE_MODE (type) == SCmode && TARGET_SH4 && TARGET_LITTLE_ENDIAN)
6157             {
6158               rtx addr, real, imag, result_value, slot;
6159               tree subtype = TREE_TYPE (type);
6160
6161               addr = std_expand_builtin_va_arg (valist, subtype);
6162 #ifdef POINTERS_EXTEND_UNSIGNED
6163               if (GET_MODE (addr) != Pmode)
6164                 addr = convert_memory_address (Pmode, addr);
6165 #endif
6166               imag = gen_rtx_MEM (TYPE_MODE (type), addr);
6167               set_mem_alias_set (imag, get_varargs_alias_set ());
6168
6169               addr = std_expand_builtin_va_arg (valist, subtype);
6170 #ifdef POINTERS_EXTEND_UNSIGNED
6171               if (GET_MODE (addr) != Pmode)
6172                 addr = convert_memory_address (Pmode, addr);
6173 #endif
6174               real = gen_rtx_MEM (TYPE_MODE (type), addr);
6175               set_mem_alias_set (real, get_varargs_alias_set ());
6176
6177               result_value = gen_rtx_CONCAT (SCmode, real, imag);
6178               /* ??? this interface is stupid - why require a pointer?  */
6179               result = gen_reg_rtx (Pmode);
6180               slot = assign_stack_temp (SCmode, 8, 0);
6181               emit_move_insn (slot, result_value);
6182               emit_move_insn (result, XEXP (slot, 0));
6183             }
6184 #endif /* FUNCTION_ARG_SCmode_WART */
6185
6186           emit_jump_insn (gen_jump (lab_over));
6187           emit_barrier ();
6188           emit_label (lab_false);
6189
6190           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
6191           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
6192           if (r != addr_rtx)
6193             emit_move_insn (addr_rtx, r);
6194         }
6195       else
6196         {
6197           tmp = build (PLUS_EXPR, ptr_type_node, next_o,
6198                        build_int_2 (rsize, 0));
6199           
6200           emit_cmp_and_jump_insns (expand_expr (tmp, NULL_RTX, Pmode,
6201                                                 EXPAND_NORMAL),
6202                                    expand_expr (next_o_limit, NULL_RTX,
6203                                                 Pmode, EXPAND_NORMAL),
6204                                    GT, const1_rtx, Pmode, 1, lab_false);
6205
6206           tmp = build1 (ADDR_EXPR, pptr_type_node, next_o);
6207           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
6208           if (r != addr_rtx)
6209             emit_move_insn (addr_rtx, r);
6210
6211           emit_jump_insn (gen_jump (lab_over));
6212           emit_barrier ();
6213           emit_label (lab_false);
6214
6215           if (size > 4 && ! TARGET_SH4)
6216             {
6217               tmp = build (MODIFY_EXPR, ptr_type_node, next_o, next_o_limit);
6218               TREE_SIDE_EFFECTS (tmp) = 1;
6219               expand_expr (tmp, const0_rtx, VOIDmode, EXPAND_NORMAL);
6220             }
6221
6222           tmp = build1 (ADDR_EXPR, pptr_type_node, next_stack);
6223           r = expand_expr (tmp, addr_rtx, Pmode, EXPAND_NORMAL);
6224           if (r != addr_rtx)
6225             emit_move_insn (addr_rtx, r);
6226         }
6227
6228       if (! result)
6229         emit_label (lab_over);
6230     }
6231
6232   /* ??? In va-sh.h, there had been code to make values larger than
6233      size 8 indirect.  This does not match the FUNCTION_ARG macros.  */
6234
6235   result_ptr = std_expand_builtin_va_arg (valist, type);
6236   if (result)
6237     {
6238       emit_move_insn (result, result_ptr);
6239       emit_label (lab_over);
6240     }
6241   else
6242     result = result_ptr;
6243
6244   if (pass_by_ref)
6245     {
6246 #ifdef POINTERS_EXTEND_UNSIGNED
6247       if (GET_MODE (addr) != Pmode)
6248         addr = convert_memory_address (Pmode, result);
6249 #endif
6250       result = gen_rtx_MEM (ptr_mode, force_reg (Pmode, result));
6251       set_mem_alias_set (result, get_varargs_alias_set ());
6252     }
6253   /* ??? expand_builtin_va_arg will also set the alias set of the dereferenced
6254      argument to the varargs alias set.  */
6255   return result;
6256 }
6257
6258 static bool
6259 sh_promote_prototypes (tree type)
6260 {
6261   if (TARGET_HITACHI)
6262     return 0;
6263   if (! type)
6264     return 1;
6265   return ! sh_attr_renesas_p (type);
6266 }
6267
6268 /* Define where to put the arguments to a function.
6269    Value is zero to push the argument on the stack,
6270    or a hard register in which to store the argument.
6271
6272    MODE is the argument's machine mode.
6273    TYPE is the data type of the argument (as a tree).
6274     This is null for libcalls where that information may
6275     not be available.
6276    CUM is a variable of type CUMULATIVE_ARGS which gives info about
6277     the preceding args and about the function being called.
6278    NAMED is nonzero if this argument is a named parameter
6279     (otherwise it is an extra parameter matching an ellipsis).
6280
6281    On SH the first args are normally in registers
6282    and the rest are pushed.  Any arg that starts within the first
6283    NPARM_REGS words is at least partially passed in a register unless
6284    its data type forbids.  */
6285
6286
6287 rtx
6288 sh_function_arg (CUMULATIVE_ARGS *ca, enum machine_mode mode,
6289                  tree type, int named)
6290 {
6291   if (! TARGET_SH5 && mode == VOIDmode)
6292     return GEN_INT (ca->renesas_abi ? 1 : 0);
6293
6294   if (! TARGET_SH5
6295       && PASS_IN_REG_P (*ca, mode, type)
6296       && (named || ! (TARGET_HITACHI || ca->renesas_abi)))
6297     {
6298       int regno;
6299
6300       if (mode == SCmode && TARGET_SH4 && TARGET_LITTLE_ENDIAN
6301           && (! FUNCTION_ARG_SCmode_WART || (ROUND_REG (*ca, mode) & 1)))
6302         {
6303           rtx r1 = gen_rtx_EXPR_LIST (VOIDmode,
6304                                       gen_rtx_REG (SFmode,
6305                                                    BASE_ARG_REG (mode)
6306                                                    + (ROUND_REG (*ca, mode) ^ 1)),
6307                                       const0_rtx);
6308           rtx r2 = gen_rtx_EXPR_LIST(VOIDmode,
6309                                      gen_rtx_REG (SFmode,
6310                                                   BASE_ARG_REG (mode)
6311                                                   + ((ROUND_REG (*ca, mode) + 1) ^ 1)),
6312                                      GEN_INT (4));
6313           return gen_rtx_PARALLEL(SCmode, gen_rtvec(2, r1, r2));
6314         }
6315
6316      /* If the alignment of a DF value causes an SF register to be
6317         skipped, we will use that skipped register for the next SF
6318         value.  */
6319       if ((TARGET_HITACHI || ca->renesas_abi)
6320           && ca->free_single_fp_reg
6321           && mode == SFmode)
6322         return gen_rtx_REG (mode, ca->free_single_fp_reg);
6323
6324       regno = (BASE_ARG_REG (mode) + ROUND_REG (*ca, mode))
6325                ^ (mode == SFmode && TARGET_SH4
6326                   && TARGET_LITTLE_ENDIAN != 0
6327                   && ! TARGET_HITACHI && ! ca->renesas_abi);
6328       return gen_rtx_REG (mode, regno);
6329
6330     }
6331   
6332   if (TARGET_SH5)
6333     {
6334       if (mode == VOIDmode && TARGET_SHCOMPACT)
6335         return GEN_INT (ca->call_cookie);
6336
6337       /* The following test assumes unnamed arguments are promoted to
6338          DFmode.  */
6339       if (mode == SFmode && ca->free_single_fp_reg)
6340         return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode, ca->free_single_fp_reg);
6341
6342       if ((GET_SH_ARG_CLASS (mode) == SH_ARG_FLOAT)
6343           && (named || ! ca->prototype_p)
6344           && ca->arg_count[(int) SH_ARG_FLOAT] < NPARM_REGS (SFmode))
6345         {
6346           if (! ca->prototype_p && TARGET_SHMEDIA)
6347             return SH5_PROTOTYPELESS_FLOAT_ARG (*ca, mode);
6348
6349           return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode,
6350                                            FIRST_FP_PARM_REG
6351                                            + ca->arg_count[(int) SH_ARG_FLOAT]);
6352         }
6353
6354       if (ca->arg_count[(int) SH_ARG_INT] < NPARM_REGS (SImode)
6355           && (! TARGET_SHCOMPACT
6356               || (! SHCOMPACT_FORCE_ON_STACK (mode, type)
6357                   && ! SH5_WOULD_BE_PARTIAL_NREGS (*ca, mode,
6358                                                    type, named))))
6359         {
6360           return gen_rtx_REG (mode, (FIRST_PARM_REG
6361                                        + ca->arg_count[(int) SH_ARG_INT]));
6362         }
6363
6364       return 0;
6365     }
6366
6367   return 0;
6368 }
6369  
6370 /* Update the data in CUM to advance over an argument
6371    of mode MODE and data type TYPE.
6372    (TYPE is null for libcalls where that information may not be
6373    available.)  */
6374
6375 void
6376 sh_function_arg_advance (CUMULATIVE_ARGS *ca, enum machine_mode mode,
6377                          tree type, int named)
6378 {
6379  if (ca->force_mem)
6380    ca->force_mem = 0;
6381  else if (TARGET_SH5)
6382    {
6383      tree type2 = (ca->byref && type
6384                    ? TREE_TYPE (type)
6385                    : type);
6386      enum machine_mode mode2 = (ca->byref && type
6387                                 ? TYPE_MODE (type2)
6388                                 : mode);
6389      int dwords = ((ca->byref
6390                     ? ca->byref
6391                     : mode2 == BLKmode
6392                     ? int_size_in_bytes (type2)
6393                     : GET_MODE_SIZE (mode2)) + 7) / 8;
6394      int numregs = MIN (dwords, NPARM_REGS (SImode)
6395                         - ca->arg_count[(int) SH_ARG_INT]);
6396
6397      if (numregs)
6398        {
6399          ca->arg_count[(int) SH_ARG_INT] += numregs;
6400          if (TARGET_SHCOMPACT
6401              && SHCOMPACT_FORCE_ON_STACK (mode2, type2))
6402            {
6403              ca->call_cookie
6404                |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
6405                                        - numregs, 1);
6406              /* N.B. We want this also for outgoing.  */
6407              ca->stack_regs += numregs;
6408            }
6409          else if (ca->byref)
6410            {
6411              if (! ca->outgoing)
6412                ca->stack_regs += numregs;
6413              ca->byref_regs += numregs;
6414              ca->byref = 0;
6415              do
6416                ca->call_cookie
6417                  |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
6418                                          - numregs, 2);
6419              while (--numregs);
6420              ca->call_cookie
6421                |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
6422                                        - 1, 1);
6423            }
6424          else if (dwords > numregs)
6425            {
6426              int pushregs = numregs;
6427
6428              if (TARGET_SHCOMPACT)
6429                ca->stack_regs += numregs;
6430              while (pushregs < NPARM_REGS (SImode) - 1
6431                     && (CALL_COOKIE_INT_REG_GET
6432                         (ca->call_cookie,
6433                         NPARM_REGS (SImode) - pushregs)
6434                         == 1))
6435                {
6436                  ca->call_cookie
6437                    &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
6438                                              - pushregs, 1);
6439                  pushregs++;
6440                }
6441              if (numregs == NPARM_REGS (SImode))
6442                ca->call_cookie
6443                  |= CALL_COOKIE_INT_REG (0, 1)
6444                     | CALL_COOKIE_STACKSEQ (numregs - 1);
6445              else
6446                ca->call_cookie
6447                  |= CALL_COOKIE_STACKSEQ (numregs);
6448            }
6449        }
6450      if (GET_SH_ARG_CLASS (mode2) == SH_ARG_FLOAT
6451          && (named || ! ca->prototype_p))
6452        {
6453          if (mode2 == SFmode && ca->free_single_fp_reg)
6454            ca->free_single_fp_reg = 0;
6455          else if (ca->arg_count[(int) SH_ARG_FLOAT]
6456                   < NPARM_REGS (SFmode))
6457            {
6458              int numfpregs
6459                = MIN ((GET_MODE_SIZE (mode2) + 7) / 8 * 2,
6460                       NPARM_REGS (SFmode)
6461                       - ca->arg_count[(int) SH_ARG_FLOAT]);
6462
6463              ca->arg_count[(int) SH_ARG_FLOAT] += numfpregs;
6464
6465              if (TARGET_SHCOMPACT && ! ca->prototype_p)
6466                {
6467                  if (ca->outgoing && numregs > 0)
6468                    do
6469                      {
6470                        ca->call_cookie
6471                          |= (CALL_COOKIE_INT_REG
6472                              (ca->arg_count[(int) SH_ARG_INT]
6473                               - numregs + ((numfpregs - 2) / 2),
6474                               4 + (ca->arg_count[(int) SH_ARG_FLOAT]
6475                                    - numfpregs) / 2));
6476                      }
6477                    while (numfpregs -= 2);
6478                }
6479              else if (mode2 == SFmode && (named)
6480                       && (ca->arg_count[(int) SH_ARG_FLOAT]
6481                           < NPARM_REGS (SFmode)))
6482                ca->free_single_fp_reg
6483                  = FIRST_FP_PARM_REG - numfpregs
6484                  + ca->arg_count[(int) SH_ARG_FLOAT] + 1;
6485            }
6486        }
6487      return;
6488    }
6489
6490  if ((TARGET_HITACHI || ca->renesas_abi) && TARGET_FPU_DOUBLE)
6491    {
6492      /* Note that we've used the skipped register.  */
6493      if (mode == SFmode && ca->free_single_fp_reg)
6494        {
6495          ca->free_single_fp_reg = 0;
6496          return;
6497        }
6498      /* When we have a DF after an SF, there's an SF register that get
6499         skipped in order to align the DF value.  We note this skipped
6500         register, because the next SF value will use it, and not the
6501         SF that follows the DF.  */
6502      if (mode == DFmode
6503          && ROUND_REG (*ca, DFmode) != ROUND_REG (*ca, SFmode))
6504        {
6505          ca->free_single_fp_reg = (ROUND_REG (*ca, SFmode)
6506                                      + BASE_ARG_REG (mode));
6507        }
6508    }
6509
6510  if (! (TARGET_SH4 || ca->renesas_abi)
6511      || PASS_IN_REG_P (*ca, mode, type))
6512    (ca->arg_count[(int) GET_SH_ARG_CLASS (mode)]
6513     = (ROUND_REG (*ca, mode)
6514        + (mode == BLKmode
6515           ? ROUND_ADVANCE (int_size_in_bytes (type))
6516           : ROUND_ADVANCE (GET_MODE_SIZE (mode)))));
6517 }
6518
6519 /* If the structure value address is not passed in a register, define
6520    `STRUCT_VALUE' as an expression returning an RTX for the place
6521    where the address is passed.  If it returns 0, the address is
6522    passed as an "invisible" first argument.  */
6523 /* The Renesas calling convention doesn't quite fit into this scheme since
6524    the address is passed like an invisible argument, but one that is always
6525    passed in memory.  */
6526 static rtx
6527 sh_struct_value_rtx (tree fndecl, int incoming ATTRIBUTE_UNUSED)
6528 {
6529   if (TARGET_HITACHI || sh_attr_renesas_p (fndecl))
6530     return 0;
6531   return gen_rtx_REG (Pmode, 2);
6532 }
6533
6534 static bool
6535 sh_return_in_memory (tree type, tree fndecl)
6536 {
6537   if (TARGET_SH5)
6538     {
6539       if (TYPE_MODE (type) == BLKmode)
6540         return ((unsigned HOST_WIDE_INT) int_size_in_bytes (type)) > 8;
6541       else
6542         return GET_MODE_SIZE (TYPE_MODE (type)) > 8;
6543     }
6544   else
6545     {
6546       return (TYPE_MODE (type) == BLKmode
6547               || ((TARGET_HITACHI || sh_attr_renesas_p (fndecl))
6548                   && TREE_CODE (type) == RECORD_TYPE));
6549     }
6550 }
6551
6552 /* We actually emit the code in sh_expand_prologue.  We used to use
6553    a static variable to flag that we need to emit this code, but that
6554    doesn't when inlining, when functions are deferred and then emitted
6555    later.  Fortunately, we already have two flags that are part of struct
6556    function that tell if a function uses varargs or stdarg.  */
6557 static void
6558 sh_setup_incoming_varargs (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED,
6559                            enum machine_mode mode ATTRIBUTE_UNUSED,
6560                            tree type ATTRIBUTE_UNUSED,
6561                            int *pretend_arg_size ATTRIBUTE_UNUSED,
6562                            int second_time ATTRIBUTE_UNUSED)
6563 {
6564   if (! current_function_stdarg)
6565     abort ();
6566 }
6567
6568 static bool
6569 sh_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
6570 {
6571   return TARGET_SH5;
6572 }
6573
6574 static bool
6575 sh_pretend_outgoing_varargs_named (CUMULATIVE_ARGS *ca)
6576 {
6577   return ! (TARGET_HITACHI || ca->renesas_abi) && ! TARGET_SH5;
6578 }
6579
6580
6581 /* Define the offset between two registers, one to be eliminated, and
6582    the other its replacement, at the start of a routine.  */
6583
6584 int
6585 initial_elimination_offset (int from, int to)
6586 {
6587   int regs_saved;
6588   int regs_saved_rounding = 0;
6589   int total_saved_regs_space;
6590   int total_auto_space;
6591   int save_flags = target_flags;
6592   int copy_flags;
6593   HARD_REG_SET live_regs_mask;
6594
6595   shmedia_space_reserved_for_target_registers = false;
6596   regs_saved = calc_live_regs (&live_regs_mask);
6597   regs_saved += SHMEDIA_REGS_STACK_ADJUST ();
6598
6599   if (shmedia_reserve_space_for_target_registers_p (regs_saved, &live_regs_mask))
6600     {
6601       shmedia_space_reserved_for_target_registers = true;
6602       regs_saved += shmedia_target_regs_stack_adjust (&live_regs_mask);
6603     }
6604
6605   if (TARGET_SH5 && regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT))
6606     regs_saved_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
6607                            - regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT));
6608
6609   total_auto_space = rounded_frame_size (regs_saved) - regs_saved_rounding;
6610   copy_flags = target_flags;
6611   target_flags = save_flags;
6612
6613   total_saved_regs_space = regs_saved + regs_saved_rounding;
6614
6615   if (from == ARG_POINTER_REGNUM && to == FRAME_POINTER_REGNUM)
6616     return total_saved_regs_space + total_auto_space
6617       + current_function_args_info.byref_regs * 8;
6618
6619   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
6620     return total_saved_regs_space + total_auto_space
6621       + current_function_args_info.byref_regs * 8;
6622
6623   /* Initial gap between fp and sp is 0.  */
6624   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
6625     return 0;
6626
6627   if (from == RETURN_ADDRESS_POINTER_REGNUM
6628       && (to == FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM))
6629     {
6630       if (TARGET_SH5)
6631         {
6632           int n = total_saved_regs_space;
6633           int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
6634           save_schedule schedule;
6635           save_entry *entry;
6636           
6637           n += total_auto_space;
6638
6639           /* If it wasn't saved, there's not much we can do.  */
6640           if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
6641             return n;
6642
6643           target_flags = copy_flags;
6644
6645           sh5_schedule_saves (&live_regs_mask, &schedule, n);
6646           for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
6647             if (entry->reg == pr_reg)
6648               {
6649                 target_flags = save_flags;
6650                 return entry->offset;
6651               }
6652           abort ();
6653         }
6654       else
6655         return total_auto_space;
6656     }
6657
6658   abort ();
6659 }
6660 \f
6661 /* Handle machine specific pragmas to be semi-compatible with Renesas
6662    compiler.  */
6663
6664 void
6665 sh_pr_interrupt (struct cpp_reader *pfile ATTRIBUTE_UNUSED)
6666 {
6667   pragma_interrupt = 1;
6668 }
6669
6670 void
6671 sh_pr_trapa (struct cpp_reader *pfile ATTRIBUTE_UNUSED)
6672 {
6673   pragma_interrupt = pragma_trapa = 1;
6674 }
6675
6676 void
6677 sh_pr_nosave_low_regs (struct cpp_reader *pfile ATTRIBUTE_UNUSED)
6678 {
6679   pragma_nosave_low_regs = 1;
6680 }
6681
6682 /* Generate 'handle_interrupt' attribute for decls */
6683
6684 static void
6685 sh_insert_attributes (tree node, tree *attributes)
6686 {
6687   if (! pragma_interrupt
6688       || TREE_CODE (node) != FUNCTION_DECL)
6689     return;
6690
6691   /* We are only interested in fields.  */
6692   if (TREE_CODE_CLASS (TREE_CODE (node)) != 'd')
6693     return;
6694
6695   /* Add a 'handle_interrupt' attribute.  */
6696   * attributes = tree_cons (get_identifier ("interrupt_handler"), NULL, * attributes);
6697
6698   return;
6699 }
6700
6701 /* Supported attributes:
6702
6703    interrupt_handler -- specifies this function is an interrupt handler.
6704
6705    sp_switch -- specifies an alternate stack for an interrupt handler
6706    to run on.
6707
6708    trap_exit -- use a trapa to exit an interrupt function instead of
6709    an rte instruction.
6710
6711    renesas -- use Renesas calling/layout conventions (functions and
6712    structures).
6713
6714 */
6715
6716 const struct attribute_spec sh_attribute_table[] =
6717 {
6718   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
6719   { "interrupt_handler", 0, 0, true,  false, false, sh_handle_interrupt_handler_attribute },
6720   { "sp_switch",         1, 1, true,  false, false, sh_handle_sp_switch_attribute },
6721   { "trap_exit",         1, 1, true,  false, false, sh_handle_trap_exit_attribute },
6722   { "renesas",           0, 0, false, true, false, sh_handle_renesas_attribute },
6723   { NULL,                0, 0, false, false, false, NULL }
6724 };
6725
6726 /* Handle an "interrupt_handler" attribute; arguments as in
6727    struct attribute_spec.handler.  */
6728 static tree
6729 sh_handle_interrupt_handler_attribute (tree *node, tree name,
6730                                        tree args ATTRIBUTE_UNUSED,
6731                                        int flags ATTRIBUTE_UNUSED,
6732                                        bool *no_add_attrs)
6733 {
6734   if (TREE_CODE (*node) != FUNCTION_DECL)
6735     {
6736       warning ("`%s' attribute only applies to functions",
6737                IDENTIFIER_POINTER (name));
6738       *no_add_attrs = true;
6739     }
6740   else if (TARGET_SHCOMPACT)
6741     {
6742       error ("attribute interrupt_handler is not compatible with -m5-compact");
6743       *no_add_attrs = true;
6744     }
6745
6746   return NULL_TREE;
6747 }
6748
6749 /* Handle an "sp_switch" attribute; arguments as in
6750    struct attribute_spec.handler.  */
6751 static tree
6752 sh_handle_sp_switch_attribute (tree *node, tree name, tree args,
6753                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
6754 {
6755   if (TREE_CODE (*node) != FUNCTION_DECL)
6756     {
6757       warning ("`%s' attribute only applies to functions",
6758                IDENTIFIER_POINTER (name));
6759       *no_add_attrs = true;
6760     }
6761   else if (!pragma_interrupt)
6762     {
6763       /* The sp_switch attribute only has meaning for interrupt functions.  */
6764       warning ("`%s' attribute only applies to interrupt functions",
6765                IDENTIFIER_POINTER (name));
6766       *no_add_attrs = true;
6767     }
6768   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
6769     {
6770       /* The argument must be a constant string.  */
6771       warning ("`%s' attribute argument not a string constant",
6772                IDENTIFIER_POINTER (name));
6773       *no_add_attrs = true;
6774     }
6775   else
6776     {
6777       sp_switch = gen_rtx_SYMBOL_REF (VOIDmode,
6778                                       TREE_STRING_POINTER (TREE_VALUE (args)));
6779     }
6780
6781   return NULL_TREE;
6782 }
6783
6784 /* Handle an "trap_exit" attribute; arguments as in
6785    struct attribute_spec.handler.  */
6786 static tree
6787 sh_handle_trap_exit_attribute (tree *node, tree name, tree args,
6788                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
6789 {
6790   if (TREE_CODE (*node) != FUNCTION_DECL)
6791     {
6792       warning ("`%s' attribute only applies to functions",
6793                IDENTIFIER_POINTER (name));
6794       *no_add_attrs = true;
6795     }
6796   else if (!pragma_interrupt)
6797     {
6798       /* The trap_exit attribute only has meaning for interrupt functions.  */
6799       warning ("`%s' attribute only applies to interrupt functions",
6800                IDENTIFIER_POINTER (name));
6801       *no_add_attrs = true;
6802     }
6803   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
6804     {
6805       /* The argument must be a constant integer.  */
6806       warning ("`%s' attribute argument not an integer constant",
6807                IDENTIFIER_POINTER (name));
6808       *no_add_attrs = true;
6809     }
6810   else
6811     {
6812       trap_exit = TREE_INT_CST_LOW (TREE_VALUE (args));
6813     }
6814
6815   return NULL_TREE;
6816 }
6817
6818 static tree
6819 sh_handle_renesas_attribute (tree *node ATTRIBUTE_UNUSED,
6820                              tree name ATTRIBUTE_UNUSED,
6821                              tree args ATTRIBUTE_UNUSED,
6822                              int flags ATTRIBUTE_UNUSED,
6823                              bool *no_add_attrs ATTRIBUTE_UNUSED)
6824 {
6825   return NULL_TREE;
6826 }
6827
6828 /* True if __attribute__((renesas)) or -mrenesas.  */
6829 int
6830 sh_attr_renesas_p (tree td)
6831 {
6832   if (TARGET_HITACHI)
6833     return 1;
6834   if (td == 0)
6835     return 0;
6836   if (DECL_P (td))
6837     td = TREE_TYPE (td);
6838   return (lookup_attribute ("renesas", TYPE_ATTRIBUTES (td))
6839           != NULL_TREE);
6840 }
6841
6842 /* True if __attribute__((renesas)) or -mrenesas, for the current
6843    function.  */
6844 int
6845 sh_cfun_attr_renesas_p (void)
6846 {
6847   return sh_attr_renesas_p (current_function_decl);
6848 }
6849
6850 int
6851 sh_cfun_interrupt_handler_p (void)
6852 {
6853   return (lookup_attribute ("interrupt_handler",
6854                             DECL_ATTRIBUTES (current_function_decl))
6855           != NULL_TREE);
6856 }
6857
6858 /* ??? target_switches in toplev.c is static, hence we have to duplicate it.  */
6859 static const struct
6860 {
6861   const char *const name;
6862   const int value;
6863   const char *const description;
6864 }
6865 sh_target_switches[] = TARGET_SWITCHES;
6866 #define target_switches sh_target_switches
6867
6868 /* Like default_pch_valid_p, but take flag_mask into account.  */
6869 const char *
6870 sh_pch_valid_p (const void *data_p, size_t len)
6871 {
6872   const char *data = (const char *)data_p;
6873   const char *flag_that_differs = NULL;
6874   size_t i;
6875   int old_flags;
6876   int flag_mask
6877     = (SH1_BIT | SH2_BIT | SH3_BIT | SH_E_BIT | HARD_SH4_BIT | FPU_SINGLE_BIT
6878        | SH4_BIT | HITACHI_BIT | LITTLE_ENDIAN_BIT);
6879   
6880   /* -fpic and -fpie also usually make a PCH invalid.  */
6881   if (data[0] != flag_pic)
6882     return _("created and used with different settings of -fpic");
6883   if (data[1] != flag_pie)
6884     return _("created and used with different settings of -fpie");
6885   data += 2;
6886
6887   /* Check target_flags.  */
6888   memcpy (&old_flags, data, sizeof (target_flags));
6889   if (((old_flags ^ target_flags) & flag_mask) != 0)
6890     {
6891       for (i = 0; i < ARRAY_SIZE (target_switches); i++)
6892         {
6893           int bits;
6894
6895           bits = target_switches[i].value;
6896           if (bits < 0)
6897             bits = -bits;
6898           bits &= flag_mask;
6899           if ((target_flags & bits) != (old_flags & bits))
6900             {
6901               flag_that_differs = target_switches[i].name;
6902               goto make_message;
6903             }
6904         }
6905       abort ();
6906     }
6907   data += sizeof (target_flags);
6908   len -= sizeof (target_flags);
6909   
6910   /* Check string options.  */
6911 #ifdef TARGET_OPTIONS
6912   for (i = 0; i < ARRAY_SIZE (target_options); i++)
6913     {
6914       const char *str = *target_options[i].variable;
6915       size_t l;
6916       if (! str)
6917         str = "";
6918       l = strlen (str) + 1;
6919       if (len < l || memcmp (data, str, l) != 0)
6920         {
6921           flag_that_differs = target_options[i].prefix;
6922           goto make_message;
6923         }
6924       data += l;
6925       len -= l;
6926     }
6927 #endif
6928
6929   return NULL;
6930   
6931  make_message:
6932   {
6933     char *r;
6934     asprintf (&r, _("created and used with differing settings of `-m%s'"),
6935                   flag_that_differs);
6936     if (r == NULL)
6937       return _("out of memory");
6938     return r;
6939   }
6940 }
6941 \f
6942 /* Predicates used by the templates.  */
6943
6944 /* Returns 1 if OP is MACL, MACH or PR.  The input must be a REG rtx.
6945    Used only in general_movsrc_operand.  */
6946
6947 int
6948 system_reg_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
6949 {
6950   switch (REGNO (op))
6951     {
6952     case PR_REG:
6953     case MACL_REG:
6954     case MACH_REG:
6955       return 1;
6956     }
6957   return 0;
6958 }
6959
6960 /* Returns 1 if OP can be source of a simple move operation.
6961    Same as general_operand, but a LABEL_REF is valid, PRE_DEC is
6962    invalid as are subregs of system registers.  */
6963
6964 int
6965 general_movsrc_operand (rtx op, enum machine_mode mode)
6966 {
6967   if (GET_CODE (op) == MEM)
6968     {
6969       rtx inside = XEXP (op, 0);
6970       if (GET_CODE (inside) == CONST)
6971         inside = XEXP (inside, 0);
6972
6973       if (GET_CODE (inside) == LABEL_REF)
6974         return 1;
6975
6976       if (GET_CODE (inside) == PLUS
6977           && GET_CODE (XEXP (inside, 0)) == LABEL_REF
6978           && GET_CODE (XEXP (inside, 1)) == CONST_INT)
6979         return 1;
6980
6981       /* Only post inc allowed.  */
6982       if (GET_CODE (inside) == PRE_DEC)
6983         return 0;
6984     }
6985
6986   if ((mode == QImode || mode == HImode)
6987       && (GET_CODE (op) == SUBREG
6988           && GET_CODE (XEXP (op, 0)) == REG
6989           && system_reg_operand (XEXP (op, 0), mode)))
6990     return 0;
6991
6992   return general_operand (op, mode);
6993 }
6994
6995 /* Returns 1 if OP can be a destination of a move.
6996    Same as general_operand, but no preinc allowed.  */
6997
6998 int
6999 general_movdst_operand (rtx op, enum machine_mode mode)
7000 {
7001   /* Only pre dec allowed.  */
7002   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == POST_INC)
7003     return 0;
7004
7005   return general_operand (op, mode);
7006 }
7007
7008 /* Returns 1 if OP is a normal arithmetic register.  */
7009
7010 int
7011 arith_reg_operand (rtx op, enum machine_mode mode)
7012 {
7013   if (register_operand (op, mode))
7014     {
7015       int regno;
7016
7017       if (GET_CODE (op) == REG)
7018         regno = REGNO (op);
7019       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
7020         regno = REGNO (SUBREG_REG (op));
7021       else
7022         return 1;
7023
7024       return (regno != T_REG && regno != PR_REG
7025               && ! TARGET_REGISTER_P (regno)
7026               && (regno != FPUL_REG || TARGET_SH4)
7027               && regno != MACH_REG && regno != MACL_REG);
7028     }
7029   return 0;
7030 }
7031
7032 /* Like above, but for DImode destinations: forbid paradoxical DImode subregs,
7033    because this would lead to missing sign extensions when truncating from
7034    DImode to SImode.  */
7035 int
7036 arith_reg_dest (rtx op, enum machine_mode mode)
7037 {
7038   if (mode == DImode && GET_CODE (op) == SUBREG
7039       && GET_MODE_SIZE (GET_MODE (SUBREG_REG (op))) < 8)
7040     return 0;
7041   return arith_reg_operand (op, mode);
7042 }
7043
7044 int
7045 int_gpr_dest (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7046 {
7047   enum machine_mode op_mode = GET_MODE (op);
7048
7049   if (GET_MODE_CLASS (op_mode) != MODE_INT
7050       || GET_MODE_SIZE (op_mode) >= UNITS_PER_WORD)
7051     return 0;
7052   if (! reload_completed)
7053     return 0;
7054   return true_regnum (op) <= LAST_GENERAL_REG;
7055 }
7056
7057 int
7058 fp_arith_reg_operand (rtx op, enum machine_mode mode)
7059 {
7060   if (register_operand (op, mode))
7061     {
7062       int regno;
7063
7064       if (GET_CODE (op) == REG)
7065         regno = REGNO (op);
7066       else if (GET_CODE (op) == SUBREG && GET_CODE (SUBREG_REG (op)) == REG)
7067         regno = REGNO (SUBREG_REG (op));
7068       else
7069         return 1;
7070
7071       return (regno >= FIRST_PSEUDO_REGISTER
7072               || FP_REGISTER_P (regno));
7073     }
7074   return 0;
7075 }
7076
7077 /* Returns 1 if OP is a valid source operand for an arithmetic insn.  */
7078
7079 int
7080 arith_operand (rtx op, enum machine_mode mode)
7081 {
7082   if (arith_reg_operand (op, mode))
7083     return 1;
7084
7085   if (TARGET_SHMEDIA)
7086     {
7087       /* FIXME: We should be checking whether the CONST_INT fits in a
7088          CONST_OK_FOR_I16 here, but this causes reload_cse to crash when
7089          attempting to transform a sequence of two 64-bit sets of the
7090          same register from literal constants into a set and an add,
7091          when the difference is too wide for an add.  */
7092       if (GET_CODE (op) == CONST_INT
7093           || EXTRA_CONSTRAINT_C16 (op))
7094         return 1;
7095       else
7096         return 0;
7097     }
7098   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_I08 (INTVAL (op)))
7099     return 1;
7100
7101   return 0;
7102 }
7103
7104 /* Returns 1 if OP is a valid source operand for a compare insn.  */
7105
7106 int
7107 arith_reg_or_0_operand (rtx op, enum machine_mode mode)
7108 {
7109   if (arith_reg_operand (op, mode))
7110     return 1;
7111
7112   if (EXTRA_CONSTRAINT_Z (op))
7113     return 1;
7114
7115   return 0;
7116 }
7117
7118 /* Return 1 if OP is a valid source operand for an SHmedia operation
7119    that takes either a register or a 6-bit immediate.  */
7120
7121 int
7122 shmedia_6bit_operand (rtx op, enum machine_mode mode)
7123 {
7124   return (arith_reg_operand (op, mode)
7125           || (GET_CODE (op) == CONST_INT && CONST_OK_FOR_I06 (INTVAL (op))));
7126 }
7127
7128 /* Returns 1 if OP is a valid source operand for a logical operation.  */
7129
7130 int
7131 logical_operand (rtx op, enum machine_mode mode)
7132 {
7133   if (arith_reg_operand (op, mode))
7134     return 1;
7135
7136   if (TARGET_SHMEDIA)
7137     {
7138       if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_I10 (INTVAL (op)))
7139         return 1;
7140       else
7141         return 0;
7142     }
7143   else if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_K08 (INTVAL (op)))
7144     return 1;
7145
7146   return 0;
7147 }
7148
7149 int
7150 and_operand (rtx op, enum machine_mode mode)
7151 {
7152   if (logical_operand (op, mode))
7153     return 1;
7154
7155   /* Check mshflo.l / mshflhi.l opportunities.  */
7156   if (TARGET_SHMEDIA
7157       && mode == DImode
7158       && GET_CODE (op) == CONST_INT
7159       && CONST_OK_FOR_J16 (INTVAL (op)))
7160         return 1;
7161
7162   return 0;
7163 }
7164
7165 /* Nonzero if OP is a floating point value with value 0.0.  */
7166
7167 int
7168 fp_zero_operand (rtx op)
7169 {
7170   REAL_VALUE_TYPE r;
7171
7172   if (GET_MODE (op) != SFmode)
7173     return 0;
7174
7175   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
7176   return REAL_VALUES_EQUAL (r, dconst0) && ! REAL_VALUE_MINUS_ZERO (r);
7177 }
7178
7179 /* Nonzero if OP is a floating point value with value 1.0.  */
7180
7181 int
7182 fp_one_operand (rtx op)
7183 {
7184   REAL_VALUE_TYPE r;
7185
7186   if (GET_MODE (op) != SFmode)
7187     return 0;
7188
7189   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
7190   return REAL_VALUES_EQUAL (r, dconst1);
7191 }
7192
7193 /* For -m4 and -m4-single-only, mode switching is used.  If we are
7194    compiling without -mfmovd, movsf_ie isn't taken into account for
7195    mode switching.  We could check in machine_dependent_reorg for
7196    cases where we know we are in single precision mode, but there is
7197    interface to find that out during reload, so we must avoid
7198    choosing an fldi alternative during reload and thus failing to
7199    allocate a scratch register for the constant loading.  */
7200 int
7201 fldi_ok (void)
7202 {
7203   return ! TARGET_SH4 || TARGET_FMOVD || reload_completed;
7204 }
7205
7206 int
7207 tertiary_reload_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7208 {
7209   enum rtx_code code = GET_CODE (op);
7210   return code == MEM || (TARGET_SH4 && code == CONST_DOUBLE);
7211 }
7212
7213 int
7214 fpscr_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7215 {
7216   return (GET_CODE (op) == REG && REGNO (op) == FPSCR_REG
7217           && GET_MODE (op) == PSImode);
7218 }
7219
7220 int
7221 fpul_operand (rtx op, enum machine_mode mode)
7222 {
7223   if (TARGET_SHMEDIA)
7224     return fp_arith_reg_operand (op, mode);
7225
7226   return (GET_CODE (op) == REG
7227           && (REGNO (op) == FPUL_REG || REGNO (op) >= FIRST_PSEUDO_REGISTER)
7228           && GET_MODE (op) == mode);
7229 }
7230
7231 int
7232 symbol_ref_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7233 {
7234   return (GET_CODE (op) == SYMBOL_REF);
7235 }
7236
7237 /* Return the TLS type for TLS symbols, 0 for otherwise.  */
7238 int
7239 tls_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7240 {
7241   if (GET_CODE (op) != SYMBOL_REF)
7242     return 0;
7243   return SYMBOL_REF_TLS_MODEL (op);
7244 }
7245
7246 int
7247 commutative_float_operator (rtx op, enum machine_mode mode)
7248 {
7249   if (GET_MODE (op) != mode)
7250     return 0;
7251   switch (GET_CODE (op))
7252     {
7253     case PLUS:
7254     case MULT:
7255       return 1;
7256     default:
7257       break;
7258     }
7259   return 0;
7260 }
7261
7262 int
7263 noncommutative_float_operator (rtx op, enum machine_mode mode)
7264 {
7265   if (GET_MODE (op) != mode)
7266     return 0;
7267   switch (GET_CODE (op))
7268     {
7269     case MINUS:
7270     case DIV:
7271       return 1;
7272     default:
7273       break;
7274     }
7275   return 0;
7276 }
7277
7278 int
7279 unary_float_operator (rtx op, enum machine_mode mode)
7280 {
7281   if (GET_MODE (op) != mode)
7282     return 0;
7283   switch (GET_CODE (op))
7284     {
7285     case ABS:
7286     case NEG:
7287     case SQRT:
7288       return 1;
7289     default:
7290       break;
7291     }
7292   return 0;
7293 }
7294
7295 int
7296 binary_float_operator (rtx op, enum machine_mode mode)
7297 {
7298   if (GET_MODE (op) != mode)
7299     return 0;
7300   switch (GET_CODE (op))
7301     {
7302     case PLUS:
7303     case MINUS:
7304     case MULT:
7305     case DIV:
7306       return 1;
7307     default:
7308       break;
7309     }
7310   return 0;
7311 }
7312
7313 int
7314 binary_logical_operator (rtx op, enum machine_mode mode)
7315 {
7316   if (GET_MODE (op) != mode)
7317     return 0;
7318   switch (GET_CODE (op))
7319     {
7320     case IOR:
7321     case AND:
7322     case XOR:
7323       return 1;
7324     default:
7325       break;
7326     }
7327   return 0;
7328 }
7329
7330 int
7331 equality_comparison_operator (rtx op, enum machine_mode mode)
7332 {
7333   return ((mode == VOIDmode || GET_MODE (op) == mode)
7334           && (GET_CODE (op) == EQ || GET_CODE (op) == NE));
7335 }
7336
7337 int greater_comparison_operator (rtx op, enum machine_mode mode)
7338 {
7339   if (mode != VOIDmode && GET_MODE (op) == mode)
7340     return 0;
7341   switch (GET_CODE (op))
7342     {
7343     case GT:
7344     case GE:
7345     case GTU:
7346     case GEU:
7347       return 1;
7348     default:
7349       return 0;
7350     }
7351 }
7352
7353 int less_comparison_operator (rtx op, enum machine_mode mode)
7354 {
7355   if (mode != VOIDmode && GET_MODE (op) == mode)
7356     return 0;
7357   switch (GET_CODE (op))
7358     {
7359     case LT:
7360     case LE:
7361     case LTU:
7362     case LEU:
7363       return 1;
7364     default:
7365       return 0;
7366     }
7367 }
7368
7369 /* Accept pseudos and branch target registers.  */
7370 int
7371 target_reg_operand (rtx op, enum machine_mode mode)
7372 {
7373   if (mode != DImode
7374       || GET_MODE (op) != DImode)
7375     return 0;
7376
7377   if (GET_CODE (op) == SUBREG)
7378     op = XEXP (op, 0);
7379
7380   if (GET_CODE (op) != REG)
7381     return 0;
7382
7383   /* We must protect ourselves from matching pseudos that are virtual
7384      register, because they will eventually be replaced with hardware
7385      registers that aren't branch-target registers.  */
7386   if (REGNO (op) > LAST_VIRTUAL_REGISTER
7387       || TARGET_REGISTER_P (REGNO (op)))
7388     return 1;
7389
7390   return 0;
7391 }
7392
7393 /* Same as target_reg_operand, except that label_refs and symbol_refs
7394    are accepted before reload.  */
7395 int
7396 target_operand (rtx op, enum machine_mode mode)
7397 {
7398   if (mode != DImode)
7399     return 0;
7400
7401   if ((GET_MODE (op) == DImode || GET_MODE (op) == VOIDmode)
7402       && EXTRA_CONSTRAINT_Csy (op))
7403     return ! reload_completed;
7404
7405   return target_reg_operand (op, mode);
7406 }
7407
7408 int
7409 mextr_bit_offset (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
7410 {
7411   HOST_WIDE_INT i;
7412
7413   if (GET_CODE (op) != CONST_INT)
7414     return 0;
7415   i = INTVAL (op);
7416   return i >= 1*8 && i <= 7*8 && (i & 7) == 0;
7417 }
7418
7419 int
7420 extend_reg_operand (rtx op, enum machine_mode mode)
7421 {
7422   return (GET_CODE (op) == TRUNCATE
7423           ? arith_operand
7424           : arith_reg_operand) (op, mode);
7425 }
7426
7427 int
7428 trunc_hi_operand (rtx op, enum machine_mode mode)
7429 {
7430   enum machine_mode op_mode = GET_MODE (op);
7431
7432   if (op_mode != SImode && op_mode != DImode
7433       && op_mode != V4HImode && op_mode != V2SImode)
7434     return 0;
7435   return extend_reg_operand (op, mode);
7436 }
7437
7438 int
7439 extend_reg_or_0_operand (rtx op, enum machine_mode mode)
7440 {
7441   return (GET_CODE (op) == TRUNCATE
7442           ? arith_operand
7443           : arith_reg_or_0_operand) (op, mode);
7444 }
7445
7446 int
7447 general_extend_operand (rtx op, enum machine_mode mode)
7448 {
7449   return (GET_CODE (op) == TRUNCATE
7450           ? arith_operand
7451           : nonimmediate_operand) (op, mode);
7452 }
7453
7454 int
7455 inqhi_operand (rtx op, enum machine_mode mode)
7456 {
7457   if (GET_CODE (op) != TRUNCATE || mode != GET_MODE (op))
7458     return 0;
7459   op = XEXP (op, 0);
7460   /* Can't use true_regnum here because copy_cost wants to know about
7461      SECONDARY_INPUT_RELOAD_CLASS.  */
7462   return GET_CODE (op) == REG && FP_REGISTER_P (REGNO (op));
7463 }
7464
7465 int
7466 sh_rep_vec (rtx v, enum machine_mode mode)
7467 {
7468   int i;
7469   rtx x, y;
7470
7471   if ((GET_CODE (v) != CONST_VECTOR && GET_CODE (v) != PARALLEL)
7472       || (GET_MODE (v) != mode && mode != VOIDmode))
7473     return 0;
7474   i = XVECLEN (v, 0) - 2;
7475   x = XVECEXP (v, 0, i + 1);
7476   if (GET_MODE_UNIT_SIZE (mode) == 1)
7477     {
7478       y = XVECEXP (v, 0, i);
7479       for (i -= 2 ; i >= 0; i -= 2)
7480         if (! rtx_equal_p (XVECEXP (v, 0, i + 1), x)
7481             || ! rtx_equal_p (XVECEXP (v, 0, i), y))
7482           return 0;
7483     }
7484   else
7485     for (; i >= 0; i--)
7486       if (XVECEXP (v, 0, i) != x)
7487         return 0;
7488   return 1;
7489 }
7490
7491 /* Determine if V is a constant vector matching MODE with only one element
7492    that is not a sign extension.  Two byte-sized elements count as one.  */
7493 int
7494 sh_1el_vec (rtx v, enum machine_mode mode)
7495 {
7496   int unit_size;
7497   int i, last, least, sign_ix;
7498   rtx sign;
7499
7500   if (GET_CODE (v) != CONST_VECTOR
7501       || (GET_MODE (v) != mode && mode != VOIDmode))
7502     return 0;
7503   /* Determine numbers of last and of least significant elements.  */
7504   last = XVECLEN (v, 0) - 1;
7505   least = TARGET_LITTLE_ENDIAN ? 0 : last;
7506   if (GET_CODE (XVECEXP (v, 0, least)) != CONST_INT)
7507     return 0;
7508   sign_ix = least;
7509   if (GET_MODE_UNIT_SIZE (mode) == 1)
7510     sign_ix = TARGET_LITTLE_ENDIAN ? 1 : last - 1;
7511   if (GET_CODE (XVECEXP (v, 0, sign_ix)) != CONST_INT)
7512     return 0;
7513   unit_size = GET_MODE_UNIT_SIZE (GET_MODE (v));
7514   sign = (INTVAL (XVECEXP (v, 0, sign_ix)) >> (unit_size * BITS_PER_UNIT - 1)
7515           ? constm1_rtx : const0_rtx);
7516   i = XVECLEN (v, 0) - 1;
7517   do
7518     if (i != least && i != sign_ix && XVECEXP (v, 0, i) != sign)
7519       return 0;
7520   while (--i);
7521   return 1;
7522 }
7523
7524 int
7525 sh_const_vec (rtx v, enum machine_mode mode)
7526 {
7527   int i;
7528
7529   if (GET_CODE (v) != CONST_VECTOR
7530       || (GET_MODE (v) != mode && mode != VOIDmode))
7531     return 0;
7532   i = XVECLEN (v, 0) - 1;
7533   for (; i >= 0; i--)
7534     if (GET_CODE (XVECEXP (v, 0, i)) != CONST_INT)
7535       return 0;
7536   return 1;
7537 }
7538 \f
7539 /* Return the destination address of a branch.  */
7540    
7541 static int
7542 branch_dest (rtx branch)
7543 {
7544   rtx dest = SET_SRC (PATTERN (branch));
7545   int dest_uid;
7546
7547   if (GET_CODE (dest) == IF_THEN_ELSE)
7548     dest = XEXP (dest, 1);
7549   dest = XEXP (dest, 0);
7550   dest_uid = INSN_UID (dest);
7551   return INSN_ADDRESSES (dest_uid);
7552 }
7553 \f
7554 /* Return nonzero if REG is not used after INSN.
7555    We assume REG is a reload reg, and therefore does
7556    not live past labels.  It may live past calls or jumps though.  */
7557 int
7558 reg_unused_after (rtx reg, rtx insn)
7559 {
7560   enum rtx_code code;
7561   rtx set;
7562
7563   /* If the reg is set by this instruction, then it is safe for our
7564      case.  Disregard the case where this is a store to memory, since
7565      we are checking a register used in the store address.  */
7566   set = single_set (insn);
7567   if (set && GET_CODE (SET_DEST (set)) != MEM
7568       && reg_overlap_mentioned_p (reg, SET_DEST (set)))
7569     return 1;
7570
7571   while ((insn = NEXT_INSN (insn)))
7572     {
7573       code = GET_CODE (insn);
7574
7575 #if 0
7576       /* If this is a label that existed before reload, then the register
7577          if dead here.  However, if this is a label added by reorg, then
7578          the register may still be live here.  We can't tell the difference,
7579          so we just ignore labels completely.  */
7580       if (code == CODE_LABEL)
7581         return 1;
7582       /* else */
7583 #endif
7584
7585       if (code == JUMP_INSN)
7586         return 0;
7587
7588       /* If this is a sequence, we must handle them all at once.
7589          We could have for instance a call that sets the target register,
7590          and an insn in a delay slot that uses the register.  In this case,
7591          we must return 0.  */
7592       else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
7593         {
7594           int i;
7595           int retval = 0;
7596
7597           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
7598             {
7599               rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
7600               rtx set = single_set (this_insn);
7601
7602               if (GET_CODE (this_insn) == CALL_INSN)
7603                 code = CALL_INSN;
7604               else if (GET_CODE (this_insn) == JUMP_INSN)
7605                 {
7606                   if (INSN_ANNULLED_BRANCH_P (this_insn))
7607                     return 0;
7608                   code = JUMP_INSN;
7609                 }
7610
7611               if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
7612                 return 0;
7613               if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
7614                 {
7615                   if (GET_CODE (SET_DEST (set)) != MEM)
7616                     retval = 1;
7617                   else
7618                     return 0;
7619                 }
7620               if (set == 0
7621                   && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
7622                 return 0;
7623             }
7624           if (retval == 1)
7625             return 1;
7626           else if (code == JUMP_INSN)
7627             return 0;
7628         }
7629       else if (GET_RTX_CLASS (code) == 'i')
7630         {
7631           rtx set = single_set (insn);
7632
7633           if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
7634             return 0;
7635           if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
7636             return GET_CODE (SET_DEST (set)) != MEM;
7637           if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
7638             return 0;
7639         }
7640
7641       if (code == CALL_INSN && call_used_regs[REGNO (reg)])
7642         return 1;
7643     }
7644   return 1;
7645 }
7646 \f
7647 #include "ggc.h"
7648
7649 static GTY(()) rtx fpscr_rtx;
7650 rtx
7651 get_fpscr_rtx (void)
7652 {
7653   if (! fpscr_rtx)
7654     {
7655       fpscr_rtx = gen_rtx (REG, PSImode, FPSCR_REG);
7656       REG_USERVAR_P (fpscr_rtx) = 1;
7657       mark_user_reg (fpscr_rtx);
7658     }
7659   if (! reload_completed || mdep_reorg_phase != SH_AFTER_MDEP_REORG)
7660     mark_user_reg (fpscr_rtx);
7661   return fpscr_rtx;
7662 }
7663
7664 void
7665 emit_sf_insn (rtx pat)
7666 {
7667   emit_insn (pat);
7668 }
7669
7670 void
7671 emit_df_insn (rtx pat)
7672 {
7673   emit_insn (pat);
7674 }
7675
7676 void
7677 expand_sf_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
7678 {
7679   emit_sf_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
7680 }
7681
7682 void
7683 expand_sf_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
7684 {
7685   emit_sf_insn ((*fun) (operands[0], operands[1], operands[2],
7686                          get_fpscr_rtx ()));
7687 }
7688
7689 void
7690 expand_df_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
7691 {
7692   emit_df_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
7693 }
7694
7695 void
7696 expand_df_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
7697 {
7698   emit_df_insn ((*fun) (operands[0], operands[1], operands[2],
7699                          get_fpscr_rtx ()));
7700 }
7701 \f
7702 /* ??? gcc does flow analysis strictly after common subexpression
7703    elimination.  As a result, common subexpression elimination fails
7704    when there are some intervening statements setting the same register.
7705    If we did nothing about this, this would hurt the precision switching
7706    for SH4 badly.  There is some cse after reload, but it is unable to
7707    undo the extra register pressure from the unused instructions, and
7708    it cannot remove auto-increment loads.
7709
7710    A C code example that shows this flow/cse weakness for (at least) SH
7711    and sparc (as of gcc ss-970706) is this:
7712
7713 double
7714 f(double a)
7715 {
7716   double d;
7717   d = 0.1;
7718   a += d;
7719   d = 1.1;
7720   d = 0.1;
7721   a *= d;
7722   return a;
7723 }
7724
7725    So we add another pass before common subexpression elimination, to
7726    remove assignments that are dead due to a following assignment in the
7727    same basic block.  */
7728
7729 static void 
7730 mark_use (rtx x, rtx *reg_set_block)
7731 {
7732   enum rtx_code code;
7733
7734   if (! x)
7735     return;
7736   code = GET_CODE (x);
7737   switch (code)
7738     {
7739     case REG:
7740       {
7741         int regno = REGNO (x);
7742         int nregs = (regno < FIRST_PSEUDO_REGISTER
7743                      ? HARD_REGNO_NREGS (regno, GET_MODE (x))
7744                      : 1);
7745         do
7746           {
7747             reg_set_block[regno + nregs - 1] = 0;
7748           }
7749         while (--nregs);
7750         break;
7751       }
7752     case SET:
7753       {
7754         rtx dest = SET_DEST (x);
7755
7756         if (GET_CODE (dest) == SUBREG)
7757           dest = SUBREG_REG (dest);
7758         if (GET_CODE (dest) != REG)
7759           mark_use (dest, reg_set_block);
7760         mark_use (SET_SRC (x), reg_set_block);
7761         break;
7762       }
7763     case CLOBBER:
7764       break;
7765     default:
7766       {
7767         const char *fmt = GET_RTX_FORMAT (code);
7768         int i, j;
7769         for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7770           {
7771             if (fmt[i] == 'e')
7772               mark_use (XEXP (x, i), reg_set_block);
7773             else if (fmt[i] == 'E')
7774               for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7775                 mark_use (XVECEXP (x, i, j), reg_set_block);
7776           }
7777         break;
7778       }
7779     }
7780 }
7781 \f
7782 static rtx get_free_reg (HARD_REG_SET);
7783
7784 /* This function returns a register to use to load the address to load
7785    the fpscr from.  Currently it always returns r1 or r7, but when we are
7786    able to use pseudo registers after combine, or have a better mechanism
7787    for choosing a register, it should be done here.  */
7788 /* REGS_LIVE is the liveness information for the point for which we
7789    need this allocation.  In some bare-bones exit blocks, r1 is live at the
7790    start.  We can even have all of r0..r3 being live:
7791 __complex__ long long f (double d) { if (d == 0) return 2; else return 3; }
7792    INSN before which new insns are placed with will clobber the register
7793    we return.  If a basic block consists only of setting the return value
7794    register to a pseudo and using that register, the return value is not
7795    live before or after this block, yet we we'll insert our insns right in
7796    the middle.  */
7797
7798 static rtx
7799 get_free_reg (HARD_REG_SET regs_live)
7800 {
7801   if (! TEST_HARD_REG_BIT (regs_live, 1))
7802     return gen_rtx_REG (Pmode, 1);
7803
7804   /* Hard reg 1 is live; since this is a SMALL_REGISTER_CLASSES target,
7805      there shouldn't be anything but a jump before the function end.  */
7806   if (! TEST_HARD_REG_BIT (regs_live, 7))
7807     return gen_rtx_REG (Pmode, 7);
7808
7809   abort ();
7810 }
7811
7812 /* This function will set the fpscr from memory. 
7813    MODE is the mode we are setting it to.  */
7814 void
7815 fpscr_set_from_mem (int mode, HARD_REG_SET regs_live)
7816 {
7817   enum attr_fp_mode fp_mode = mode;
7818   rtx addr_reg = get_free_reg (regs_live);
7819
7820   if (fp_mode == (enum attr_fp_mode) ACTUAL_NORMAL_MODE (FP_MODE))
7821     emit_insn (gen_fpu_switch1 (addr_reg));
7822   else
7823     emit_insn (gen_fpu_switch0 (addr_reg));
7824 }
7825
7826 /* Is the given character a logical line separator for the assembler?  */
7827 #ifndef IS_ASM_LOGICAL_LINE_SEPARATOR
7828 #define IS_ASM_LOGICAL_LINE_SEPARATOR(C) ((C) == ';')
7829 #endif
7830
7831 int
7832 sh_insn_length_adjustment (rtx insn)
7833 {
7834   /* Instructions with unfilled delay slots take up an extra two bytes for
7835      the nop in the delay slot.  */
7836   if (((GET_CODE (insn) == INSN
7837         && GET_CODE (PATTERN (insn)) != USE
7838         && GET_CODE (PATTERN (insn)) != CLOBBER)
7839        || GET_CODE (insn) == CALL_INSN
7840        || (GET_CODE (insn) == JUMP_INSN
7841            && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
7842            && GET_CODE (PATTERN (insn)) != ADDR_VEC))
7843       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE
7844       && get_attr_needs_delay_slot (insn) == NEEDS_DELAY_SLOT_YES)
7845     return 2;
7846
7847   /* SH2e has a bug that prevents the use of annulled branches, so if
7848      the delay slot is not filled, we'll have to put a NOP in it.  */
7849   if (sh_cpu == CPU_SH2E
7850       && GET_CODE (insn) == JUMP_INSN
7851       && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
7852       && GET_CODE (PATTERN (insn)) != ADDR_VEC
7853       && get_attr_type (insn) == TYPE_CBRANCH
7854       && GET_CODE (PATTERN (NEXT_INSN (PREV_INSN (insn)))) != SEQUENCE)
7855     return 2;
7856
7857   /* sh-dsp parallel processing insn take four bytes instead of two.  */
7858      
7859   if (GET_CODE (insn) == INSN)
7860     {
7861       int sum = 0;
7862       rtx body = PATTERN (insn);
7863       const char *template;
7864       char c;
7865       int maybe_label = 1;
7866
7867       if (GET_CODE (body) == ASM_INPUT)
7868         template = XSTR (body, 0);
7869       else if (asm_noperands (body) >= 0)
7870         template
7871           = decode_asm_operands (body, NULL, NULL, NULL, NULL);
7872       else
7873         return 0;
7874       do
7875         {
7876           int ppi_adjust = 0;
7877
7878           do
7879             c = *template++;
7880           while (c == ' ' || c == '\t');
7881           /* all sh-dsp parallel-processing insns start with p.
7882              The only non-ppi sh insn starting with p is pref.
7883              The only ppi starting with pr is prnd.  */
7884           if ((c == 'p' || c == 'P') && strncasecmp ("re", template, 2))
7885             ppi_adjust = 2;
7886           /* The repeat pseudo-insn expands two three insns, a total of
7887              six bytes in size.  */
7888           else if ((c == 'r' || c == 'R')
7889                    && ! strncasecmp ("epeat", template, 5))
7890             ppi_adjust = 4;
7891           while (c && c != '\n' && ! IS_ASM_LOGICAL_LINE_SEPARATOR (c))
7892             {
7893               /* If this is a label, it is obviously not a ppi insn.  */
7894               if (c == ':' && maybe_label)
7895                 {
7896                   ppi_adjust = 0;
7897                   break;
7898                 }
7899               else if (c == '\'' || c == '"')
7900                 maybe_label = 0;
7901               c = *template++;
7902             }
7903           sum += ppi_adjust;
7904           maybe_label = c != ':';
7905         }
7906       while (c);
7907       return sum;
7908     }
7909   return 0;
7910 }
7911 \f
7912 /* Return TRUE if X references a SYMBOL_REF or LABEL_REF whose symbol
7913    isn't protected by a PIC unspec.  */
7914 int
7915 nonpic_symbol_mentioned_p (rtx x)
7916 {
7917   register const char *fmt;
7918   register int i;
7919
7920   if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF
7921       || GET_CODE (x) == PC)
7922     return 1;
7923
7924   /* We don't want to look into the possible MEM location of a
7925      CONST_DOUBLE, since we're not going to use it, in general.  */
7926   if (GET_CODE (x) == CONST_DOUBLE)
7927     return 0;
7928
7929   if (GET_CODE (x) == UNSPEC
7930       && (XINT (x, 1) == UNSPEC_PIC
7931           || XINT (x, 1) == UNSPEC_GOT
7932           || XINT (x, 1) == UNSPEC_GOTOFF
7933           || XINT (x, 1) == UNSPEC_GOTPLT
7934           || XINT (x, 1) == UNSPEC_GOTTPOFF
7935           || XINT (x, 1) == UNSPEC_DTPOFF
7936           || XINT (x, 1) == UNSPEC_PLT))
7937       return 0;
7938
7939   fmt = GET_RTX_FORMAT (GET_CODE (x));
7940   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
7941     {
7942       if (fmt[i] == 'E')
7943         {
7944           register int j;
7945
7946           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7947             if (nonpic_symbol_mentioned_p (XVECEXP (x, i, j)))
7948               return 1;
7949         }
7950       else if (fmt[i] == 'e' && nonpic_symbol_mentioned_p (XEXP (x, i)))
7951         return 1;
7952     }
7953
7954   return 0;
7955 }
7956
7957 /* Convert a non-PIC address in `orig' to a PIC address using @GOT or
7958    @GOTOFF in `reg'.  */
7959 rtx
7960 legitimize_pic_address (rtx orig, enum machine_mode mode ATTRIBUTE_UNUSED,
7961                         rtx reg)
7962 {
7963   if (tls_symbolic_operand (orig, Pmode))
7964     return orig;
7965
7966   if (GET_CODE (orig) == LABEL_REF
7967       || (GET_CODE (orig) == SYMBOL_REF && SYMBOL_REF_LOCAL_P (orig)))
7968     {
7969       if (reg == 0)
7970         reg = gen_reg_rtx (Pmode);
7971
7972       emit_insn (gen_symGOTOFF2reg (reg, orig));
7973       return reg;
7974     }
7975   else if (GET_CODE (orig) == SYMBOL_REF)
7976     {
7977       if (reg == 0)
7978         reg = gen_reg_rtx (Pmode);
7979
7980       emit_insn (gen_symGOT2reg (reg, orig));
7981       return reg;
7982     }
7983   return orig;
7984 }
7985
7986 /* Mark the use of a constant in the literal table. If the constant
7987    has multiple labels, make it unique.  */
7988 static rtx
7989 mark_constant_pool_use (rtx x)
7990 {
7991   rtx insn, lab, pattern;
7992
7993   if (x == NULL)
7994     return x;
7995
7996   switch (GET_CODE (x))
7997     {
7998     case LABEL_REF:
7999       x = XEXP (x, 0);
8000     case CODE_LABEL:
8001       break;
8002     default:
8003       return x;
8004     }
8005
8006   /* Get the first label in the list of labels for the same constant
8007      and delete another labels in the list.  */
8008   lab = x;
8009   for (insn = PREV_INSN (x); insn; insn = PREV_INSN (insn))
8010     {
8011       if (GET_CODE (insn) != CODE_LABEL
8012           || LABEL_REFS (insn) != NEXT_INSN (insn))
8013         break;
8014       lab = insn;
8015     }
8016
8017   for (insn = LABEL_REFS (lab); insn; insn = LABEL_REFS (insn))
8018     INSN_DELETED_P (insn) = 1;
8019
8020   /* Mark constants in a window.  */
8021   for (insn = NEXT_INSN (x); insn; insn = NEXT_INSN (insn))
8022     {
8023       if (GET_CODE (insn) != INSN)
8024         continue;
8025
8026       pattern = PATTERN (insn);
8027       if (GET_CODE (pattern) != UNSPEC_VOLATILE)
8028         continue;
8029
8030       switch (XINT (pattern, 1))
8031         {
8032         case UNSPECV_CONST2:
8033         case UNSPECV_CONST4:
8034         case UNSPECV_CONST8:
8035           XVECEXP (pattern, 0, 1) = const1_rtx;
8036           break;
8037         case UNSPECV_WINDOW_END:
8038           if (XVECEXP (pattern, 0, 0) == x)
8039             return lab;
8040           break;
8041         case UNSPECV_CONST_END:
8042           return lab;
8043         default:
8044           break;
8045         }
8046     }
8047
8048   return lab;
8049 }
8050 \f
8051 /* Return true if it's possible to redirect BRANCH1 to the destination
8052    of an unconditional jump BRANCH2.  We only want to do this if the
8053    resulting branch will have a short displacement.  */
8054 int 
8055 sh_can_redirect_branch (rtx branch1, rtx branch2)
8056 {
8057   if (flag_expensive_optimizations && simplejump_p (branch2))
8058     {
8059       rtx dest = XEXP (SET_SRC (single_set (branch2)), 0);
8060       rtx insn;
8061       int distance;
8062       
8063       for (distance = 0, insn = NEXT_INSN (branch1); 
8064            insn && distance < 256; 
8065            insn = PREV_INSN (insn))
8066         {
8067           if (insn == dest)    
8068             return 1;
8069           else
8070             distance += get_attr_length (insn);
8071         }
8072       for (distance = 0, insn = NEXT_INSN (branch1); 
8073            insn && distance < 256; 
8074            insn = NEXT_INSN (insn))
8075         {
8076           if (insn == dest)    
8077             return 1;
8078           else
8079             distance += get_attr_length (insn);
8080         }
8081     }
8082   return 0;
8083 }
8084
8085 /* Return nonzero if register old_reg can be renamed to register new_reg.  */
8086 int
8087 sh_hard_regno_rename_ok (unsigned int old_reg ATTRIBUTE_UNUSED,
8088                          unsigned int new_reg)
8089 {
8090
8091 /* Interrupt functions can only use registers that have already been
8092    saved by the prologue, even if they would normally be
8093    call-clobbered.  */
8094
8095   if (sh_cfun_interrupt_handler_p () && !regs_ever_live[new_reg])
8096      return 0;
8097
8098    return 1;
8099 }
8100
8101 /* Function to update the integer COST
8102    based on the relationship between INSN that is dependent on
8103    DEP_INSN through the dependence LINK.  The default is to make no
8104    adjustment to COST.  This can be used for example to specify to
8105    the scheduler that an output- or anti-dependence does not incur
8106    the same cost as a data-dependence.  The return value should be
8107    the new value for COST.  */
8108 static int
8109 sh_adjust_cost (rtx insn, rtx link ATTRIBUTE_UNUSED, rtx dep_insn, int cost)
8110 {
8111   rtx reg, use_pat;
8112
8113   if (TARGET_SHMEDIA)
8114     {
8115       /* On SHmedia, if the dependence is an anti-dependence or
8116          output-dependence, there is no cost.  */
8117       if (REG_NOTE_KIND (link) != 0)
8118         cost = 0;
8119
8120       if (get_attr_is_mac_media (insn)
8121           && get_attr_is_mac_media (dep_insn))
8122         cost = 1;
8123     }
8124   else if (REG_NOTE_KIND (link) == 0)
8125     {
8126       enum attr_type dep_type, type;
8127
8128       if (recog_memoized (insn) < 0
8129           || recog_memoized (dep_insn) < 0)
8130         return cost;
8131
8132       dep_type = get_attr_type (dep_insn);
8133       if (dep_type == TYPE_FLOAD || dep_type == TYPE_PCFLOAD)
8134         cost--;
8135       if ((dep_type == TYPE_LOAD_SI || dep_type == TYPE_PCLOAD_SI)
8136           && (type = get_attr_type (insn)) != TYPE_CALL
8137           && type != TYPE_SFUNC)
8138         cost--;
8139
8140       /* The only input for a call that is timing-critical is the
8141          function's address.  */
8142       if (GET_CODE(insn) == CALL_INSN)
8143         {
8144           rtx call = PATTERN (insn);
8145
8146           if (GET_CODE (call) == PARALLEL)
8147             call = XVECEXP (call, 0 ,0);
8148           if (GET_CODE (call) == SET)
8149             call = SET_SRC (call);
8150           if (GET_CODE (call) == CALL && GET_CODE (XEXP (call, 0)) == MEM
8151               && ! reg_set_p (XEXP (XEXP (call, 0), 0), dep_insn))
8152             cost = 0;
8153         }
8154       /* Likewise, the most timing critical input for an sfuncs call
8155          is the function address.  However, sfuncs typically start
8156          using their arguments pretty quickly.
8157          Assume a four cycle delay before they are needed.  */
8158       /* All sfunc calls are parallels with at least four components.
8159          Exploit this to avoid unnecessary calls to sfunc_uses_reg.  */
8160       else if (GET_CODE (PATTERN (insn)) == PARALLEL
8161                && XVECLEN (PATTERN (insn), 0) >= 4
8162                && (reg = sfunc_uses_reg (insn)))
8163         {
8164           if (! reg_set_p (reg, dep_insn))
8165             cost -= 4;
8166         }
8167       /* When the preceding instruction loads the shift amount of
8168          the following SHAD/SHLD, the latency of the load is increased
8169          by 1 cycle.  */
8170       else if (TARGET_SH4
8171                && get_attr_type (insn) == TYPE_DYN_SHIFT
8172                && get_attr_any_int_load (dep_insn) == ANY_INT_LOAD_YES
8173                && reg_overlap_mentioned_p (SET_DEST (PATTERN (dep_insn)),
8174                                            XEXP (SET_SRC (single_set(insn)),
8175                                                  1)))
8176         cost++;
8177       /* When an LS group instruction with a latency of less than
8178          3 cycles is followed by a double-precision floating-point
8179          instruction, FIPR, or FTRV, the latency of the first
8180          instruction is increased to 3 cycles.  */
8181       else if (cost < 3
8182                && get_attr_insn_class (dep_insn) == INSN_CLASS_LS_GROUP
8183                && get_attr_dfp_comp (insn) == DFP_COMP_YES)
8184         cost = 3;
8185       /* The lsw register of a double-precision computation is ready one
8186          cycle earlier.  */
8187       else if (reload_completed
8188                && get_attr_dfp_comp (dep_insn) == DFP_COMP_YES
8189                && (use_pat = single_set (insn))
8190                && ! regno_use_in (REGNO (SET_DEST (single_set (dep_insn))),
8191                                   SET_SRC (use_pat)))
8192         cost -= 1;
8193
8194       if (get_attr_any_fp_comp (dep_insn) == ANY_FP_COMP_YES
8195           && get_attr_late_fp_use (insn) == LATE_FP_USE_YES)
8196         cost -= 1;
8197     }
8198   /* An anti-dependence penalty of two applies if the first insn is a double
8199      precision fadd / fsub / fmul.  */
8200   else if (REG_NOTE_KIND (link) == REG_DEP_ANTI
8201            && recog_memoized (dep_insn) >= 0
8202            && get_attr_type (dep_insn) == TYPE_DFP_ARITH
8203            /* A lot of alleged anti-flow dependences are fake,
8204               so check this one is real.  */
8205            && flow_dependent_p (dep_insn, insn))
8206     cost = 2;
8207
8208
8209   return cost;
8210 }
8211
8212 /* Check if INSN is flow-dependent on DEP_INSN.  Can also be used to check
8213    if DEP_INSN is anti-flow dependent on INSN.  */
8214 static int
8215 flow_dependent_p (rtx insn, rtx dep_insn)
8216 {
8217   rtx tmp = PATTERN (insn);
8218
8219   note_stores (PATTERN (dep_insn), flow_dependent_p_1, &tmp);
8220   return tmp == NULL_RTX;
8221 }
8222
8223 /* A helper function for flow_dependent_p called through note_stores.  */
8224 static void
8225 flow_dependent_p_1 (rtx x, rtx pat ATTRIBUTE_UNUSED, void *data)
8226 {
8227   rtx * pinsn = (rtx *) data;
8228
8229   if (*pinsn && reg_referenced_p (x, *pinsn))
8230     *pinsn = NULL_RTX;
8231 }
8232
8233 /* For use by ALLOCATE_INITIAL_VALUE.  Note that sh.md contains some
8234    'special function' patterns (type sfunc) that clobber pr, but that
8235    do not look like function calls to leaf_function_p.  Hence we must
8236    do this extra check.  */
8237 int
8238 sh_pr_n_sets (void)
8239 {
8240   return REG_N_SETS (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
8241 }
8242
8243 /* This Function returns nonzero if the DFA based scheduler interface
8244    is to be used.  At present this is supported for the SH4 only.  */
8245 static int
8246 sh_use_dfa_interface(void)
8247 {
8248   if (TARGET_HARD_SH4)
8249     return 1;
8250   else
8251     return 0;
8252 }
8253
8254 /* This function returns "2" to indicate dual issue for the SH4
8255    processor.  To be used by the DFA pipeline description.  */
8256 static int
8257 sh_issue_rate(void)
8258 {
8259   if (TARGET_SUPERSCALAR)
8260     return 2;
8261   else
8262     return 1;
8263 }
8264
8265 /* SHmedia requires registers for branches, so we can't generate new
8266    branches past reload.  */
8267 static bool
8268 sh_cannot_modify_jumps_p (void)
8269 {
8270   return (TARGET_SHMEDIA && (reload_in_progress || reload_completed));
8271 }
8272
8273 static int
8274 sh_target_reg_class (void)
8275 {
8276   return TARGET_SHMEDIA ? TARGET_REGS : NO_REGS;
8277 }
8278
8279 static bool
8280 sh_optimize_target_register_callee_saved (bool after_prologue_epilogue_gen)
8281 {
8282   return (shmedia_space_reserved_for_target_registers
8283           && (! after_prologue_epilogue_gen || TARGET_SAVE_ALL_TARGET_REGS));
8284 }
8285
8286 static bool
8287 sh_ms_bitfield_layout_p (record_type)
8288      tree record_type ATTRIBUTE_UNUSED;
8289 {
8290   return (TARGET_SH5 || TARGET_HITACHI || sh_attr_renesas_p (record_type));
8291 }
8292 \f
8293 /* 
8294    On the SH1..SH4, the trampoline looks like
8295    2 0002 D202                  mov.l   l2,r2
8296    1 0000 D301                  mov.l   l1,r3
8297    3 0004 422B                  jmp     @r2
8298    4 0006 0009                  nop
8299    5 0008 00000000      l1:     .long   area
8300    6 000c 00000000      l2:     .long   function
8301
8302    SH5 (compact) uses r1 instead of r3 for the static chain.  */
8303
8304
8305 /* Emit RTL insns to initialize the variable parts of a trampoline.
8306    FNADDR is an RTX for the address of the function's pure code.
8307    CXT is an RTX for the static chain value for the function.  */
8308
8309 void
8310 sh_initialize_trampoline (rtx tramp, rtx fnaddr, rtx cxt)
8311 {
8312   if (TARGET_SHMEDIA64)
8313     {
8314       rtx tramp_templ;
8315       int fixed_len;
8316
8317       rtx movi1 = GEN_INT (0xcc000010);
8318       rtx shori1 = GEN_INT (0xc8000010);
8319       rtx src, dst;
8320
8321       /* The following trampoline works within a +- 128 KB range for cxt:
8322          ptb/u cxt,tr1; movi fnaddr >> 48,r0; shori fnaddr >> 32,r0;
8323          shori fnaddr >> 16,r0; shori fnaddr,r0; ptabs/l r0,tr0
8324          gettr tr1,r1; blink tr0,r63  */
8325       /* Address rounding makes it hard to compute the exact bounds of the
8326          offset for this trampoline, but we have a rather generous offset
8327          range, so frame_offset should do fine as an upper bound.  */
8328       if (cxt == virtual_stack_vars_rtx && frame_offset < 0x20000)
8329         {
8330           /* ??? could optimize this trampoline initialization
8331              by writing DImode words with two insns each.  */
8332           rtx mask = force_reg (DImode, GEN_INT (0x3fffc00));
8333           rtx insn = gen_rtx_MINUS (DImode, cxt, tramp);
8334           insn = gen_rtx_ASHIFT (DImode, insn, GEN_INT (10-2));
8335           insn = gen_rtx_AND (DImode, insn, mask);
8336           /* Or in ptb/u .,tr1 pattern */
8337           insn = gen_rtx_IOR (DImode, insn, gen_int_mode (0xec000010, SImode));
8338           insn = force_operand (insn, NULL_RTX);
8339           insn = gen_lowpart (SImode, insn);
8340           emit_move_insn (gen_rtx_MEM (SImode, tramp), insn);
8341           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (38));
8342           insn = gen_rtx_AND (DImode, insn, mask);
8343           insn = force_operand (gen_rtx_IOR (DImode, movi1, insn), NULL_RTX);
8344           insn = gen_lowpart (SImode, insn);
8345           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 4)), insn);
8346           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (22));
8347           insn = gen_rtx_AND (DImode, insn, mask);
8348           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
8349           insn = gen_lowpart (SImode, insn);
8350           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 8)), insn);
8351           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (6));
8352           insn = gen_rtx_AND (DImode, insn, mask);
8353           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
8354           insn = gen_lowpart (SImode, insn);
8355           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 12)),
8356                           insn);
8357           insn = gen_rtx_ASHIFT (DImode, fnaddr, GEN_INT (10));
8358           insn = gen_rtx_AND (DImode, insn, mask);
8359           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
8360           insn = gen_lowpart (SImode, insn);
8361           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 16)),
8362                           insn);
8363           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 20)),
8364                           GEN_INT (0x6bf10600));
8365           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 24)),
8366                           GEN_INT (0x4415fc10));
8367           emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 28)),
8368                           GEN_INT (0x4401fff0));
8369           emit_insn (gen_ic_invalidate_line (tramp));
8370           return;
8371         }
8372       tramp_templ = gen_rtx_SYMBOL_REF (Pmode,"__GCC_nested_trampoline");
8373       fixed_len = TRAMPOLINE_SIZE - 2 * GET_MODE_SIZE (Pmode);
8374
8375       tramp_templ = gen_datalabel_ref (tramp_templ);
8376       dst = gen_rtx_MEM (BLKmode, tramp);
8377       src = gen_rtx_MEM (BLKmode, tramp_templ);
8378       set_mem_align (dst, 256);
8379       set_mem_align (src, 64);
8380       emit_block_move (dst, src, GEN_INT (fixed_len), BLOCK_OP_NORMAL);
8381
8382       emit_move_insn (gen_rtx_MEM (Pmode, plus_constant (tramp, fixed_len)),
8383                       fnaddr);
8384       emit_move_insn (gen_rtx_MEM (Pmode,
8385                                    plus_constant (tramp,
8386                                                   fixed_len
8387                                                   + GET_MODE_SIZE (Pmode))), 
8388                       cxt);
8389       emit_insn (gen_ic_invalidate_line (tramp));
8390       return;
8391     }
8392   else if (TARGET_SHMEDIA)
8393     {
8394       /* movi fnaddr >> 16,r1; shori fnaddr,r1; ptabs/l r1,tr0
8395          movi cxt >> 16,r1; shori cxt,r1; blink tr0,r63  */
8396       rtx quad0 = gen_reg_rtx (DImode), cxtload = gen_reg_rtx (DImode);
8397       rtx quad1 = gen_reg_rtx (DImode), quad2 = gen_reg_rtx (DImode);
8398       /* movi 0,r1: 0xcc000010 shori 0,r1: c8000010  concatenated,
8399          rotated 10 right, and higher 16 bit of every 32 selected.  */
8400       rtx movishori
8401         = force_reg (V2HImode, (simplify_gen_subreg
8402                                 (V2HImode, GEN_INT (0x4330432), SImode, 0)));
8403       rtx ptabs = force_reg (DImode, GEN_INT (0x6bf10600));
8404       rtx blink = force_reg (DImode, GEN_INT (0x4401fff0));
8405
8406       tramp = force_reg (Pmode, tramp);
8407       fnaddr = force_reg (SImode, fnaddr);
8408       cxt = force_reg (SImode, cxt);
8409       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, quad0, 0),
8410                                  gen_rtx_SUBREG (V2HImode, fnaddr, 0),
8411                                  movishori));
8412       emit_insn (gen_rotrdi3_mextr (quad0, quad0,
8413                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
8414       emit_insn (gen_ashldi3_media (quad0, quad0, GEN_INT (2)));
8415       emit_move_insn (gen_rtx_MEM (DImode, tramp), quad0);
8416       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, cxtload, 0),
8417                                  gen_rtx_SUBREG (V2HImode, cxt, 0),
8418                                  movishori));
8419       emit_insn (gen_rotrdi3_mextr (cxtload, cxtload,
8420                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
8421       emit_insn (gen_ashldi3_media (cxtload, cxtload, GEN_INT (2)));
8422       if (TARGET_LITTLE_ENDIAN)
8423         {
8424           emit_insn (gen_mshflo_l_di (quad1, ptabs, cxtload));
8425           emit_insn (gen_mextr4 (quad2, cxtload, blink));
8426         }
8427       else
8428         {
8429           emit_insn (gen_mextr4 (quad1, cxtload, ptabs));
8430           emit_insn (gen_mshflo_l_di (quad2, blink, cxtload));
8431         }
8432       emit_move_insn (gen_rtx_MEM (DImode, plus_constant (tramp, 8)), quad1);
8433       emit_move_insn (gen_rtx_MEM (DImode, plus_constant (tramp, 16)), quad2);
8434       emit_insn (gen_ic_invalidate_line (tramp));
8435       return;
8436     }
8437   else if (TARGET_SHCOMPACT)
8438     {
8439       emit_insn (gen_initialize_trampoline (tramp, cxt, fnaddr));
8440       return;
8441     }
8442   emit_move_insn (gen_rtx_MEM (SImode, tramp),
8443                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0xd301d202 : 0xd202d301,
8444                                 SImode));
8445   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 4)),
8446                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0x0009422b : 0x422b0009,
8447                                 SImode));
8448   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 8)),
8449                   cxt);
8450   emit_move_insn (gen_rtx_MEM (SImode, plus_constant (tramp, 12)),
8451                   fnaddr);
8452   if (TARGET_HARVARD)
8453     {
8454       if (TARGET_USERMODE)
8455         emit_library_call (function_symbol ("__ic_invalidate"),
8456                            0, VOIDmode, 1, tramp, SImode);
8457       else
8458         emit_insn (gen_ic_invalidate_line (tramp));
8459     }
8460 }
8461
8462 /* FIXME: This is overly conservative.  A SHcompact function that
8463    receives arguments ``by reference'' will have them stored in its
8464    own stack frame, so it must not pass pointers or references to
8465    these arguments to other functions by means of sibling calls.  */
8466 static bool
8467 sh_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
8468 {
8469   return (decl 
8470           && (! TARGET_SHCOMPACT
8471               || current_function_args_info.stack_regs == 0)
8472           && ! sh_cfun_interrupt_handler_p ());
8473 }
8474 \f
8475 /* Machine specific built-in functions.  */
8476
8477 struct builtin_description
8478 {
8479   const enum insn_code icode;
8480   const char *const name;
8481   int signature;
8482 };
8483
8484 /* describe number and signedness of arguments; arg[0] == result
8485    (1: unsigned, 2: signed, 4: don't care, 8: pointer 0: no argument */
8486 static const char signature_args[][4] =
8487 {
8488 #define SH_BLTIN_V2SI2 0
8489   { 4, 4 },
8490 #define SH_BLTIN_V4HI2 1
8491   { 4, 4 },
8492 #define SH_BLTIN_V2SI3 2
8493   { 4, 4, 4 },
8494 #define SH_BLTIN_V4HI3 3
8495   { 4, 4, 4 },
8496 #define SH_BLTIN_V8QI3 4
8497   { 4, 4, 4 },
8498 #define SH_BLTIN_MAC_HISI 5
8499   { 1, 4, 4, 1 },
8500 #define SH_BLTIN_SH_HI 6
8501   { 4, 4, 1 },
8502 #define SH_BLTIN_SH_SI 7
8503   { 4, 4, 1 },
8504 #define SH_BLTIN_V4HI2V2SI 8
8505   { 4, 4, 4 },
8506 #define SH_BLTIN_V4HI2V8QI 9
8507   { 4, 4, 4 },
8508 #define SH_BLTIN_SISF 10
8509   { 4, 2 },
8510 #define SH_BLTIN_LDUA_L 11
8511   { 2, 8 },
8512 #define SH_BLTIN_LDUA_Q 12
8513   { 1, 8 },
8514 #define SH_BLTIN_STUA_L 13
8515   { 0, 8, 2 },
8516 #define SH_BLTIN_STUA_Q 14
8517   { 0, 8, 1 },
8518 #define SH_BLTIN_UDI 15
8519   { 0, 8, 1 },
8520 #define SH_BLTIN_NUM_SHARED_SIGNATURES 16
8521 #define SH_BLTIN_2 16
8522 #define SH_BLTIN_SU 16
8523   { 1, 2 },
8524 #define SH_BLTIN_3 17
8525 #define SH_BLTIN_SUS 17
8526   { 2, 2, 1 },
8527 #define SH_BLTIN_PSSV 18
8528   { 0, 8, 2, 2 },
8529 #define SH_BLTIN_XXUU 19
8530 #define SH_BLTIN_UUUU 19
8531   { 1, 1, 1, 1 },
8532 #define SH_BLTIN_PV 20
8533   { 0, 8 },
8534 };
8535 /* mcmv: operands considered unsigned.  */
8536 /* mmulsum_wq, msad_ubq: result considered unsigned long long.  */
8537 /* mperm: control value considered unsigned int.  */
8538 /* mshalds, mshard, mshards, mshlld, mshlrd: shift count is unsigned int.  */
8539 /* mshards_q: returns signed short.  */
8540 /* nsb: takes long long arg, returns unsigned char.  */
8541 static const struct builtin_description bdesc[] =
8542 {
8543   { CODE_FOR_absv2si2,  "__builtin_absv2si2", SH_BLTIN_V2SI2 },
8544   { CODE_FOR_absv4hi2,  "__builtin_absv4hi2", SH_BLTIN_V4HI2 },
8545   { CODE_FOR_addv2si3,  "__builtin_addv2si3", SH_BLTIN_V2SI3 },
8546   { CODE_FOR_addv4hi3,  "__builtin_addv4hi3", SH_BLTIN_V4HI3 },
8547   { CODE_FOR_ssaddv2si3,"__builtin_ssaddv2si3", SH_BLTIN_V2SI3 },
8548   { CODE_FOR_usaddv8qi3,"__builtin_usaddv8qi3", SH_BLTIN_V8QI3 },
8549   { CODE_FOR_ssaddv4hi3,"__builtin_ssaddv4hi3", SH_BLTIN_V4HI3 },
8550 #if 0
8551   { CODE_FOR_alloco32,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV },
8552   { CODE_FOR_alloco64,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV },
8553 #endif
8554   { CODE_FOR_negcmpeqv8qi,"__builtin_sh_media_MCMPEQ_B", SH_BLTIN_V8QI3 },
8555   { CODE_FOR_negcmpeqv2si,"__builtin_sh_media_MCMPEQ_L", SH_BLTIN_V2SI3 },
8556   { CODE_FOR_negcmpeqv4hi,"__builtin_sh_media_MCMPEQ_W", SH_BLTIN_V4HI3 },
8557   { CODE_FOR_negcmpgtuv8qi,"__builtin_sh_media_MCMPGT_UB", SH_BLTIN_V8QI3 },
8558   { CODE_FOR_negcmpgtv2si,"__builtin_sh_media_MCMPGT_L", SH_BLTIN_V2SI3 },
8559   { CODE_FOR_negcmpgtv4hi,"__builtin_sh_media_MCMPGT_W", SH_BLTIN_V4HI3 },
8560   { CODE_FOR_mcmv,      "__builtin_sh_media_MCMV", SH_BLTIN_UUUU },
8561   { CODE_FOR_mcnvs_lw,  "__builtin_sh_media_MCNVS_LW", SH_BLTIN_3 },
8562   { CODE_FOR_mcnvs_wb,  "__builtin_sh_media_MCNVS_WB", SH_BLTIN_V4HI2V8QI },
8563   { CODE_FOR_mcnvs_wub, "__builtin_sh_media_MCNVS_WUB", SH_BLTIN_V4HI2V8QI },
8564   { CODE_FOR_mextr1,    "__builtin_sh_media_MEXTR1", SH_BLTIN_UDI },
8565   { CODE_FOR_mextr2,    "__builtin_sh_media_MEXTR2", SH_BLTIN_UDI },
8566   { CODE_FOR_mextr3,    "__builtin_sh_media_MEXTR3", SH_BLTIN_UDI },
8567   { CODE_FOR_mextr4,    "__builtin_sh_media_MEXTR4", SH_BLTIN_UDI },
8568   { CODE_FOR_mextr5,    "__builtin_sh_media_MEXTR5", SH_BLTIN_UDI },
8569   { CODE_FOR_mextr6,    "__builtin_sh_media_MEXTR6", SH_BLTIN_UDI },
8570   { CODE_FOR_mextr7,    "__builtin_sh_media_MEXTR7", SH_BLTIN_UDI },
8571   { CODE_FOR_mmacfx_wl, "__builtin_sh_media_MMACFX_WL", SH_BLTIN_MAC_HISI },
8572   { CODE_FOR_mmacnfx_wl,"__builtin_sh_media_MMACNFX_WL", SH_BLTIN_MAC_HISI },
8573   { CODE_FOR_mulv2si3,  "__builtin_mulv2si3", SH_BLTIN_V2SI3, },
8574   { CODE_FOR_mulv4hi3,  "__builtin_mulv4hi3", SH_BLTIN_V4HI3 },
8575   { CODE_FOR_mmulfx_l,  "__builtin_sh_media_MMULFX_L", SH_BLTIN_V2SI3 },
8576   { CODE_FOR_mmulfx_w,  "__builtin_sh_media_MMULFX_W", SH_BLTIN_V4HI3 },
8577   { CODE_FOR_mmulfxrp_w,"__builtin_sh_media_MMULFXRP_W", SH_BLTIN_V4HI3 },
8578   { CODE_FOR_mmulhi_wl, "__builtin_sh_media_MMULHI_WL", SH_BLTIN_V4HI2V2SI },
8579   { CODE_FOR_mmullo_wl, "__builtin_sh_media_MMULLO_WL", SH_BLTIN_V4HI2V2SI },
8580   { CODE_FOR_mmulsum_wq,"__builtin_sh_media_MMULSUM_WQ", SH_BLTIN_XXUU },
8581   { CODE_FOR_mperm_w,   "__builtin_sh_media_MPERM_W", SH_BLTIN_SH_HI },
8582   { CODE_FOR_msad_ubq,  "__builtin_sh_media_MSAD_UBQ", SH_BLTIN_XXUU },
8583   { CODE_FOR_mshalds_l, "__builtin_sh_media_MSHALDS_L", SH_BLTIN_SH_SI },
8584   { CODE_FOR_mshalds_w, "__builtin_sh_media_MSHALDS_W", SH_BLTIN_SH_HI },
8585   { CODE_FOR_ashrv2si3, "__builtin_ashrv2si3", SH_BLTIN_SH_SI },
8586   { CODE_FOR_ashrv4hi3, "__builtin_ashrv4hi3", SH_BLTIN_SH_HI },
8587   { CODE_FOR_mshards_q, "__builtin_sh_media_MSHARDS_Q", SH_BLTIN_SUS },
8588   { CODE_FOR_mshfhi_b,  "__builtin_sh_media_MSHFHI_B", SH_BLTIN_V8QI3 },
8589   { CODE_FOR_mshfhi_l,  "__builtin_sh_media_MSHFHI_L", SH_BLTIN_V2SI3 },
8590   { CODE_FOR_mshfhi_w,  "__builtin_sh_media_MSHFHI_W", SH_BLTIN_V4HI3 },
8591   { CODE_FOR_mshflo_b,  "__builtin_sh_media_MSHFLO_B", SH_BLTIN_V8QI3 },
8592   { CODE_FOR_mshflo_l,  "__builtin_sh_media_MSHFLO_L", SH_BLTIN_V2SI3 },
8593   { CODE_FOR_mshflo_w,  "__builtin_sh_media_MSHFLO_W", SH_BLTIN_V4HI3 },
8594   { CODE_FOR_ashlv2si3, "__builtin_ashlv2si3", SH_BLTIN_SH_SI },
8595   { CODE_FOR_ashlv4hi3, "__builtin_ashlv4hi3", SH_BLTIN_SH_HI },
8596   { CODE_FOR_lshrv2si3, "__builtin_lshrv2si3", SH_BLTIN_SH_SI },
8597   { CODE_FOR_lshrv4hi3, "__builtin_lshrv4hi3", SH_BLTIN_SH_HI },
8598   { CODE_FOR_subv2si3,  "__builtin_subv2si3", SH_BLTIN_V2SI3 },
8599   { CODE_FOR_subv4hi3,  "__builtin_subv4hi3", SH_BLTIN_V4HI3 },
8600   { CODE_FOR_sssubv2si3,"__builtin_sssubv2si3", SH_BLTIN_V2SI3 },
8601   { CODE_FOR_ussubv8qi3,"__builtin_ussubv8qi3", SH_BLTIN_V8QI3 },
8602   { CODE_FOR_sssubv4hi3,"__builtin_sssubv4hi3", SH_BLTIN_V4HI3 },
8603   { CODE_FOR_fcosa_s,   "__builtin_sh_media_FCOSA_S", SH_BLTIN_SISF },
8604   { CODE_FOR_fsina_s,   "__builtin_sh_media_FSINA_S", SH_BLTIN_SISF },
8605   { CODE_FOR_fipr,      "__builtin_sh_media_FIPR_S", SH_BLTIN_3 },
8606   { CODE_FOR_ftrv,      "__builtin_sh_media_FTRV_S", SH_BLTIN_3 },
8607   { CODE_FOR_fsrra_s,   "__builtin_sh_media_FSRRA_S", SH_BLTIN_2 },
8608 #if 0
8609   { CODE_FOR_ldhi_l,    "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L },
8610   { CODE_FOR_ldhi_q,    "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q },
8611   { CODE_FOR_ldlo_l,    "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L },
8612   { CODE_FOR_ldlo_q,    "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q },
8613   { CODE_FOR_sthi_l,    "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L },
8614   { CODE_FOR_sthi_q,    "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q },
8615   { CODE_FOR_stlo_l,    "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L },
8616   { CODE_FOR_stlo_q,    "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q },
8617   { CODE_FOR_ldhi_l64,  "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L },
8618   { CODE_FOR_ldhi_q64,  "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q },
8619   { CODE_FOR_ldlo_l64,  "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L },
8620   { CODE_FOR_ldlo_q64,  "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q },
8621   { CODE_FOR_sthi_l64,  "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L },
8622   { CODE_FOR_sthi_q64,  "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q },
8623   { CODE_FOR_stlo_l64,  "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L },
8624   { CODE_FOR_stlo_q64,  "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q },
8625 #endif
8626   { CODE_FOR_nsb,       "__builtin_sh_media_NSB", SH_BLTIN_SU },
8627   { CODE_FOR_byterev,   "__builtin_sh_media_BYTEREV", SH_BLTIN_2 },
8628 #if 0
8629   { CODE_FOR_prefetch32,"__builtin_sh_media_PREFO", SH_BLTIN_PSSV },
8630   { CODE_FOR_prefetch64,"__builtin_sh_media_PREFO", SH_BLTIN_PSSV }
8631 #endif
8632 };
8633
8634 static void
8635 sh_media_init_builtins (void)
8636 {
8637   tree shared[SH_BLTIN_NUM_SHARED_SIGNATURES];
8638   const struct builtin_description *d;
8639
8640   memset (shared, 0, sizeof shared);
8641   for (d = bdesc; d - bdesc < (int) ARRAY_SIZE (bdesc); d++)
8642     {
8643       tree type, arg_type;
8644       int signature = d->signature;
8645       int i;
8646
8647       if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES && shared[signature])
8648         type = shared[signature];
8649       else
8650         {
8651           int has_result = signature_args[signature][0] != 0;
8652
8653           if (signature_args[signature][1] == 8
8654               && (insn_data[d->icode].operand[has_result].mode != Pmode))
8655             continue;
8656           if (! TARGET_FPU_ANY
8657               && FLOAT_MODE_P (insn_data[d->icode].operand[0].mode))
8658             continue;
8659           type = void_list_node;
8660           for (i = 3; ; i--)
8661             {
8662               int arg = signature_args[signature][i];
8663               int opno = i - 1 + has_result;
8664
8665               if (arg == 8)
8666                 arg_type = ptr_type_node;
8667               else if (arg)
8668                 arg_type = ((*lang_hooks.types.type_for_mode)
8669                             (insn_data[d->icode].operand[opno].mode,
8670                              (arg & 1)));
8671               else if (i)
8672                 continue;
8673               else
8674                 arg_type = void_type_node;
8675               if (i == 0)
8676                 break;
8677               type = tree_cons (NULL_TREE, arg_type, type);
8678             }
8679           type = build_function_type (arg_type, type);
8680           if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES)
8681             shared[signature] = type;
8682         }
8683       builtin_function (d->name, type, d - bdesc, BUILT_IN_MD,
8684                         NULL, NULL_TREE);
8685     }
8686 }
8687
8688 static void
8689 sh_init_builtins (void)
8690 {
8691   if (TARGET_SHMEDIA)
8692     sh_media_init_builtins ();
8693 }
8694
8695 /* Expand an expression EXP that calls a built-in function,
8696    with result going to TARGET if that's convenient
8697    (and in mode MODE if that's convenient).
8698    SUBTARGET may be used as the target for computing one of EXP's operands.
8699    IGNORE is nonzero if the value is to be ignored.  */
8700
8701 static rtx
8702 sh_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
8703                    enum machine_mode mode ATTRIBUTE_UNUSED, int ignore)
8704 {
8705   tree fndecl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
8706   tree arglist = TREE_OPERAND (exp, 1);
8707   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
8708   const struct builtin_description *d = &bdesc[fcode];
8709   enum insn_code icode = d->icode;
8710   int signature = d->signature;
8711   enum machine_mode tmode = VOIDmode;
8712   int nop = 0, i;
8713   rtx op[4];
8714   rtx pat;
8715
8716   if (signature_args[signature][0])
8717     {
8718       if (ignore)
8719         return 0;
8720
8721       tmode = insn_data[icode].operand[0].mode;
8722       if (! target
8723           || GET_MODE (target) != tmode
8724           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
8725         target = gen_reg_rtx (tmode);
8726       op[nop++] = target;
8727     }
8728   else
8729     target = 0;
8730
8731   for (i = 1; i <= 3; i++, nop++)
8732     {
8733       tree arg;
8734       enum machine_mode opmode, argmode;
8735
8736       if (! signature_args[signature][i])
8737         break;
8738       arg = TREE_VALUE (arglist);
8739       if (arg == error_mark_node)
8740         return const0_rtx;
8741       arglist = TREE_CHAIN (arglist);
8742       opmode = insn_data[icode].operand[nop].mode;
8743       argmode = TYPE_MODE (TREE_TYPE (arg));
8744       if (argmode != opmode)
8745         arg = build1 (NOP_EXPR,
8746                       (*lang_hooks.types.type_for_mode) (opmode, 0), arg);
8747       op[nop] = expand_expr (arg, NULL_RTX, opmode, 0);
8748       if (! (*insn_data[icode].operand[nop].predicate) (op[nop], opmode))
8749         op[nop] = copy_to_mode_reg (opmode, op[nop]);
8750     }
8751
8752   switch (nop)
8753     {
8754     case 1:
8755       pat = (*insn_data[d->icode].genfun) (op[0]);
8756       break;
8757     case 2:
8758       pat = (*insn_data[d->icode].genfun) (op[0], op[1]);
8759       break;
8760     case 3:
8761       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2]);
8762       break;
8763     case 4:
8764       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2], op[3]);
8765       break;
8766     default:
8767       abort ();
8768     }
8769   if (! pat)
8770     return 0;
8771   emit_insn (pat);
8772   return target;
8773 }
8774
8775 void
8776 sh_expand_unop_v2sf (enum rtx_code code, rtx op0, rtx op1)
8777 {
8778   rtx sel0 = const0_rtx;
8779   rtx sel1 = const1_rtx;
8780   rtx (*fn) (rtx, rtx, rtx, rtx, rtx) = gen_unary_sf_op;
8781   rtx op = gen_rtx_fmt_e (code, SFmode, op1);
8782
8783   emit_insn ((*fn) (op0, op1, op, sel0, sel0));
8784   emit_insn ((*fn) (op0, op1, op, sel1, sel1));
8785 }
8786
8787 void
8788 sh_expand_binop_v2sf (enum rtx_code code, rtx op0, rtx op1, rtx op2)
8789 {
8790   rtx sel0 = const0_rtx;
8791   rtx sel1 = const1_rtx;
8792   rtx (*fn) (rtx, rtx, rtx, rtx, rtx, rtx, rtx, rtx)
8793     = gen_binary_sf_op;
8794   rtx op = gen_rtx_fmt_ee (code, SFmode, op1, op2);
8795
8796   emit_insn ((*fn) (op0, op1, op2, op, sel0, sel0, sel0, sel1));
8797   emit_insn ((*fn) (op0, op1, op2, op, sel1, sel1, sel1, sel0));
8798 }
8799
8800 /* Return the class of registers for which a mode change from FROM to TO
8801    is invalid.  */
8802 bool
8803 sh_cannot_change_mode_class (enum machine_mode from, enum machine_mode to,
8804                              enum reg_class class)
8805 {
8806   if (GET_MODE_SIZE (from) != GET_MODE_SIZE (to))
8807     {
8808        if (TARGET_LITTLE_ENDIAN)
8809          {
8810            if (GET_MODE_SIZE (to) < 8 || GET_MODE_SIZE (from) < 8)
8811              return reg_classes_intersect_p (DF_REGS, class);
8812          }
8813        else
8814          {
8815            if (GET_MODE_SIZE (from) < 8)
8816              return reg_classes_intersect_p (DF_HI_REGS, class);
8817          }
8818     }
8819   return 0;
8820 }
8821
8822
8823 /* If ADDRESS refers to a CODE_LABEL, add NUSES to the number of times
8824    that label is used.  */
8825
8826 void
8827 sh_mark_label (rtx address, int nuses)
8828 {
8829   if (GOTOFF_P (address))
8830     {
8831       /* Extract the label or symbol.  */
8832       address = XEXP (address, 0);
8833       if (GET_CODE (address) == PLUS)
8834         address = XEXP (address, 0);
8835       address = XVECEXP (address, 0, 0);
8836     }
8837   if (GET_CODE (address) == LABEL_REF
8838       && GET_CODE (XEXP (address, 0)) == CODE_LABEL)
8839     LABEL_NUSES (XEXP (address, 0)) += nuses;
8840 }
8841
8842 /* Compute extra cost of moving data between one register class
8843    and another.  */
8844
8845 /* If SECONDARY*_RELOAD_CLASS says something about the src/dst pair, regclass
8846    uses this information.  Hence, the general register <-> floating point
8847    register information here is not used for SFmode.  */
8848
8849 int
8850 sh_register_move_cost (enum machine_mode mode,
8851                        enum reg_class srcclass, enum reg_class dstclass)
8852 {
8853   if (dstclass == T_REGS || dstclass == PR_REGS)
8854     return 10;
8855
8856   if (dstclass == MAC_REGS && srcclass == MAC_REGS)
8857     return 4;
8858
8859   if (mode == SImode && ! TARGET_SHMEDIA && TARGET_FMOVD
8860       && REGCLASS_HAS_FP_REG (srcclass)
8861       && REGCLASS_HAS_FP_REG (dstclass))
8862     return 4;
8863
8864   if ((REGCLASS_HAS_FP_REG (dstclass) && srcclass == MAC_REGS)
8865       || (dstclass== MAC_REGS && REGCLASS_HAS_FP_REG (srcclass)))
8866     return 9;
8867
8868   if ((REGCLASS_HAS_FP_REG (dstclass)
8869        && REGCLASS_HAS_GENERAL_REG (srcclass))
8870       || (REGCLASS_HAS_GENERAL_REG (dstclass)
8871           && REGCLASS_HAS_FP_REG (srcclass)))
8872    return ((TARGET_SHMEDIA ? 4 : TARGET_FMOVD ? 8 : 12)
8873            * ((GET_MODE_SIZE (mode) + 7) / 8U));
8874
8875   if ((dstclass == FPUL_REGS
8876        && REGCLASS_HAS_GENERAL_REG (srcclass))
8877       || (srcclass == FPUL_REGS
8878           && REGCLASS_HAS_GENERAL_REG (dstclass)))
8879     return 5;
8880
8881   if ((dstclass == FPUL_REGS
8882        && (srcclass == PR_REGS || srcclass == MAC_REGS || srcclass == T_REGS))
8883       || (srcclass == FPUL_REGS         
8884           && (dstclass == PR_REGS || dstclass == MAC_REGS)))
8885     return 7;
8886
8887   if ((srcclass == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
8888       || ((dstclass) == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
8889     return 20;
8890
8891   if ((srcclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
8892       || (dstclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
8893   return 4;
8894
8895   if (TARGET_SHMEDIA
8896       || (TARGET_FMOVD
8897           && ! REGCLASS_HAS_GENERAL_REG (srcclass)
8898           && ! REGCLASS_HAS_GENERAL_REG (dstclass)))
8899     return 2 * ((GET_MODE_SIZE (mode) + 7) / 8U);
8900
8901   return 2 * ((GET_MODE_SIZE (mode) + 3) / 4U);
8902 }
8903
8904 /* Like register_operand, but take into account that SHMEDIA can use
8905    the constant zero like a general register.  */
8906 int
8907 sh_register_operand (rtx op, enum machine_mode mode)
8908 {
8909   if (op == CONST0_RTX (mode) && TARGET_SHMEDIA)
8910     return 1;
8911   return register_operand (op, mode);
8912 }
8913
8914 int
8915 cmpsi_operand (rtx op, enum machine_mode mode)
8916 {
8917   if (GET_CODE (op) == REG && REGNO (op) == T_REG
8918       && GET_MODE (op) == SImode)
8919     return 1;
8920   return arith_operand (op, mode);
8921 }
8922
8923 static rtx emit_load_ptr (rtx, rtx);
8924
8925 static rtx
8926 emit_load_ptr (rtx reg, rtx addr)
8927 {
8928   rtx mem = gen_rtx_MEM (ptr_mode, addr);
8929
8930   if (Pmode != ptr_mode)
8931     mem = gen_rtx_SIGN_EXTEND (Pmode, mem);
8932   return emit_move_insn (reg, mem);
8933 }
8934
8935 void
8936 sh_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
8937                     HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
8938                     tree function)
8939 {
8940   CUMULATIVE_ARGS cum;
8941   int structure_value_byref = 0;
8942   rtx this, this_value, sibcall, insns, funexp;
8943   tree funtype = TREE_TYPE (function);
8944   int simple_add = CONST_OK_FOR_ADD (delta);
8945   int did_load = 0;
8946   rtx scratch0, scratch1, scratch2;
8947
8948   reload_completed = 1;
8949   epilogue_completed = 1;
8950   no_new_pseudos = 1;
8951   current_function_uses_only_leaf_regs = 1;
8952
8953   emit_note (NOTE_INSN_PROLOGUE_END);
8954
8955   /* Find the "this" pointer.  We have such a wide range of ABIs for the
8956      SH that it's best to do this completely machine independently.
8957      "this" is passed as first argument, unless a structure return pointer 
8958      comes first, in which case "this" comes second.  */
8959   INIT_CUMULATIVE_ARGS (cum, funtype, NULL_RTX, 0);
8960 #ifndef PCC_STATIC_STRUCT_RETURN
8961   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
8962     structure_value_byref = 1;
8963 #endif /* not PCC_STATIC_STRUCT_RETURN */
8964   if (structure_value_byref && sh_struct_value_rtx (function, 0) == 0)
8965     { 
8966       tree ptype = build_pointer_type (TREE_TYPE (funtype));
8967
8968       FUNCTION_ARG_ADVANCE (cum, Pmode, ptype, 1);
8969     }
8970   this = FUNCTION_ARG (cum, Pmode, ptr_type_node, 1);
8971
8972   /* For SHcompact, we only have r0 for a scratch register: r1 is the
8973      static chain pointer (even if you can't have nested virtual functions
8974      right now, someone might implement them sometime), and the rest of the
8975      registers are used for argument passing, are callee-saved, or reserved.  */
8976   scratch0 = scratch1 = scratch2 = gen_rtx_REG (Pmode, 0);
8977   if (! TARGET_SH5)
8978     {
8979       scratch1 = gen_rtx_REG (ptr_mode, 1);
8980       /* N.B., if not TARGET_HITACHI, register 2 is used to pass the pointer
8981          pointing where to return struct values.  */
8982       scratch2 = gen_rtx_REG (Pmode, 3);
8983     }
8984   else if (TARGET_SHMEDIA)
8985     {
8986       scratch1 = gen_rtx_REG (ptr_mode, 21);
8987       scratch2 = gen_rtx_REG (Pmode, TR0_REG);
8988     }
8989
8990   this_value = plus_constant (this, delta);
8991   if (vcall_offset
8992       && (simple_add || scratch0 != scratch1)
8993       && strict_memory_address_p (ptr_mode, this_value))
8994     {
8995       emit_load_ptr (scratch0, this_value);
8996       did_load = 1;
8997     }
8998
8999   if (!delta)
9000     ; /* Do nothing.  */
9001   else if (simple_add)
9002     emit_move_insn (this, this_value);
9003   else
9004     {
9005       emit_move_insn (scratch1, GEN_INT (delta));
9006       emit_insn (gen_add2_insn (this, scratch1));
9007     }
9008
9009   if (vcall_offset)
9010     {
9011       rtx offset_addr;
9012
9013       if (!did_load)
9014         emit_load_ptr (scratch0, this);
9015
9016       offset_addr = plus_constant (scratch0, vcall_offset);
9017       if (strict_memory_address_p (ptr_mode, offset_addr))
9018         ; /* Do nothing.  */
9019       else if (! TARGET_SH5)
9020         {
9021           /* scratch0 != scratch1, and we have indexed loads.  Get better
9022              schedule by loading the offset into r1 and using an indexed
9023              load - then the load of r1 can issue before the load from
9024              (this + delta) finishes.  */
9025           emit_move_insn (scratch1, GEN_INT (vcall_offset));
9026           offset_addr = gen_rtx_PLUS (Pmode, scratch0, scratch1);
9027         }
9028       else if (CONST_OK_FOR_ADD (vcall_offset))
9029         {
9030           emit_insn (gen_add2_insn (scratch0, GEN_INT (vcall_offset)));
9031           offset_addr = scratch0;
9032         }
9033       else if (scratch0 != scratch1)
9034         {
9035           emit_move_insn (scratch1, GEN_INT (vcall_offset));
9036           emit_insn (gen_add2_insn (scratch0, scratch1));
9037           offset_addr = scratch0;
9038         }
9039       else
9040         abort (); /* FIXME */
9041       emit_load_ptr (scratch0, offset_addr);
9042
9043      if (Pmode != ptr_mode)
9044         scratch0 = gen_rtx_TRUNCATE (ptr_mode, scratch0);
9045       emit_insn (gen_add2_insn (this, scratch0));
9046     }
9047
9048   /* Generate a tail call to the target function.  */
9049   if (! TREE_USED (function))
9050     {
9051       assemble_external (function);
9052       TREE_USED (function) = 1;
9053     }
9054   funexp = XEXP (DECL_RTL (function), 0);
9055   emit_move_insn (scratch2, funexp);
9056   funexp = gen_rtx_MEM (FUNCTION_MODE, scratch2);
9057   sibcall = emit_call_insn (gen_sibcall (funexp, const0_rtx, NULL_RTX));
9058   SIBLING_CALL_P (sibcall) = 1;
9059   use_reg (&CALL_INSN_FUNCTION_USAGE (sibcall), this);
9060   emit_barrier ();
9061
9062   /* Run just enough of rest_of_compilation to do scheduling and get
9063      the insns emitted.  Note that use_thunk calls
9064      assemble_start_function and assemble_end_function.  */
9065
9066   insn_locators_initialize ();
9067   insns = get_insns ();
9068
9069   if (optimize > 0 && flag_schedule_insns_after_reload)
9070     {
9071
9072       find_basic_blocks (insns, max_reg_num (), rtl_dump_file);
9073       life_analysis (insns, rtl_dump_file, PROP_FINAL);
9074
9075       split_all_insns (1);
9076
9077       schedule_insns (rtl_dump_file);
9078     }
9079
9080   sh_reorg ();
9081
9082   if (optimize > 0 && flag_delayed_branch)
9083       dbr_schedule (insns, rtl_dump_file);
9084   shorten_branches (insns);
9085   final_start_function (insns, file, 1);
9086   final (insns, file, 1, 0);
9087   final_end_function ();
9088
9089   if (optimize > 0 && flag_schedule_insns_after_reload)
9090     {
9091       /* Release all memory allocated by flow.  */
9092       free_basic_block_vars (0);
9093
9094       /* Release all memory held by regsets now.  */
9095       regset_release_memory ();
9096     }
9097
9098   reload_completed = 0;
9099   epilogue_completed = 0;
9100   no_new_pseudos = 0;
9101 }
9102
9103 rtx
9104 function_symbol (const char *name)
9105 {
9106   rtx sym = gen_rtx_SYMBOL_REF (Pmode, name);
9107   SYMBOL_REF_FLAGS (sym) = SYMBOL_FLAG_FUNCTION;
9108   return sym;
9109 }
9110
9111 /* Find the number of a general purpose register in S.  */
9112 static int
9113 scavenge_reg (HARD_REG_SET *s)
9114 {
9115   int r;
9116   for (r = FIRST_GENERAL_REG; r <= LAST_GENERAL_REG; r++)
9117     if (TEST_HARD_REG_BIT (*s, r))
9118       return r;
9119   return -1;
9120 }
9121
9122 rtx
9123 sh_get_pr_initial_val (void)
9124 {
9125   rtx val;
9126
9127   /* ??? Unfortunately, get_hard_reg_initial_val doesn't always work for the
9128      PR register on SHcompact, because it might be clobbered by the prologue.
9129      We check first if that is known to be the case.  */
9130   if (TARGET_SHCOMPACT
9131       && ((current_function_args_info.call_cookie
9132            & ~ CALL_COOKIE_RET_TRAMP (1))
9133           || current_function_has_nonlocal_label))
9134     return gen_rtx_MEM (SImode, return_address_pointer_rtx);
9135
9136   /* If we haven't finished rtl generation, there might be a nonlocal label
9137      that we haven't seen yet.
9138      ??? get_hard_reg_initial_val fails if it is called while no_new_pseudos
9139      is set, unless it has been called before for the same register.  And even
9140      then, we end in trouble if we didn't use the register in the same
9141      basic block before.  So call get_hard_reg_initial_val now and wrap it
9142      in an unspec if we might need to replace it.  */
9143   /* ??? We also must do this for TARGET_SH1 in general, because otherwise
9144      combine can put the pseudo returned by get_hard_reg_initial_val into
9145      instructions that need a general purpose registers, which will fail to
9146      be recognized when the pseudo becomes allocated to PR.  */
9147   val
9148     = get_hard_reg_initial_val (Pmode, TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
9149   if (TARGET_SH1)
9150     return gen_rtx_UNSPEC (SImode, gen_rtvec (1, val), UNSPEC_RA);
9151   return val;
9152 }
9153
9154 int
9155 sh_expand_t_scc (enum rtx_code code, rtx target)
9156 {
9157   rtx result = target;
9158   HOST_WIDE_INT val;
9159
9160   if (GET_CODE (sh_compare_op0) != REG || REGNO (sh_compare_op0) != T_REG
9161       || GET_CODE (sh_compare_op1) != CONST_INT)
9162     return 0;
9163   if (GET_CODE (result) != REG)
9164     result = gen_reg_rtx (SImode);
9165   val = INTVAL (sh_compare_op1);
9166   if ((code == EQ && val == 1) || (code == NE && val == 0))
9167     emit_insn (gen_movt (result));
9168   else if ((code == EQ && val == 0) || (code == NE && val == 1))
9169     {
9170       emit_insn (gen_rtx_CLOBBER (VOIDmode, result));
9171       emit_insn (gen_subc (result, result, result));
9172       emit_insn (gen_addsi3 (result, result, GEN_INT (1)));
9173     }
9174   else if (code == EQ || code == NE)
9175     emit_insn (gen_move_insn (result, GEN_INT (code == NE)));
9176   else
9177     return 0;
9178   if (result != target)
9179     emit_move_insn (target, result);
9180   return 1;
9181 }
9182
9183 /* INSN is an sfunc; return the rtx that describes the address used.  */
9184 static rtx
9185 extract_sfunc_addr (rtx insn)
9186 {
9187   rtx pattern, part = NULL_RTX;
9188   int len, i;
9189
9190   pattern = PATTERN (insn);
9191   len = XVECLEN (pattern, 0);
9192   for (i = 0; i < len; i++)
9193     {
9194       part = XVECEXP (pattern, 0, i);
9195       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == Pmode
9196           && GENERAL_REGISTER_P (true_regnum (XEXP (part, 0))))
9197         return XEXP (part, 0);
9198     }
9199   if (GET_CODE (XVECEXP (pattern, 0, 0)) == UNSPEC_VOLATILE)
9200     return XVECEXP (XVECEXP (pattern, 0, 0), 0, 1);
9201   abort ();
9202 }
9203
9204 /* Verify that the register in use_sfunc_addr still agrees with the address
9205    used in the sfunc.  This prevents fill_slots_from_thread from changing
9206    use_sfunc_addr.
9207    INSN is the use_sfunc_addr instruction, and REG is the register it
9208    guards.  */
9209 int
9210 check_use_sfunc_addr (rtx insn, rtx reg)
9211 {
9212   /* Search for the sfunc.  It should really come right after INSN.  */
9213   while ((insn = NEXT_INSN (insn)))
9214     {
9215       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
9216         break;
9217       if (! INSN_P (insn))
9218         continue;
9219         
9220       if (GET_CODE (PATTERN (insn)) == SEQUENCE)
9221         insn = XVECEXP (PATTERN (insn), 0, 0);
9222       if (GET_CODE (PATTERN (insn)) != PARALLEL
9223           || get_attr_type (insn) != TYPE_SFUNC)
9224         continue;
9225       return rtx_equal_p (extract_sfunc_addr (insn), reg);
9226     }
9227   abort ();
9228 }
9229
9230 #include "gt-sh.h"