OSDN Git Service

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