OSDN Git Service

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