OSDN Git Service

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