remove unused files
[platform/upstream/gcc48.git] / gcc / config / sh / sh.c
1 /* Output routines for GCC for Renesas / SuperH SH.
2    Copyright (C) 1993-2013 Free Software Foundation, Inc.
3    Contributed by Steve Chamberlain (sac@cygnus.com).
4    Improved by Jim Wilson (wilson@cygnus.com).
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* FIXME: This is a temporary hack, so that we can include <algorithm>
23    below.  <algorithm> will try to include <cstdlib> which will reference
24    malloc & co, which are poisoned by "system.h".  The proper solution is
25    to include <cstdlib> in "system.h" instead of <stdlib.h>.  */
26 #include <cstdlib>
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "insn-config.h"
33 #include "rtl.h"
34 #include "tree.h"
35 #include "flags.h"
36 #include "expr.h"
37 #include "optabs.h"
38 #include "reload.h"
39 #include "function.h"
40 #include "regs.h"
41 #include "hard-reg-set.h"
42 #include "output.h"
43 #include "insn-attr.h"
44 #include "diagnostic-core.h"
45 #include "recog.h"
46 #include "dwarf2.h"
47 #include "tm_p.h"
48 #include "target.h"
49 #include "target-def.h"
50 #include "langhooks.h"
51 #include "basic-block.h"
52 #include "df.h"
53 #include "intl.h"
54 #include "sched-int.h"
55 #include "params.h"
56 #include "ggc.h"
57 #include "gimple.h"
58 #include "cfgloop.h"
59 #include "alloc-pool.h"
60 #include "tm-constrs.h"
61 #include "opts.h"
62
63 #include <sstream>
64 #include <vector>
65 #include <algorithm>
66
67 int code_for_indirect_jump_scratch = CODE_FOR_indirect_jump_scratch;
68
69 #define MSW (TARGET_LITTLE_ENDIAN ? 1 : 0)
70 #define LSW (TARGET_LITTLE_ENDIAN ? 0 : 1)
71
72 /* These are some macros to abstract register modes.  */
73 #define CONST_OK_FOR_I10(VALUE) (((HOST_WIDE_INT)(VALUE)) >= -512 \
74                                  && ((HOST_WIDE_INT)(VALUE)) <= 511)
75
76 #define CONST_OK_FOR_ADD(size) \
77   (TARGET_SHMEDIA ? CONST_OK_FOR_I10 (size) : CONST_OK_FOR_I08 (size))
78 #define GEN_MOV (*(TARGET_SHMEDIA64 ? gen_movdi : gen_movsi))
79 #define GEN_ADD3 (*(TARGET_SHMEDIA64 ? gen_adddi3 : gen_addsi3))
80 #define GEN_SUB3 (*(TARGET_SHMEDIA64 ? gen_subdi3 : gen_subsi3))
81
82 /* Used to simplify the logic below.  Find the attributes wherever
83    they may be.  */
84 #define SH_ATTRIBUTES(decl) \
85   (TYPE_P (decl)) ? TYPE_ATTRIBUTES (decl) \
86                   : DECL_ATTRIBUTES (decl) \
87                   ? (DECL_ATTRIBUTES (decl)) \
88                   : TYPE_ATTRIBUTES (TREE_TYPE (decl))
89
90 /* Set to 1 by expand_prologue() when the function is an interrupt handler.  */
91 int current_function_interrupt;
92
93 tree sh_deferred_function_attributes;
94 tree *sh_deferred_function_attributes_tail = &sh_deferred_function_attributes;
95
96 /* Global variables for machine-dependent things.  */
97
98 /* Which cpu are we scheduling for.  */
99 enum processor_type sh_cpu;
100
101 /* Definitions used in ready queue reordering for first scheduling pass.  */
102
103 /* Reg weights arrays for modes SFmode and SImode, indexed by insn LUID.  */
104 static short *regmode_weight[2];
105
106 /* Total SFmode and SImode weights of scheduled insns.  */
107 static int curr_regmode_pressure[2];
108
109 /* Number of r0 life regions.  */
110 static int r0_life_regions;
111
112 /* If true, skip cycles for Q -> R movement.  */
113 static int skip_cycles = 0;
114
115 /* Cached value of can_issue_more.  This is cached in sh_variable_issue hook
116    and returned from sh_reorder2.  */
117 static short cached_can_issue_more;
118
119 /* Unique number for UNSPEC_BBR pattern.  */
120 static unsigned int unspec_bbr_uid = 1;
121
122 /* Provides the class number of the smallest class containing
123    reg number.  */
124 enum reg_class regno_reg_class[FIRST_PSEUDO_REGISTER] =
125 {
126   R0_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   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
136   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
137   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
138   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
139   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
140   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
141   GENERAL_REGS, GENERAL_REGS, GENERAL_REGS, GENERAL_REGS,
142   FP0_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   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
152   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
153   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
154   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
155   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
156   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
157   FP_REGS, FP_REGS, FP_REGS, FP_REGS,
158   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
159   TARGET_REGS, TARGET_REGS, TARGET_REGS, TARGET_REGS,
160   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
161   DF_REGS, DF_REGS, DF_REGS, DF_REGS,
162   NO_REGS, GENERAL_REGS, PR_REGS, T_REGS,
163   MAC_REGS, MAC_REGS, FPUL_REGS, FPSCR_REGS,
164   GENERAL_REGS, GENERAL_REGS,
165 };
166
167 char sh_register_names[FIRST_PSEUDO_REGISTER] \
168   [MAX_REGISTER_NAME_LENGTH + 1] = SH_REGISTER_NAMES_INITIALIZER;
169
170 char sh_additional_register_names[ADDREGNAMES_SIZE] \
171   [MAX_ADDITIONAL_REGISTER_NAME_LENGTH + 1]
172   = SH_ADDITIONAL_REGISTER_NAMES_INITIALIZER;
173
174 int assembler_dialect;
175
176 static bool shmedia_space_reserved_for_target_registers;
177
178 static void split_branches (rtx);
179 static int branch_dest (rtx);
180 static void force_into (rtx, rtx);
181 static void print_slot (rtx);
182 static rtx add_constant (rtx, enum machine_mode, rtx);
183 static void dump_table (rtx, rtx);
184 static bool broken_move (rtx);
185 static bool mova_p (rtx);
186 static rtx find_barrier (int, rtx, rtx);
187 static bool noncall_uses_reg (rtx, rtx, rtx *);
188 static rtx gen_block_redirect (rtx, int, int);
189 static void sh_reorg (void);
190 static void sh_option_override (void);
191 static void output_stack_adjust (int, rtx, int, HARD_REG_SET *, bool);
192 static rtx frame_insn (rtx);
193 static rtx push (int);
194 static void pop (int);
195 static void push_regs (HARD_REG_SET *, int);
196 static int calc_live_regs (HARD_REG_SET *);
197 static HOST_WIDE_INT rounded_frame_size (int);
198 static bool sh_frame_pointer_required (void);
199 static rtx mark_constant_pool_use (rtx);
200 static tree sh_handle_interrupt_handler_attribute (tree *, tree, tree,
201                                                    int, bool *);
202 static tree sh_handle_resbank_handler_attribute (tree *, tree,
203                                                  tree, int, bool *);
204 static tree sh2a_handle_function_vector_handler_attribute (tree *, tree,
205                                                            tree, int, bool *);
206 static tree sh_handle_sp_switch_attribute (tree *, tree, tree, int, bool *);
207 static tree sh_handle_trap_exit_attribute (tree *, tree, tree, int, bool *);
208 static tree sh_handle_renesas_attribute (tree *, tree, tree, int, bool *);
209 static void sh_print_operand (FILE *, rtx, int);
210 static void sh_print_operand_address (FILE *, rtx);
211 static bool sh_print_operand_punct_valid_p (unsigned char code);
212 static bool sh_asm_output_addr_const_extra (FILE *file, rtx x);
213 static void sh_output_function_epilogue (FILE *, HOST_WIDE_INT);
214 static void sh_insert_attributes (tree, tree *);
215 static const char *sh_check_pch_target_flags (int);
216 static int sh_register_move_cost (enum machine_mode, reg_class_t, reg_class_t);
217 static int sh_adjust_cost (rtx, rtx, rtx, int);
218 static int sh_issue_rate (void);
219 static int sh_dfa_new_cycle (FILE *, int, rtx, int, int, int *sort_p);
220 static short find_set_regmode_weight (rtx, enum machine_mode);
221 static short find_insn_regmode_weight (rtx, enum machine_mode);
222 static void find_regmode_weight (basic_block, enum machine_mode);
223 static int find_r0_life_regions (basic_block);
224 static void  sh_md_init_global (FILE *, int, int);
225 static void  sh_md_finish_global (FILE *, int);
226 static int rank_for_reorder (const void *, const void *);
227 static void swap_reorder (rtx *, int);
228 static void ready_reorder (rtx *, int);
229 static bool high_pressure (enum machine_mode);
230 static int sh_reorder (FILE *, int, rtx *, int *, int);
231 static int sh_reorder2 (FILE *, int, rtx *, int *, int);
232 static void sh_md_init (FILE *, int, int);
233 static int sh_variable_issue (FILE *, int, rtx, int);
234
235 static bool sh_function_ok_for_sibcall (tree, tree);
236
237 static bool sh_cannot_modify_jumps_p (void);
238 static reg_class_t sh_target_reg_class (void);
239 static bool sh_optimize_target_register_callee_saved (bool);
240 static bool sh_ms_bitfield_layout_p (const_tree);
241
242 static void sh_init_builtins (void);
243 static tree sh_builtin_decl (unsigned, bool);
244 static rtx sh_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
245 static void sh_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
246                                 HOST_WIDE_INT, tree);
247 static void sh_file_start (void);
248 static bool flow_dependent_p (rtx, rtx);
249 static void flow_dependent_p_1 (rtx, const_rtx, void *);
250 static int shiftcosts (rtx);
251 static int and_xor_ior_costs (rtx, int);
252 static int addsubcosts (rtx);
253 static int multcosts (rtx);
254 static bool unspec_caller_rtx_p (rtx);
255 static bool sh_cannot_copy_insn_p (rtx);
256 static bool sh_rtx_costs (rtx, int, int, int, int *, bool);
257 static int sh_address_cost (rtx, enum machine_mode, addr_space_t, bool);
258 static int sh_pr_n_sets (void);
259 static rtx sh_allocate_initial_value (rtx);
260 static reg_class_t sh_preferred_reload_class (rtx, reg_class_t);
261 static reg_class_t sh_secondary_reload (bool, rtx, reg_class_t,
262                                         enum machine_mode,
263                                         struct secondary_reload_info *);
264 static bool sh_legitimate_address_p (enum machine_mode, rtx, bool);
265 static rtx sh_legitimize_address (rtx, rtx, enum machine_mode);
266 static rtx sh_delegitimize_address (rtx);
267 static int shmedia_target_regs_stack_space (HARD_REG_SET *);
268 static int shmedia_reserve_space_for_target_registers_p (int, HARD_REG_SET *);
269 static int shmedia_target_regs_stack_adjust (HARD_REG_SET *);
270 static int scavenge_reg (HARD_REG_SET *s);
271 struct save_schedule_s;
272 static struct save_entry_s *sh5_schedule_saves (HARD_REG_SET *,
273                                                 struct save_schedule_s *, int);
274
275 static rtx sh_struct_value_rtx (tree, int);
276 static rtx sh_function_value (const_tree, const_tree, bool);
277 static bool sh_function_value_regno_p (const unsigned int);
278 static rtx sh_libcall_value (enum machine_mode, const_rtx);
279 static bool sh_return_in_memory (const_tree, const_tree);
280 static rtx sh_builtin_saveregs (void);
281 static void sh_setup_incoming_varargs (cumulative_args_t, enum machine_mode,
282                                        tree, int *, int);
283 static bool sh_strict_argument_naming (cumulative_args_t);
284 static bool sh_pretend_outgoing_varargs_named (cumulative_args_t);
285 static tree sh_build_builtin_va_list (void);
286 static void sh_va_start (tree, rtx);
287 static tree sh_gimplify_va_arg_expr (tree, tree, gimple_seq *, gimple_seq *);
288 static bool sh_promote_prototypes (const_tree);
289 static enum machine_mode sh_promote_function_mode (const_tree type,
290                                                    enum machine_mode,
291                                                    int *punsignedp,
292                                                    const_tree funtype,
293                                                    int for_return);
294 static bool sh_pass_by_reference (cumulative_args_t, enum machine_mode,
295                                   const_tree, bool);
296 static bool sh_callee_copies (cumulative_args_t, enum machine_mode,
297                               const_tree, bool);
298 static int sh_arg_partial_bytes (cumulative_args_t, enum machine_mode,
299                                  tree, bool);
300 static void sh_function_arg_advance (cumulative_args_t, enum machine_mode,
301                                      const_tree, bool);
302 static rtx sh_function_arg (cumulative_args_t, enum machine_mode,
303                             const_tree, bool);
304 static bool sh_scalar_mode_supported_p (enum machine_mode);
305 static int sh_dwarf_calling_convention (const_tree);
306 static void sh_encode_section_info (tree, rtx, int);
307 static bool sh2a_function_vector_p (tree);
308 static void sh_trampoline_init (rtx, tree, rtx);
309 static rtx sh_trampoline_adjust_address (rtx);
310 static void sh_conditional_register_usage (void);
311 static bool sh_legitimate_constant_p (enum machine_mode, rtx);
312 static int mov_insn_size (enum machine_mode, bool);
313 static int max_mov_insn_displacement (enum machine_mode, bool);
314 static int mov_insn_alignment_mask (enum machine_mode, bool);
315 static HOST_WIDE_INT disp_addr_displacement (rtx);
316 static bool sequence_insn_p (rtx);
317 static void sh_canonicalize_comparison (int *, rtx *, rtx *, bool);
318 static void sh_canonicalize_comparison (enum rtx_code&, rtx&, rtx&,
319                                         enum machine_mode, bool);
320
321 static void sh_init_sync_libfuncs (void) ATTRIBUTE_UNUSED;
322 \f
323 static const struct attribute_spec sh_attribute_table[] =
324 {
325   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler,
326        affects_type_identity } */
327   { "interrupt_handler", 0, 0, true,  false, false,
328     sh_handle_interrupt_handler_attribute, false },
329   { "sp_switch",         1, 1, true,  false, false,
330      sh_handle_sp_switch_attribute, false },
331   { "trap_exit",         1, 1, true,  false, false,
332     sh_handle_trap_exit_attribute, false },
333   { "renesas",           0, 0, false, true, false,
334     sh_handle_renesas_attribute, false },
335   { "trapa_handler",     0, 0, true,  false, false,
336     sh_handle_interrupt_handler_attribute, false },
337   { "nosave_low_regs",   0, 0, true,  false, false,
338     sh_handle_interrupt_handler_attribute, false },
339   { "resbank",           0, 0, true,  false, false,
340     sh_handle_resbank_handler_attribute, false },
341   { "function_vector",   1, 1, true,  false, false,
342     sh2a_handle_function_vector_handler_attribute, false },
343   { NULL,                0, 0, false, false, false, NULL, false }
344 };
345 \f
346 /* Initialize the GCC target structure.  */
347 #undef TARGET_ATTRIBUTE_TABLE
348 #define TARGET_ATTRIBUTE_TABLE sh_attribute_table
349
350 /* The next two are used for debug info when compiling with -gdwarf.  */
351 #undef TARGET_ASM_UNALIGNED_HI_OP
352 #define TARGET_ASM_UNALIGNED_HI_OP "\t.uaword\t"
353 #undef TARGET_ASM_UNALIGNED_SI_OP
354 #define TARGET_ASM_UNALIGNED_SI_OP "\t.ualong\t"
355
356 /* These are NULLed out on non-SH5 in TARGET_OPTION_OVERRIDE.  */
357 #undef TARGET_ASM_UNALIGNED_DI_OP
358 #define TARGET_ASM_UNALIGNED_DI_OP "\t.uaquad\t"
359 #undef TARGET_ASM_ALIGNED_DI_OP
360 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
361
362 #undef TARGET_OPTION_OVERRIDE
363 #define TARGET_OPTION_OVERRIDE sh_option_override
364
365 #undef TARGET_PRINT_OPERAND
366 #define TARGET_PRINT_OPERAND sh_print_operand
367 #undef TARGET_PRINT_OPERAND_ADDRESS
368 #define TARGET_PRINT_OPERAND_ADDRESS sh_print_operand_address
369 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
370 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P sh_print_operand_punct_valid_p
371 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
372 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA sh_asm_output_addr_const_extra
373  
374 #undef TARGET_ASM_FUNCTION_EPILOGUE
375 #define TARGET_ASM_FUNCTION_EPILOGUE sh_output_function_epilogue
376
377 #undef TARGET_ASM_OUTPUT_MI_THUNK
378 #define TARGET_ASM_OUTPUT_MI_THUNK sh_output_mi_thunk
379
380 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
381 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK \
382   hook_bool_const_tree_hwi_hwi_const_tree_true
383
384 #undef TARGET_ASM_FILE_START
385 #define TARGET_ASM_FILE_START sh_file_start
386 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
387 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
388
389 #undef TARGET_REGISTER_MOVE_COST
390 #define TARGET_REGISTER_MOVE_COST sh_register_move_cost
391
392 #undef TARGET_INSERT_ATTRIBUTES
393 #define TARGET_INSERT_ATTRIBUTES sh_insert_attributes
394
395 #undef TARGET_SCHED_ADJUST_COST
396 #define TARGET_SCHED_ADJUST_COST sh_adjust_cost
397
398 #undef TARGET_SCHED_ISSUE_RATE
399 #define TARGET_SCHED_ISSUE_RATE sh_issue_rate
400
401 /* The next 5 hooks have been implemented for reenabling sched1.  With the
402    help of these macros we are limiting the movement of insns in sched1 to
403    reduce the register pressure.  The overall idea is to keep count of SImode
404    and SFmode regs required by already scheduled insns. When these counts
405    cross some threshold values; give priority to insns that free registers.
406    The insn that frees registers is most likely to be the insn with lowest
407    LUID (original insn order); but such an insn might be there in the stalled
408    queue (Q) instead of the ready queue (R).  To solve this, we skip cycles
409    up to a max of 8 cycles so that such insns may move from Q -> R.
410
411    The description of the hooks are as below:
412
413    TARGET_SCHED_INIT_GLOBAL: Added a new target hook in the generic
414    scheduler; it is called inside the sched_init function just after
415    find_insn_reg_weights function call. It is used to calculate the SImode
416    and SFmode weights of insns of basic blocks; much similar to what
417    find_insn_reg_weights does.
418    TARGET_SCHED_FINISH_GLOBAL: Corresponding cleanup hook.
419
420    TARGET_SCHED_DFA_NEW_CYCLE: Skip cycles if high register pressure is
421    indicated by TARGET_SCHED_REORDER2; doing this may move insns from
422    (Q)->(R).
423
424    TARGET_SCHED_REORDER: If the register pressure for SImode or SFmode is
425    high; reorder the ready queue so that the insn with lowest LUID will be
426    issued next.
427
428    TARGET_SCHED_REORDER2: If the register pressure is high, indicate to
429    TARGET_SCHED_DFA_NEW_CYCLE to skip cycles.
430
431    TARGET_SCHED_VARIABLE_ISSUE: Cache the value of can_issue_more so that it
432    can be returned from TARGET_SCHED_REORDER2.
433
434    TARGET_SCHED_INIT: Reset the register pressure counting variables.  */
435
436 #undef TARGET_SCHED_DFA_NEW_CYCLE
437 #define TARGET_SCHED_DFA_NEW_CYCLE sh_dfa_new_cycle
438
439 #undef TARGET_SCHED_INIT_GLOBAL
440 #define TARGET_SCHED_INIT_GLOBAL sh_md_init_global
441
442 #undef TARGET_SCHED_FINISH_GLOBAL
443 #define TARGET_SCHED_FINISH_GLOBAL sh_md_finish_global
444
445 #undef TARGET_SCHED_VARIABLE_ISSUE
446 #define TARGET_SCHED_VARIABLE_ISSUE sh_variable_issue
447
448 #undef TARGET_SCHED_REORDER
449 #define TARGET_SCHED_REORDER sh_reorder
450
451 #undef TARGET_SCHED_REORDER2
452 #define TARGET_SCHED_REORDER2 sh_reorder2
453
454 #undef TARGET_SCHED_INIT
455 #define TARGET_SCHED_INIT sh_md_init
456
457 #undef TARGET_DELEGITIMIZE_ADDRESS
458 #define TARGET_DELEGITIMIZE_ADDRESS sh_delegitimize_address
459
460 #undef TARGET_LEGITIMIZE_ADDRESS
461 #define TARGET_LEGITIMIZE_ADDRESS sh_legitimize_address
462
463 #undef TARGET_CANNOT_MODIFY_JUMPS_P
464 #define TARGET_CANNOT_MODIFY_JUMPS_P sh_cannot_modify_jumps_p
465 #undef TARGET_BRANCH_TARGET_REGISTER_CLASS
466 #define TARGET_BRANCH_TARGET_REGISTER_CLASS sh_target_reg_class
467 #undef TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED
468 #define TARGET_BRANCH_TARGET_REGISTER_CALLEE_SAVED \
469   sh_optimize_target_register_callee_saved
470
471 #undef TARGET_MS_BITFIELD_LAYOUT_P
472 #define TARGET_MS_BITFIELD_LAYOUT_P sh_ms_bitfield_layout_p
473
474 #undef TARGET_INIT_BUILTINS
475 #define TARGET_INIT_BUILTINS sh_init_builtins
476 #undef TARGET_BUILTIN_DECL
477 #define TARGET_BUILTIN_DECL sh_builtin_decl
478 #undef TARGET_EXPAND_BUILTIN
479 #define TARGET_EXPAND_BUILTIN sh_expand_builtin
480
481 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
482 #define TARGET_FUNCTION_OK_FOR_SIBCALL sh_function_ok_for_sibcall
483
484 #undef TARGET_CANNOT_COPY_INSN_P
485 #define TARGET_CANNOT_COPY_INSN_P sh_cannot_copy_insn_p
486 #undef TARGET_RTX_COSTS
487 #define TARGET_RTX_COSTS sh_rtx_costs
488 #undef TARGET_ADDRESS_COST
489 #define TARGET_ADDRESS_COST sh_address_cost
490 #undef TARGET_ALLOCATE_INITIAL_VALUE
491 #define TARGET_ALLOCATE_INITIAL_VALUE sh_allocate_initial_value
492
493 #undef TARGET_MACHINE_DEPENDENT_REORG
494 #define TARGET_MACHINE_DEPENDENT_REORG sh_reorg
495
496 #undef TARGET_DWARF_REGISTER_SPAN
497 #define TARGET_DWARF_REGISTER_SPAN sh_dwarf_register_span
498
499 #ifdef HAVE_AS_TLS
500 #undef TARGET_HAVE_TLS
501 #define TARGET_HAVE_TLS true
502 #endif
503
504 #undef TARGET_PROMOTE_PROTOTYPES
505 #define TARGET_PROMOTE_PROTOTYPES sh_promote_prototypes
506 #undef TARGET_PROMOTE_FUNCTION_MODE
507 #define TARGET_PROMOTE_FUNCTION_MODE sh_promote_function_mode
508
509 #undef TARGET_FUNCTION_VALUE
510 #define TARGET_FUNCTION_VALUE sh_function_value
511 #undef TARGET_FUNCTION_VALUE_REGNO_P
512 #define TARGET_FUNCTION_VALUE_REGNO_P sh_function_value_regno_p
513 #undef TARGET_LIBCALL_VALUE
514 #define TARGET_LIBCALL_VALUE sh_libcall_value
515 #undef TARGET_STRUCT_VALUE_RTX
516 #define TARGET_STRUCT_VALUE_RTX sh_struct_value_rtx
517 #undef TARGET_RETURN_IN_MEMORY
518 #define TARGET_RETURN_IN_MEMORY sh_return_in_memory
519
520 #undef TARGET_EXPAND_BUILTIN_SAVEREGS
521 #define TARGET_EXPAND_BUILTIN_SAVEREGS sh_builtin_saveregs
522 #undef TARGET_SETUP_INCOMING_VARARGS
523 #define TARGET_SETUP_INCOMING_VARARGS sh_setup_incoming_varargs
524 #undef TARGET_STRICT_ARGUMENT_NAMING
525 #define TARGET_STRICT_ARGUMENT_NAMING sh_strict_argument_naming
526 #undef TARGET_PRETEND_OUTGOING_VARARGS_NAMED
527 #define TARGET_PRETEND_OUTGOING_VARARGS_NAMED sh_pretend_outgoing_varargs_named
528 #undef TARGET_MUST_PASS_IN_STACK
529 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
530 #undef TARGET_PASS_BY_REFERENCE
531 #define TARGET_PASS_BY_REFERENCE sh_pass_by_reference
532 #undef TARGET_CALLEE_COPIES
533 #define TARGET_CALLEE_COPIES sh_callee_copies
534 #undef TARGET_ARG_PARTIAL_BYTES
535 #define TARGET_ARG_PARTIAL_BYTES sh_arg_partial_bytes
536 #undef TARGET_FUNCTION_ARG
537 #define TARGET_FUNCTION_ARG sh_function_arg
538 #undef TARGET_FUNCTION_ARG_ADVANCE
539 #define TARGET_FUNCTION_ARG_ADVANCE sh_function_arg_advance
540
541 #undef TARGET_BUILD_BUILTIN_VA_LIST
542 #define TARGET_BUILD_BUILTIN_VA_LIST sh_build_builtin_va_list
543 #undef TARGET_EXPAND_BUILTIN_VA_START
544 #define TARGET_EXPAND_BUILTIN_VA_START sh_va_start
545 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
546 #define TARGET_GIMPLIFY_VA_ARG_EXPR sh_gimplify_va_arg_expr
547
548 #undef TARGET_SCALAR_MODE_SUPPORTED_P
549 #define TARGET_SCALAR_MODE_SUPPORTED_P sh_scalar_mode_supported_p
550 #undef TARGET_VECTOR_MODE_SUPPORTED_P
551 #define TARGET_VECTOR_MODE_SUPPORTED_P sh_vector_mode_supported_p
552
553 #undef TARGET_CHECK_PCH_TARGET_FLAGS
554 #define TARGET_CHECK_PCH_TARGET_FLAGS sh_check_pch_target_flags
555
556 #undef TARGET_DWARF_CALLING_CONVENTION
557 #define TARGET_DWARF_CALLING_CONVENTION sh_dwarf_calling_convention
558
559 #undef TARGET_FRAME_POINTER_REQUIRED
560 #define TARGET_FRAME_POINTER_REQUIRED sh_frame_pointer_required
561
562 /* Return regmode weight for insn.  */
563 #define INSN_REGMODE_WEIGHT(INSN, MODE)\
564   regmode_weight[((MODE) == SImode) ? 0 : 1][INSN_UID (INSN)]
565
566 /* Return current register pressure for regmode.  */
567 #define CURR_REGMODE_PRESSURE(MODE)\
568   curr_regmode_pressure[((MODE) == SImode) ? 0 : 1]
569
570 #undef  TARGET_ENCODE_SECTION_INFO
571 #define TARGET_ENCODE_SECTION_INFO      sh_encode_section_info
572
573 #undef TARGET_SECONDARY_RELOAD
574 #define TARGET_SECONDARY_RELOAD sh_secondary_reload
575
576 #undef  TARGET_PREFERRED_RELOAD_CLASS
577 #define TARGET_PREFERRED_RELOAD_CLASS sh_preferred_reload_class
578
579 #undef TARGET_CONDITIONAL_REGISTER_USAGE
580 #define TARGET_CONDITIONAL_REGISTER_USAGE sh_conditional_register_usage
581
582 #undef TARGET_LEGITIMATE_ADDRESS_P
583 #define TARGET_LEGITIMATE_ADDRESS_P     sh_legitimate_address_p
584
585 #undef TARGET_TRAMPOLINE_INIT
586 #define TARGET_TRAMPOLINE_INIT          sh_trampoline_init
587 #undef TARGET_TRAMPOLINE_ADJUST_ADDRESS
588 #define TARGET_TRAMPOLINE_ADJUST_ADDRESS sh_trampoline_adjust_address
589
590 #undef TARGET_LEGITIMATE_CONSTANT_P
591 #define TARGET_LEGITIMATE_CONSTANT_P    sh_legitimate_constant_p
592
593 #undef TARGET_CANONICALIZE_COMPARISON
594 #define TARGET_CANONICALIZE_COMPARISON  sh_canonicalize_comparison
595
596 /* Machine-specific symbol_ref flags.  */
597 #define SYMBOL_FLAG_FUNCVEC_FUNCTION    (SYMBOL_FLAG_MACH_DEP << 0)
598
599 /* The tas.b instruction sets the 7th bit in the byte, i.e. 0x80.  This value
600    is used by optabs.c atomic op expansion code as well as in sync.md.  */
601 #undef TARGET_ATOMIC_TEST_AND_SET_TRUEVAL
602 #define TARGET_ATOMIC_TEST_AND_SET_TRUEVAL 0x80
603
604 struct gcc_target targetm = TARGET_INITIALIZER;
605 \f
606
607 /* Information on the currently selected atomic model.
608    This is initialized in sh_option_override.  */
609 static sh_atomic_model selected_atomic_model_;
610
611 const sh_atomic_model&
612 selected_atomic_model (void)
613 {
614   return selected_atomic_model_;
615 }
616
617 static sh_atomic_model
618 parse_validate_atomic_model_option (const char* str)
619 {
620   const char* model_names[sh_atomic_model::num_models];
621   model_names[sh_atomic_model::none] = "none";
622   model_names[sh_atomic_model::soft_gusa] = "soft-gusa";
623   model_names[sh_atomic_model::hard_llcs] = "hard-llcs";
624   model_names[sh_atomic_model::soft_tcb] = "soft-tcb";
625   model_names[sh_atomic_model::soft_imask] = "soft-imask";
626
627   const char* model_cdef_names[sh_atomic_model::num_models];
628   model_cdef_names[sh_atomic_model::none] = "NONE";
629   model_cdef_names[sh_atomic_model::soft_gusa] = "SOFT_GUSA";
630   model_cdef_names[sh_atomic_model::hard_llcs] = "HARD_LLCS";
631   model_cdef_names[sh_atomic_model::soft_tcb] = "SOFT_TCB";
632   model_cdef_names[sh_atomic_model::soft_imask] = "SOFT_IMASK";
633
634   sh_atomic_model ret;
635   ret.type = sh_atomic_model::none;
636   ret.name = model_names[sh_atomic_model::none];
637   ret.cdef_name = model_cdef_names[sh_atomic_model::none];
638   ret.strict = false;
639   ret.tcb_gbr_offset = -1;
640
641   /* Handle empty string as 'none'.  */
642   if (str == NULL || *str == '\0')
643     return ret;
644
645 #define err_ret(...) do { error (__VA_ARGS__); return ret; } while (0)
646
647   std::vector<std::string> tokens;
648   for (std::stringstream ss (str); ss.good (); )
649   {
650     tokens.push_back (std::string ());
651     std::getline (ss, tokens.back (), ',');
652   }
653
654   if (tokens.empty ())
655     err_ret ("invalid atomic model option");
656
657   /* The first token must be the atomic model name.  */
658   {
659     for (size_t i = 0; i < sh_atomic_model::num_models; ++i)
660       if (tokens.front () == model_names[i])
661         {
662           ret.type = (sh_atomic_model::enum_type)i;
663           ret.name = model_names[i];
664           ret.cdef_name = model_cdef_names[i];
665           goto got_mode_name;
666         }
667
668     err_ret ("invalid atomic model name \"%s\"", tokens.front ().c_str ());
669 got_mode_name:;
670   }
671
672   /* Go through the remaining tokens.  */
673   for (size_t i = 1; i < tokens.size (); ++i)
674     {
675       if (tokens[i] == "strict")
676         ret.strict = true;
677       else if (tokens[i].find ("gbr-offset=") == 0)
678         {
679           std::string offset_str = tokens[i].substr (strlen ("gbr-offset="));
680           ret.tcb_gbr_offset = integral_argument (offset_str.c_str ());
681           if (offset_str.empty () || ret.tcb_gbr_offset == -1)
682             err_ret ("could not parse gbr-offset value \"%s\" in atomic model "
683                      "option", offset_str.c_str ());
684         }
685       else
686         err_ret ("unknown parameter \"%s\" in atomic model option",
687                  tokens[i].c_str ());
688     }
689
690   /* Check that the selection makes sense.  */
691   if (TARGET_SHMEDIA && ret.type != sh_atomic_model::none)
692     err_ret ("atomic operations are not supported on SHmedia");
693
694   if (ret.type == sh_atomic_model::soft_gusa && !TARGET_SH3)
695     err_ret ("atomic model %s is only available on SH3 and SH4 targets",
696              ret.name);
697
698   if (ret.type == sh_atomic_model::hard_llcs && !TARGET_SH4A)
699     err_ret ("atomic model %s is only available on SH4A targets", ret.name);
700
701   if (ret.type == sh_atomic_model::soft_tcb && ret.tcb_gbr_offset == -1)
702     err_ret ("atomic model %s requires gbr-offset parameter", ret.name);
703
704   if (ret.type == sh_atomic_model::soft_tcb
705       && (ret.tcb_gbr_offset < 0 || ret.tcb_gbr_offset > 1020
706           || (ret.tcb_gbr_offset & 3) != 0))
707     err_ret ("invalid gbr-offset value \"%d\" for atomic model %s; it must be "
708              "a multiple of 4 in the range 0-1020", ret.tcb_gbr_offset,
709              ret.name);
710
711   if (ret.type == sh_atomic_model::soft_imask && TARGET_USERMODE)
712     err_ret ("cannot use atomic model %s in user mode", ret.name);
713
714   return ret;
715
716 #undef err_ret
717 }
718
719 /* Implement TARGET_OPTION_OVERRIDE macro.  Validate and override 
720    various options, and do some machine dependent initialization.  */
721 static void
722 sh_option_override (void)
723 {
724   int regno;
725
726   SUBTARGET_OVERRIDE_OPTIONS;
727   if (optimize > 1 && !optimize_size)
728     target_flags |= MASK_SAVE_ALL_TARGET_REGS;
729   sh_cpu = PROCESSOR_SH1;
730   assembler_dialect = 0;
731   if (TARGET_SH2)
732     sh_cpu = PROCESSOR_SH2;
733   if (TARGET_SH2E)
734     sh_cpu = PROCESSOR_SH2E;
735   if (TARGET_SH2A)
736     sh_cpu = PROCESSOR_SH2A;
737   if (TARGET_SH3)
738     sh_cpu = PROCESSOR_SH3;
739   if (TARGET_SH3E)
740     sh_cpu = PROCESSOR_SH3E;
741   if (TARGET_SH4)
742     {
743       assembler_dialect = 1;
744       sh_cpu = PROCESSOR_SH4;
745     }
746   if (TARGET_SH4A_ARCH)
747     {
748       assembler_dialect = 1;
749       sh_cpu = PROCESSOR_SH4A;
750     }
751   if (TARGET_SH5)
752     {
753       sh_cpu = PROCESSOR_SH5;
754       target_flags |= MASK_ALIGN_DOUBLE;
755       if (TARGET_SHMEDIA_FPU)
756         target_flags |= MASK_FMOVD;
757       if (TARGET_SHMEDIA)
758         {
759           /* There are no delay slots on SHmedia.  */
760           flag_delayed_branch = 0;
761           /* Relaxation isn't yet supported for SHmedia */
762           target_flags &= ~MASK_RELAX;
763           /* After reload, if conversion does little good but can cause
764              ICEs:
765              - find_if_block doesn't do anything for SH because we don't
766                have conditional execution patterns.  (We use conditional
767                move patterns, which are handled differently, and only
768                before reload).
769              - find_cond_trap doesn't do anything for the SH because we
770                don't have conditional traps.
771              - find_if_case_1 uses redirect_edge_and_branch_force in
772                the only path that does an optimization, and this causes
773                an ICE when branch targets are in registers.
774              - find_if_case_2 doesn't do anything for the SHmedia after
775                reload except when it can redirect a tablejump - and
776                that's rather rare.  */
777           flag_if_conversion2 = 0;
778           if (! strcmp (sh_div_str, "call"))
779             sh_div_strategy = SH_DIV_CALL;
780           else if (! strcmp (sh_div_str, "call2"))
781             sh_div_strategy = SH_DIV_CALL2;
782           if (! strcmp (sh_div_str, "fp") && TARGET_FPU_ANY)
783             sh_div_strategy = SH_DIV_FP;
784           else if (! strcmp (sh_div_str, "inv"))
785             sh_div_strategy = SH_DIV_INV;
786           else if (! strcmp (sh_div_str, "inv:minlat"))
787             sh_div_strategy = SH_DIV_INV_MINLAT;
788           else if (! strcmp (sh_div_str, "inv20u"))
789             sh_div_strategy = SH_DIV_INV20U;
790           else if (! strcmp (sh_div_str, "inv20l"))
791             sh_div_strategy = SH_DIV_INV20L;
792           else if (! strcmp (sh_div_str, "inv:call2"))
793             sh_div_strategy = SH_DIV_INV_CALL2;
794           else if (! strcmp (sh_div_str, "inv:call"))
795             sh_div_strategy = SH_DIV_INV_CALL;
796           else if (! strcmp (sh_div_str, "inv:fp"))
797             {
798               if (TARGET_FPU_ANY)
799                 sh_div_strategy = SH_DIV_INV_FP;
800               else
801                 sh_div_strategy = SH_DIV_INV;
802             }
803           TARGET_CBRANCHDI4 = 0;
804           /* Assembler CFI isn't yet fully supported for SHmedia.  */
805           flag_dwarf2_cfi_asm = 0;
806         }
807     }
808   else
809     {
810        /* Only the sh64-elf assembler fully supports .quad properly.  */
811        targetm.asm_out.aligned_op.di = NULL;
812        targetm.asm_out.unaligned_op.di = NULL;
813     }
814   if (TARGET_SH1)
815     {
816       if (! strcmp (sh_div_str, "call-div1"))
817         sh_div_strategy = SH_DIV_CALL_DIV1;
818       else if (! strcmp (sh_div_str, "call-fp")
819                && (TARGET_FPU_DOUBLE || TARGET_FPU_SINGLE_ONLY
820                    || (TARGET_SHCOMPACT && TARGET_FPU_ANY)))
821         sh_div_strategy = SH_DIV_CALL_FP;
822       else if (! strcmp (sh_div_str, "call-table") && TARGET_DYNSHIFT)
823         sh_div_strategy = SH_DIV_CALL_TABLE;
824       else
825         /* Pick one that makes most sense for the target in general.
826            It is not much good to use different functions depending
827            on -Os, since then we'll end up with two different functions
828            when some of the code is compiled for size, and some for
829            speed.  */
830
831         /* SH4 tends to emphasize speed.  */
832         if (TARGET_HARD_SH4)
833           sh_div_strategy = SH_DIV_CALL_TABLE;
834         /* These have their own way of doing things.  */
835         else if (TARGET_SH2A)
836           sh_div_strategy = SH_DIV_INTRINSIC;
837         /* ??? Should we use the integer SHmedia function instead?  */
838         else if (TARGET_SHCOMPACT && TARGET_FPU_ANY)
839           sh_div_strategy = SH_DIV_CALL_FP;
840         /* SH1 .. SH3 cores often go into small-footprint systems, so
841            default to the smallest implementation available.  */
842         else
843           sh_div_strategy = SH_DIV_CALL_DIV1;
844     }
845   if (!TARGET_SH1)
846     TARGET_PRETEND_CMOVE = 0;
847   if (sh_divsi3_libfunc[0])
848     ; /* User supplied - leave it alone.  */
849   else if (TARGET_DIVIDE_CALL_FP)
850     sh_divsi3_libfunc = "__sdivsi3_i4";
851   else if (TARGET_DIVIDE_CALL_TABLE)
852     sh_divsi3_libfunc = "__sdivsi3_i4i";
853   else if (TARGET_SH5)
854     sh_divsi3_libfunc = "__sdivsi3_1";
855   else
856     sh_divsi3_libfunc = "__sdivsi3";
857   if (sh_branch_cost == -1)
858     {
859       sh_branch_cost = 1;
860
861       /*  The SH1 does not have delay slots, hence we get a pipeline stall
862           at every branch.  The SH4 is superscalar, so the single delay slot
863           is not sufficient to keep both pipelines filled.  */
864       if (! TARGET_SH2 || TARGET_HARD_SH4)
865         sh_branch_cost = 2;
866     }
867
868   /* Set -mzdcbranch for SH4 / SH4A if not otherwise specified by the user.  */
869   if (! global_options_set.x_TARGET_ZDCBRANCH && TARGET_HARD_SH4)
870     TARGET_ZDCBRANCH = 1;
871
872   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
873     if (! VALID_REGISTER_P (regno))
874       sh_register_names[regno][0] = '\0';
875
876   for (regno = 0; regno < ADDREGNAMES_SIZE; regno++)
877     if (! VALID_REGISTER_P (ADDREGNAMES_REGNO (regno)))
878       sh_additional_register_names[regno][0] = '\0';
879
880   if ((flag_pic && ! TARGET_PREFERGOT)
881       || (TARGET_SHMEDIA && !TARGET_PT_FIXED))
882     flag_no_function_cse = 1;
883
884   if (targetm.small_register_classes_for_mode_p (VOIDmode))
885     {
886       /* Never run scheduling before reload, since that can
887          break global alloc, and generates slower code anyway due
888          to the pressure on R0.  */
889       /* Enable sched1 for SH4 if the user explicitly requests.
890          When sched1 is enabled, the ready queue will be reordered by
891          the target hooks if pressure is high.  We can not do this for
892          PIC, SH3 and lower as they give spill failures for R0.  */
893       if (!TARGET_HARD_SH4 || flag_pic)
894         flag_schedule_insns = 0;
895       /* ??? Current exception handling places basic block boundaries
896          after call_insns.  It causes the high pressure on R0 and gives
897          spill failures for R0 in reload.  See PR 22553 and the thread
898          on gcc-patches
899          <http://gcc.gnu.org/ml/gcc-patches/2005-10/msg00816.html>.  */
900       else if (flag_exceptions)
901         {
902           if (flag_schedule_insns && global_options_set.x_flag_schedule_insns)
903             warning (0, "ignoring -fschedule-insns because of exception "
904                         "handling bug");
905           flag_schedule_insns = 0;
906         }
907       else if (flag_schedule_insns
908                && !global_options_set.x_flag_schedule_insns)
909         flag_schedule_insns = 0;
910     }
911
912   /* Unwind info is not correct around the CFG unless either a frame
913      pointer is present or M_A_O_A is set.  Fixing this requires rewriting
914      unwind info generation to be aware of the CFG and propagating states
915      around edges.  */
916   if ((flag_unwind_tables || flag_asynchronous_unwind_tables
917        || flag_exceptions || flag_non_call_exceptions)
918       && flag_omit_frame_pointer && !TARGET_ACCUMULATE_OUTGOING_ARGS)
919     {
920       warning (0, "unwind tables currently require either a frame pointer "
921                "or -maccumulate-outgoing-args for correctness");
922       TARGET_ACCUMULATE_OUTGOING_ARGS = 1;
923     }
924
925   /* Unwinding with -freorder-blocks-and-partition does not work on this
926      architecture, because it requires far jumps to label crossing between
927      hot/cold sections which are rejected on this architecture.  */
928   if (flag_reorder_blocks_and_partition)
929     {
930       if (flag_exceptions)
931         {
932           inform (input_location, 
933                   "-freorder-blocks-and-partition does not work with "
934                   "exceptions on this architecture");
935           flag_reorder_blocks_and_partition = 0;
936           flag_reorder_blocks = 1;
937         }
938       else if (flag_unwind_tables)
939         {
940           inform (input_location,
941                   "-freorder-blocks-and-partition does not support unwind "
942                   "info on this architecture");
943           flag_reorder_blocks_and_partition = 0;
944           flag_reorder_blocks = 1;
945         }
946     }
947
948   /*  Adjust loop, jump and function alignment values (in bytes), if those
949       were not specified by the user using -falign-loops, -falign-jumps
950       and -falign-functions options.
951       32 bit alignment is better for speed, because instructions can be
952       fetched as a pair from a longword boundary.  For size use 16 bit
953       alignment to get more compact code.
954       Aligning all jumps increases the code size, even if it might
955       result in slightly faster code.  Thus, it is set to the smallest 
956       alignment possible if not specified by the user.  */
957   if (align_loops == 0)
958     {
959       if (TARGET_SH5)
960         align_loops = 8;
961       else
962         align_loops = optimize_size ? 2 : 4;
963     }
964
965   if (align_jumps == 0)
966     {
967       if (TARGET_SHMEDIA)
968         align_jumps = 1 << CACHE_LOG;
969       else
970         align_jumps = 2;
971     }
972   else if (align_jumps < (TARGET_SHMEDIA ? 4 : 2))
973     align_jumps = TARGET_SHMEDIA ? 4 : 2;
974
975   if (align_functions == 0)
976     {
977       if (TARGET_SHMEDIA)
978         align_functions = optimize_size
979                           ? FUNCTION_BOUNDARY/8 : (1 << CACHE_LOG);
980       else
981         align_functions = optimize_size ? 2 : 4;
982     }
983
984   /* The linker relaxation code breaks when a function contains
985      alignments that are larger than that at the start of a
986      compilation unit.  */
987   if (TARGET_RELAX)
988     {
989       int min_align = align_loops > align_jumps ? align_loops : align_jumps;
990
991       /* Also take possible .long constants / mova tables into account. */
992       if (min_align < 4)
993         min_align = 4;
994       if (align_functions < min_align)
995         align_functions = min_align;
996     }
997
998   if (flag_unsafe_math_optimizations)
999     {
1000       /* Enable fsca insn for SH4A if not otherwise specified by the user.  */
1001       if (global_options_set.x_TARGET_FSCA == 0 && TARGET_SH4A_FP)
1002         TARGET_FSCA = 1;
1003
1004       /* Enable fsrra insn for SH4A if not otherwise specified by the user.  */
1005       if (global_options_set.x_TARGET_FSRRA == 0 && TARGET_SH4A_FP)
1006         TARGET_FSRRA = 1;
1007     }
1008
1009   /*  Allow fsrra insn only if -funsafe-math-optimizations and
1010       -ffinite-math-only is enabled.  */
1011   TARGET_FSRRA = TARGET_FSRRA
1012                  && flag_unsafe_math_optimizations
1013                  && flag_finite_math_only;
1014
1015   /* If the -mieee option was not explicitly set by the user, turn it on
1016      unless -ffinite-math-only was specified.  See also PR 33135.  */
1017   if (! global_options_set.x_TARGET_IEEE)
1018     TARGET_IEEE = ! flag_finite_math_only;
1019
1020   if (sh_fixed_range_str)
1021     sh_fix_range (sh_fixed_range_str);
1022
1023   /* This target defaults to strict volatile bitfields.  */
1024   if (flag_strict_volatile_bitfields < 0 && abi_version_at_least(2))
1025     flag_strict_volatile_bitfields = 1;
1026
1027   /* Parse atomic model option and make sure it is valid for the current
1028      target CPU.  */
1029   selected_atomic_model_
1030     = parse_validate_atomic_model_option (sh_atomic_model_str);
1031 }
1032 \f
1033 /* Print the operand address in x to the stream.  */
1034 static void
1035 sh_print_operand_address (FILE *stream, rtx x)
1036 {
1037   switch (GET_CODE (x))
1038     {
1039     case REG:
1040     case SUBREG:
1041       fprintf (stream, "@%s", reg_names[true_regnum (x)]);
1042       break;
1043
1044     case PLUS:
1045       {
1046         rtx base = XEXP (x, 0);
1047         rtx index = XEXP (x, 1);
1048
1049         switch (GET_CODE (index))
1050           {
1051           case CONST_INT:
1052             fprintf (stream, "@(%d,%s)", (int) INTVAL (index),
1053                      reg_names[true_regnum (base)]);
1054             break;
1055
1056           case REG:
1057           case SUBREG:
1058             {
1059               int base_num = true_regnum (base);
1060               int index_num = true_regnum (index);
1061
1062               fprintf (stream, "@(r0,%s)",
1063                        reg_names[MAX (base_num, index_num)]);
1064               break;
1065             }
1066
1067           default:
1068             gcc_unreachable ();
1069           }
1070       }
1071       break;
1072
1073     case PRE_DEC:
1074       fprintf (stream, "@-%s", reg_names[true_regnum (XEXP (x, 0))]);
1075       break;
1076
1077     case POST_INC:
1078       fprintf (stream, "@%s+", reg_names[true_regnum (XEXP (x, 0))]);
1079       break;
1080
1081     default:
1082       x = mark_constant_pool_use (x);
1083       output_addr_const (stream, x);
1084       break;
1085     }
1086 }
1087
1088 /* Print operand x (an rtx) in assembler syntax to file stream
1089    according to modifier code.
1090
1091    '.'  print a .s if insn needs delay slot
1092    ','  print LOCAL_LABEL_PREFIX
1093    '@'  print trap, rte or rts depending upon pragma interruptness
1094    '#'  output a nop if there is nothing to put in the delay slot
1095    '''  print likelihood suffix (/u for unlikely).
1096    '>'  print branch target if -fverbose-asm
1097    'O'  print a constant without the #
1098    'R'  print the LSW of a dp value - changes if in little endian
1099    'S'  print the MSW of a dp value - changes if in little endian
1100    'T'  print the next word of a dp value - same as 'R' in big endian mode.
1101    'M'  SHMEDIA: print an `x' if `m' will print `base,index'.
1102         otherwise: print .b / .w / .l / .s / .d suffix if operand is a MEM.
1103    'N'  print 'r63' if the operand is (const_int 0).
1104    'd'  print a V2SF reg as dN instead of fpN.
1105    'm'  print a pair `base,offset' or `base,index', for LD and ST.
1106    'U'  Likewise for {LD,ST}{HI,LO}.
1107    'V'  print the position of a single bit set.
1108    'W'  print the position of a single bit cleared.
1109    't'  print a memory address which is a register.
1110    'u'  prints the lowest 16 bits of CONST_INT, as an unsigned value.
1111    'o'  output an operator.  */
1112 static void
1113 sh_print_operand (FILE *stream, rtx x, int code)
1114 {
1115   int regno;
1116   enum machine_mode mode;
1117
1118   switch (code)
1119     {
1120       tree trapa_attr;
1121
1122     case '.':
1123       if (final_sequence
1124           && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
1125           && get_attr_length (XVECEXP (final_sequence, 0, 1)))
1126         fprintf (stream, ASSEMBLER_DIALECT ? "/s" : ".s");
1127       break;
1128     case ',':
1129       fprintf (stream, "%s", LOCAL_LABEL_PREFIX);
1130       break;
1131     case '@':
1132       trapa_attr = lookup_attribute ("trap_exit",
1133                                       DECL_ATTRIBUTES (current_function_decl));
1134       if (trapa_attr)
1135         fprintf (stream, "trapa #%ld",
1136                  (long) TREE_INT_CST_LOW (TREE_VALUE (TREE_VALUE (trapa_attr))));
1137       else if (sh_cfun_interrupt_handler_p ())
1138         {
1139           if (sh_cfun_resbank_handler_p ())
1140             fprintf (stream, "resbank\n");
1141           fprintf (stream, "rte");
1142         }
1143       else
1144         fprintf (stream, "rts");
1145       break;
1146     case '#':
1147       /* Output a nop if there's nothing in the delay slot.  */
1148       if (dbr_sequence_length () == 0)
1149         fprintf (stream, "\n\tnop");
1150       break;
1151     case '\'':
1152       {
1153         rtx note = find_reg_note (current_output_insn, REG_BR_PROB, 0);
1154
1155         if (note && INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
1156           fputs ("/u", stream);
1157         break;
1158       }
1159     case '>':
1160       if (flag_verbose_asm && JUMP_LABEL (current_output_insn))
1161         {
1162           fputs ("\t! target: ", stream);
1163           output_addr_const (stream, JUMP_LABEL (current_output_insn));
1164         }
1165       break;
1166     case 'O':
1167       x = mark_constant_pool_use (x);
1168       output_addr_const (stream, x);
1169       break;
1170     /* N.B.: %R / %S / %T adjust memory addresses by four.
1171        For SHMEDIA, that means they can be used to access the first and
1172        second 32 bit part of a 64 bit (or larger) value that
1173        might be held in floating point registers or memory.
1174        While they can be used to access 64 bit parts of a larger value
1175        held in general purpose registers, that won't work with memory -
1176        neither for fp registers, since the frxx names are used.  */
1177     case 'R':
1178       if (REG_P (x) || GET_CODE (x) == SUBREG)
1179         {
1180           regno = true_regnum (x);
1181           regno += FP_REGISTER_P (regno) ? 1 : LSW;
1182           fputs (reg_names[regno], (stream));
1183         }
1184       else if (MEM_P (x))
1185         {
1186           x = adjust_address (x, SImode, 4 * LSW);
1187           sh_print_operand_address (stream, XEXP (x, 0));
1188         }
1189       else
1190         {
1191           rtx sub = NULL_RTX;
1192
1193           mode = GET_MODE (x);
1194           if (mode == VOIDmode)
1195             mode = DImode;
1196           if (GET_MODE_SIZE (mode) >= 8)
1197             sub = simplify_subreg (SImode, x, mode, 4 * LSW);
1198           if (sub)
1199             sh_print_operand (stream, sub, 0);
1200           else
1201             output_operand_lossage ("invalid operand to %%R");
1202         }
1203       break;
1204     case 'S':
1205       if (REG_P (x) || GET_CODE (x) == SUBREG)
1206         {
1207           regno = true_regnum (x);
1208           regno += FP_REGISTER_P (regno) ? 0 : MSW;
1209           fputs (reg_names[regno], (stream));
1210         }
1211       else if (MEM_P (x))
1212         {
1213           x = adjust_address (x, SImode, 4 * MSW);
1214           sh_print_operand_address (stream, XEXP (x, 0));
1215         }
1216       else
1217         {
1218           rtx sub = NULL_RTX;
1219
1220           mode = GET_MODE (x);
1221           if (mode == VOIDmode)
1222             mode = DImode;
1223           if (GET_MODE_SIZE (mode) >= 8)
1224             sub = simplify_subreg (SImode, x, mode, 4 * MSW);
1225           if (sub)
1226             sh_print_operand (stream, sub, 0);
1227           else
1228             output_operand_lossage ("invalid operand to %%S");
1229         }
1230       break;
1231     case 'T':
1232       /* Next word of a double.  */
1233       switch (GET_CODE (x))
1234         {
1235         case REG:
1236           fputs (reg_names[REGNO (x) + 1], (stream));
1237           break;
1238         case MEM:
1239           if (GET_CODE (XEXP (x, 0)) != PRE_DEC
1240               && GET_CODE (XEXP (x, 0)) != POST_INC)
1241             x = adjust_address (x, SImode, 4);
1242           sh_print_operand_address (stream, XEXP (x, 0));
1243           break;
1244         default:
1245           break;
1246         }
1247       break;
1248
1249     case 't':
1250       gcc_assert (MEM_P (x));
1251       x = XEXP (x, 0);
1252       switch (GET_CODE (x))
1253         {
1254         case REG:
1255         case SUBREG:
1256           sh_print_operand (stream, x, 0);
1257           break;
1258         default:
1259           break;
1260         }
1261       break;
1262
1263     case 'o':
1264       switch (GET_CODE (x))
1265         {
1266         case PLUS:  fputs ("add", stream); break;
1267         case MINUS: fputs ("sub", stream); break;
1268         case MULT:  fputs ("mul", stream); break;
1269         case DIV:   fputs ("div", stream); break;
1270         case EQ:    fputs ("eq",  stream); break;
1271         case NE:    fputs ("ne",  stream); break;
1272         case GT:  case LT:  fputs ("gt",  stream); break;
1273         case GE:  case LE:  fputs ("ge",  stream); break;
1274         case GTU: case LTU: fputs ("gtu", stream); break;
1275         case GEU: case LEU: fputs ("geu", stream); break;
1276         default:
1277           break;
1278         }
1279       break;
1280     case 'M':
1281       if (TARGET_SHMEDIA)
1282         {
1283           if (MEM_P (x)
1284               && GET_CODE (XEXP (x, 0)) == PLUS
1285               && (REG_P (XEXP (XEXP (x, 0), 1))
1286                   || GET_CODE (XEXP (XEXP (x, 0), 1)) == SUBREG))
1287             fputc ('x', stream);
1288         }
1289       else
1290         {
1291           if (MEM_P (x))
1292             {
1293               switch (GET_MODE (x))
1294                 {
1295                 case QImode: fputs (".b", stream); break;
1296                 case HImode: fputs (".w", stream); break;
1297                 case SImode: fputs (".l", stream); break;
1298                 case SFmode: fputs (".s", stream); break;
1299                 case DFmode: fputs (".d", stream); break;
1300                 default: gcc_unreachable ();
1301                 }
1302             }
1303         }
1304       break;
1305
1306     case 'm':
1307       gcc_assert (MEM_P (x));
1308       x = XEXP (x, 0);
1309       /* Fall through.  */
1310     case 'U':
1311       switch (GET_CODE (x))
1312         {
1313         case REG:
1314         case SUBREG:
1315           sh_print_operand (stream, x, 0);
1316           fputs (", 0", stream);
1317           break;
1318
1319         case PLUS:
1320           sh_print_operand (stream, XEXP (x, 0), 0);
1321           fputs (", ", stream);
1322           sh_print_operand (stream, XEXP (x, 1), 0);
1323           break;
1324
1325         default:
1326           gcc_unreachable ();
1327         }
1328       break;
1329
1330     case 'V':
1331       {
1332         int num = exact_log2 (INTVAL (x));
1333         gcc_assert (num >= 0);
1334         fprintf (stream, "#%d", num);
1335       }
1336       break;
1337
1338     case 'W':
1339       {
1340         int num = exact_log2 (~INTVAL (x));
1341         gcc_assert (num >= 0);
1342         fprintf (stream, "#%d", num);
1343       }
1344       break;
1345
1346     case 'd':
1347       gcc_assert (REG_P (x) && GET_MODE (x) == V2SFmode);
1348
1349       fprintf ((stream), "d%s", reg_names[REGNO (x)] + 1);
1350       break;
1351
1352     case 'N':
1353       if (x == CONST0_RTX (GET_MODE (x)))
1354         {
1355           fprintf ((stream), "r63");
1356           break;
1357         }
1358       goto default_output;
1359     case 'u':
1360       if (CONST_INT_P (x))
1361         {
1362           fprintf ((stream), "%u", (unsigned) INTVAL (x) & (0x10000 - 1));
1363           break;
1364         }
1365       /* Fall through.  */
1366
1367     default_output:
1368     default:
1369       regno = 0;
1370       mode = GET_MODE (x);
1371
1372       switch (GET_CODE (x))
1373         {
1374         case TRUNCATE:
1375           {
1376             rtx inner = XEXP (x, 0);
1377             int offset = 0;
1378             enum machine_mode inner_mode;
1379
1380             /* We might see SUBREGs with vector mode registers inside.  */
1381             if (GET_CODE (inner) == SUBREG
1382                 && (GET_MODE_SIZE (GET_MODE (inner))
1383                     == GET_MODE_SIZE (GET_MODE (SUBREG_REG (inner))))
1384                 && subreg_lowpart_p (inner))
1385               inner = SUBREG_REG (inner);
1386             if (CONST_INT_P (inner))
1387               {
1388                 x = GEN_INT (trunc_int_for_mode (INTVAL (inner), GET_MODE (x)));
1389                 goto default_output;
1390               }
1391             inner_mode = GET_MODE (inner);
1392             if (GET_CODE (inner) == SUBREG
1393                 && (GET_MODE_SIZE (GET_MODE (inner))
1394                     < GET_MODE_SIZE (GET_MODE (SUBREG_REG (inner))))
1395                 && REG_P (SUBREG_REG (inner)))
1396               {
1397                 offset = subreg_regno_offset (REGNO (SUBREG_REG (inner)),
1398                                               GET_MODE (SUBREG_REG (inner)),
1399                                               SUBREG_BYTE (inner),
1400                                               GET_MODE (inner));
1401                 inner = SUBREG_REG (inner);
1402               }
1403             if (!REG_P (inner) || GET_MODE_SIZE (inner_mode) > 8)
1404               abort ();
1405             /* Floating point register pairs are always big endian;
1406                general purpose registers are 64 bit wide.  */
1407             regno = REGNO (inner);
1408             regno = (HARD_REGNO_NREGS (regno, inner_mode)
1409                      - HARD_REGNO_NREGS (regno, mode))
1410                      + offset;
1411             x = inner;
1412             goto reg;
1413           }
1414         case SIGN_EXTEND:
1415           x = XEXP (x, 0);
1416           goto reg;
1417           /* FIXME: We need this on SHmedia32 because reload generates
1418              some sign-extended HI or QI loads into DImode registers
1419              but, because Pmode is SImode, the address ends up with a
1420              subreg:SI of the DImode register.  Maybe reload should be
1421              fixed so as to apply alter_subreg to such loads?  */
1422         case IF_THEN_ELSE:
1423           gcc_assert (trapping_target_operand (x, VOIDmode));
1424           x = XEXP (XEXP (x, 2), 0);
1425           goto default_output;
1426         case SUBREG:
1427           gcc_assert (SUBREG_BYTE (x) == 0
1428                       && REG_P (SUBREG_REG (x)));
1429
1430           x = SUBREG_REG (x);
1431           /* Fall through.  */
1432
1433         reg:
1434         case REG:
1435           regno += REGNO (x);
1436           if (FP_REGISTER_P (regno)
1437               && mode == V16SFmode)
1438             fprintf ((stream), "mtrx%s", reg_names[regno] + 2);
1439           else if (FP_REGISTER_P (REGNO (x))
1440                    && mode == V4SFmode)
1441             fprintf ((stream), "fv%s", reg_names[regno] + 2);
1442           else if (REG_P (x)
1443                    && mode == V2SFmode)
1444             fprintf ((stream), "fp%s", reg_names[regno] + 2);
1445           else if (FP_REGISTER_P (REGNO (x))
1446                    && GET_MODE_SIZE (mode) > 4)
1447             fprintf ((stream), "d%s", reg_names[regno] + 1);
1448           else
1449             fputs (reg_names[regno], (stream));
1450           break;
1451
1452         case MEM:
1453           output_address (XEXP (x, 0));
1454           break;
1455
1456         default:
1457           if (TARGET_SH1)
1458             fputc ('#', stream);
1459           output_addr_const (stream, x);
1460           break;
1461         }
1462       break;
1463     }
1464 }
1465
1466 static bool
1467 sh_print_operand_punct_valid_p (unsigned char code)
1468 {
1469   return (code == '.' || code == '#' || code == '@' || code == ','
1470           || code == '$' || code == '\'' || code == '>');
1471 }
1472
1473 /* Implement TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA.  */
1474 static bool
1475 sh_asm_output_addr_const_extra (FILE *file, rtx x)
1476 {
1477   if (GET_CODE (x) == UNSPEC)
1478     {
1479       switch (XINT (x, 1))
1480         {
1481         case UNSPEC_DATALABEL:
1482           fputs ("datalabel ", file);
1483           output_addr_const (file, XVECEXP (x, 0, 0));
1484           break;
1485         case UNSPEC_PIC:
1486           /* GLOBAL_OFFSET_TABLE or local symbols, no suffix.  */
1487           output_addr_const (file, XVECEXP (x, 0, 0));
1488           break;
1489         case UNSPEC_GOT:
1490           output_addr_const (file, XVECEXP (x, 0, 0));
1491           fputs ("@GOT", file);
1492           break;
1493         case UNSPEC_GOTOFF:
1494           output_addr_const (file, XVECEXP (x, 0, 0));
1495           fputs ("@GOTOFF", file);
1496           break;
1497         case UNSPEC_PLT:
1498           output_addr_const (file, XVECEXP (x, 0, 0));
1499           fputs ("@PLT", file);
1500           break;
1501         case UNSPEC_GOTPLT:
1502           output_addr_const (file, XVECEXP (x, 0, 0));
1503           fputs ("@GOTPLT", file);
1504           break;
1505         case UNSPEC_DTPOFF:
1506           output_addr_const (file, XVECEXP (x, 0, 0));
1507           fputs ("@DTPOFF", file);
1508           break;
1509         case UNSPEC_GOTTPOFF:
1510           output_addr_const (file, XVECEXP (x, 0, 0));
1511           fputs ("@GOTTPOFF", file);
1512           break;
1513         case UNSPEC_TPOFF:
1514           output_addr_const (file, XVECEXP (x, 0, 0));
1515           fputs ("@TPOFF", file);
1516           break;
1517         case UNSPEC_CALLER:
1518           {
1519             char name[32];
1520             /* LPCS stands for Label for PIC Call Site.  */
1521             targetm.asm_out.generate_internal_label (name, "LPCS",
1522                                                      INTVAL (XVECEXP (x, 0, 0)));
1523             assemble_name (file, name);
1524           }
1525           break;
1526         case UNSPEC_EXTRACT_S16:
1527         case UNSPEC_EXTRACT_U16:
1528           {
1529             rtx val, shift;
1530
1531             val = XVECEXP (x, 0, 0);
1532             shift = XVECEXP (x, 0, 1);
1533             fputc ('(', file);
1534             if (shift != const0_rtx)
1535                 fputc ('(', file);
1536             if (GET_CODE (val) == CONST
1537                 || GET_RTX_CLASS (GET_CODE (val)) != RTX_OBJ)
1538               {
1539                 fputc ('(', file);
1540                 output_addr_const (file, val);
1541                 fputc (')', file);
1542               }
1543             else
1544               output_addr_const (file, val);
1545             if (shift != const0_rtx)
1546               {
1547                 fputs (" >> ", file);
1548                 output_addr_const (file, shift);
1549                 fputc (')', file);
1550               }
1551             fputs (" & 65535)", file);
1552           }
1553           break;
1554         case UNSPEC_SYMOFF:
1555           output_addr_const (file, XVECEXP (x, 0, 0));
1556           fputc ('-', file);
1557           if (GET_CODE (XVECEXP (x, 0, 1)) == CONST)
1558             {
1559               fputc ('(', file);
1560               output_addr_const (file, XVECEXP (x, 0, 1));
1561               fputc (')', file);
1562             }
1563           else
1564             output_addr_const (file, XVECEXP (x, 0, 1));
1565           break;
1566         case UNSPEC_PCREL_SYMOFF:
1567           output_addr_const (file, XVECEXP (x, 0, 0));
1568           fputs ("-(", file);
1569           output_addr_const (file, XVECEXP (x, 0, 1));
1570           fputs ("-.)", file);
1571           break;
1572         default:
1573           return false;
1574         }
1575       return true;
1576     }
1577   else
1578     return false;
1579 }
1580 \f
1581 /* Encode symbol attributes of a SYMBOL_REF into its
1582    SYMBOL_REF_FLAGS.  */
1583 static void
1584 sh_encode_section_info (tree decl, rtx rtl, int first)
1585 {
1586   default_encode_section_info (decl, rtl, first);
1587
1588   if (TREE_CODE (decl) == FUNCTION_DECL
1589       && sh2a_function_vector_p (decl) && TARGET_SH2A)
1590     SYMBOL_REF_FLAGS (XEXP (rtl, 0)) |= SYMBOL_FLAG_FUNCVEC_FUNCTION;
1591 }
1592
1593 /* Like force_operand, but guarantees that VALUE ends up in TARGET.  */
1594 static void
1595 force_into (rtx value, rtx target)
1596 {
1597   value = force_operand (value, target);
1598   if (! rtx_equal_p (value, target))
1599     emit_insn (gen_move_insn (target, value));
1600 }
1601
1602 /* Emit code to perform a block move.  Choose the best method.
1603
1604    OPERANDS[0] is the destination.
1605    OPERANDS[1] is the source.
1606    OPERANDS[2] is the size.
1607    OPERANDS[3] is the alignment safe to use.  */
1608 bool
1609 expand_block_move (rtx *operands)
1610 {
1611   int align = INTVAL (operands[3]);
1612   int constp = (CONST_INT_P (operands[2]));
1613   int bytes = (constp ? INTVAL (operands[2]) : 0);
1614
1615   if (! constp)
1616     return false;
1617
1618   /* If we could use mov.l to move words and dest is word-aligned, we
1619      can use movua.l for loads and still generate a relatively short
1620      and efficient sequence.  */
1621   if (TARGET_SH4A_ARCH && align < 4
1622       && MEM_ALIGN (operands[0]) >= 32
1623       && can_move_by_pieces (bytes, 32))
1624     {
1625       rtx dest = copy_rtx (operands[0]);
1626       rtx src = copy_rtx (operands[1]);
1627       /* We could use different pseudos for each copied word, but
1628          since movua can only load into r0, it's kind of
1629          pointless.  */
1630       rtx temp = gen_reg_rtx (SImode);
1631       rtx src_addr = copy_addr_to_reg (XEXP (src, 0));
1632       int copied = 0;
1633
1634       while (copied + 4 <= bytes)
1635         {
1636           rtx to = adjust_address (dest, SImode, copied);
1637           rtx from = adjust_automodify_address (src, BLKmode,
1638                                                 src_addr, copied);
1639
1640           set_mem_size (from, 4);
1641           emit_insn (gen_movua (temp, from));
1642           emit_move_insn (src_addr, plus_constant (Pmode, src_addr, 4));
1643           emit_move_insn (to, temp);
1644           copied += 4;
1645         }
1646
1647       if (copied < bytes)
1648         move_by_pieces (adjust_address (dest, BLKmode, copied),
1649                         adjust_automodify_address (src, BLKmode,
1650                                                    src_addr, copied),
1651                         bytes - copied, align, 0);
1652
1653       return true;
1654     }
1655
1656   /* If it isn't a constant number of bytes, or if it doesn't have 4 byte
1657      alignment, or if it isn't a multiple of 4 bytes, then fail.  */
1658   if (align < 4 || (bytes % 4 != 0))
1659     return false;
1660
1661   if (TARGET_HARD_SH4)
1662     {
1663       if (bytes < 12)
1664         return false;
1665       else if (bytes == 12)
1666         {
1667           rtx func_addr_rtx = gen_reg_rtx (Pmode);
1668           rtx r4 = gen_rtx_REG (SImode, 4);
1669           rtx r5 = gen_rtx_REG (SImode, 5);
1670
1671           function_symbol (func_addr_rtx, "__movmemSI12_i4", SFUNC_STATIC);
1672           force_into (XEXP (operands[0], 0), r4);
1673           force_into (XEXP (operands[1], 0), r5);
1674           emit_insn (gen_block_move_real_i4 (func_addr_rtx));
1675           return true;
1676         }
1677       else if (! optimize_size)
1678         {
1679           const char *entry_name;
1680           rtx func_addr_rtx = gen_reg_rtx (Pmode);
1681           int dwords;
1682           rtx r4 = gen_rtx_REG (SImode, 4);
1683           rtx r5 = gen_rtx_REG (SImode, 5);
1684           rtx r6 = gen_rtx_REG (SImode, 6);
1685
1686           entry_name = (bytes & 4 ? "__movmem_i4_odd" : "__movmem_i4_even");
1687           function_symbol (func_addr_rtx, entry_name, SFUNC_STATIC);
1688           force_into (XEXP (operands[0], 0), r4);
1689           force_into (XEXP (operands[1], 0), r5);
1690
1691           dwords = bytes >> 3;
1692           emit_insn (gen_move_insn (r6, GEN_INT (dwords - 1)));
1693           emit_insn (gen_block_lump_real_i4 (func_addr_rtx));
1694           return true;
1695         }
1696       else
1697         return false;
1698     }
1699   if (bytes < 64)
1700     {
1701       char entry[30];
1702       rtx func_addr_rtx = gen_reg_rtx (Pmode);
1703       rtx r4 = gen_rtx_REG (SImode, 4);
1704       rtx r5 = gen_rtx_REG (SImode, 5);
1705
1706       sprintf (entry, "__movmemSI%d", bytes);
1707       function_symbol (func_addr_rtx, entry, SFUNC_STATIC);
1708       force_into (XEXP (operands[0], 0), r4);
1709       force_into (XEXP (operands[1], 0), r5);
1710       emit_insn (gen_block_move_real (func_addr_rtx));
1711       return true;
1712     }
1713
1714   /* This is the same number of bytes as a memcpy call, but to a different
1715      less common function name, so this will occasionally use more space.  */
1716   if (! optimize_size)
1717     {
1718       rtx func_addr_rtx = gen_reg_rtx (Pmode);
1719       int final_switch, while_loop;
1720       rtx r4 = gen_rtx_REG (SImode, 4);
1721       rtx r5 = gen_rtx_REG (SImode, 5);
1722       rtx r6 = gen_rtx_REG (SImode, 6);
1723
1724       function_symbol (func_addr_rtx, "__movmem", SFUNC_STATIC);
1725       force_into (XEXP (operands[0], 0), r4);
1726       force_into (XEXP (operands[1], 0), r5);
1727
1728       /* r6 controls the size of the move.  16 is decremented from it
1729          for each 64 bytes moved.  Then the negative bit left over is used
1730          as an index into a list of move instructions.  e.g., a 72 byte move
1731          would be set up with size(r6) = 14, for one iteration through the
1732          big while loop, and a switch of -2 for the last part.  */
1733
1734       final_switch = 16 - ((bytes / 4) % 16);
1735       while_loop = ((bytes / 4) / 16 - 1) * 16;
1736       emit_insn (gen_move_insn (r6, GEN_INT (while_loop + final_switch)));
1737       emit_insn (gen_block_lump_real (func_addr_rtx));
1738       return true;
1739     }
1740
1741   return false;
1742 }
1743
1744 /* Prepare operands for a move define_expand; specifically, one of the
1745    operands must be in a register.  */
1746 void
1747 prepare_move_operands (rtx operands[], enum machine_mode mode)
1748 {
1749   if ((mode == SImode || mode == DImode)
1750       && flag_pic
1751       && ! ((mode == Pmode || mode == ptr_mode)
1752             && tls_symbolic_operand (operands[1], Pmode) != TLS_MODEL_NONE))
1753     {
1754       rtx temp;
1755       if (SYMBOLIC_CONST_P (operands[1]))
1756         {
1757           if (MEM_P (operands[0]))
1758             operands[1] = force_reg (Pmode, operands[1]);
1759           else if (TARGET_SHMEDIA
1760                    && GET_CODE (operands[1]) == LABEL_REF
1761                    && target_reg_operand (operands[0], mode))
1762             /* It's ok.  */;
1763           else
1764             {
1765               temp = (!can_create_pseudo_p ()
1766                       ? operands[0]
1767                       : gen_reg_rtx (Pmode));
1768               operands[1] = legitimize_pic_address (operands[1], mode, temp);
1769             }
1770         }
1771       else if (GET_CODE (operands[1]) == CONST
1772                && GET_CODE (XEXP (operands[1], 0)) == PLUS
1773                && SYMBOLIC_CONST_P (XEXP (XEXP (operands[1], 0), 0)))
1774         {
1775           temp = !can_create_pseudo_p () ? operands[0] : gen_reg_rtx (Pmode);
1776           temp = legitimize_pic_address (XEXP (XEXP (operands[1], 0), 0),
1777                                          mode, temp);
1778           operands[1] = expand_binop (mode, add_optab, temp,
1779                                       XEXP (XEXP (operands[1], 0), 1),
1780                                       (!can_create_pseudo_p ()
1781                                        ? temp
1782                                        : gen_reg_rtx (Pmode)),
1783                                       0, OPTAB_LIB_WIDEN);
1784         }
1785     }
1786
1787   if (! reload_in_progress && ! reload_completed)
1788     {
1789       /* Copy the source to a register if both operands aren't registers.  */
1790       if (! register_operand (operands[0], mode)
1791           && ! sh_register_operand (operands[1], mode))
1792         operands[1] = copy_to_mode_reg (mode, operands[1]);
1793
1794       if (MEM_P (operands[0]) && ! memory_operand (operands[0], mode))
1795         {
1796           /* This is like change_address_1 (operands[0], mode, 0, 1) ,
1797              except that we can't use that function because it is static.  */
1798           rtx new_rtx = change_address (operands[0], mode, 0);
1799           MEM_COPY_ATTRIBUTES (new_rtx, operands[0]);
1800           operands[0] = new_rtx;
1801         }
1802
1803       /* This case can happen while generating code to move the result
1804          of a library call to the target.  Reject `st r0,@(rX,rY)' because
1805          reload will fail to find a spill register for rX, since r0 is already
1806          being used for the source.  */
1807       else if (TARGET_SH1
1808                && refers_to_regno_p (R0_REG, R0_REG + 1, operands[1], (rtx *)0)
1809                && MEM_P (operands[0])
1810                && GET_CODE (XEXP (operands[0], 0)) == PLUS
1811                && REG_P (XEXP (XEXP (operands[0], 0), 1)))
1812         operands[1] = copy_to_mode_reg (mode, operands[1]);
1813     }
1814
1815   if (mode == Pmode || mode == ptr_mode)
1816     {
1817       rtx op0, op1, opc;
1818       enum tls_model tls_kind;
1819
1820       op0 = operands[0];
1821       op1 = operands[1];
1822       if (GET_CODE (op1) == CONST
1823           && GET_CODE (XEXP (op1, 0)) == PLUS
1824           && (tls_symbolic_operand (XEXP (XEXP (op1, 0), 0), Pmode)
1825               != TLS_MODEL_NONE))
1826         {
1827           opc = XEXP (XEXP (op1, 0), 1);
1828           op1 = XEXP (XEXP (op1, 0), 0);
1829         }
1830       else
1831         opc = NULL_RTX;
1832
1833       if ((tls_kind = tls_symbolic_operand (op1, Pmode)) != TLS_MODEL_NONE)
1834         {
1835           rtx tga_op1, tga_ret, tmp, tmp2;
1836
1837           if (! flag_pic
1838               && (tls_kind == TLS_MODEL_GLOBAL_DYNAMIC
1839                   || tls_kind == TLS_MODEL_LOCAL_DYNAMIC
1840                   || tls_kind == TLS_MODEL_INITIAL_EXEC))
1841             {
1842               /* Don't schedule insns for getting GOT address when
1843                  the first scheduling is enabled, to avoid spill
1844                  failures for R0.  */
1845               if (flag_schedule_insns)
1846                 emit_insn (gen_blockage ());
1847               emit_insn (gen_GOTaddr2picreg ());
1848               emit_use (gen_rtx_REG (SImode, PIC_REG));
1849               if (flag_schedule_insns)
1850                 emit_insn (gen_blockage ());
1851         }
1852
1853           switch (tls_kind)
1854             {
1855             case TLS_MODEL_GLOBAL_DYNAMIC:
1856               tga_ret = gen_rtx_REG (Pmode, R0_REG);
1857               emit_call_insn (gen_tls_global_dynamic (tga_ret, op1));
1858               tmp = gen_reg_rtx (Pmode);
1859               emit_move_insn (tmp, tga_ret);
1860               op1 = tmp;
1861               break;
1862
1863             case TLS_MODEL_LOCAL_DYNAMIC:
1864               tga_ret = gen_rtx_REG (Pmode, R0_REG);
1865               emit_call_insn (gen_tls_local_dynamic (tga_ret, op1));
1866
1867               tmp = gen_reg_rtx (Pmode);
1868               emit_move_insn (tmp, tga_ret);
1869
1870               if (register_operand (op0, Pmode))
1871                 tmp2 = op0;
1872               else
1873                 tmp2 = gen_reg_rtx (Pmode);
1874
1875               emit_insn (gen_symDTPOFF2reg (tmp2, op1, tmp));
1876               op1 = tmp2;
1877               break;
1878
1879             case TLS_MODEL_INITIAL_EXEC:
1880               tga_op1 = !can_create_pseudo_p () ? op0 : gen_reg_rtx (Pmode);
1881               tmp = gen_sym2GOTTPOFF (op1);
1882               emit_insn (gen_tls_initial_exec (tga_op1, tmp));
1883               op1 = tga_op1;
1884               break;
1885
1886             case TLS_MODEL_LOCAL_EXEC:
1887               tmp2 = gen_reg_rtx (Pmode);
1888               emit_insn (gen_store_gbr (tmp2));
1889               tmp = gen_reg_rtx (Pmode);
1890               emit_insn (gen_symTPOFF2reg (tmp, op1));
1891
1892               if (register_operand (op0, Pmode))
1893                 op1 = op0;
1894               else
1895                 op1 = gen_reg_rtx (Pmode);
1896
1897               emit_insn (gen_addsi3 (op1, tmp, tmp2));
1898               break;
1899
1900             default:
1901               gcc_unreachable ();
1902             }
1903           if (opc)
1904             emit_insn (gen_addsi3 (op1, op1, force_reg (SImode, opc)));
1905           operands[1] = op1;
1906         }
1907     }
1908 }
1909
1910 /* Implement the canonicalize_comparison target hook for the combine
1911    pass.  For the target hook this function is invoked via
1912    sh_canonicalize_comparison.  This function is also re-used to
1913    canonicalize comparisons in cbranch pattern expanders.  */
1914 static void
1915 sh_canonicalize_comparison (enum rtx_code& cmp, rtx& op0, rtx& op1,
1916                             enum machine_mode mode,
1917                             bool op0_preserve_value ATTRIBUTE_UNUSED)
1918 {
1919   /* When invoked from within the combine pass the mode is not specified,
1920      so try to get it from one of the operands.  */
1921   if (mode == VOIDmode)
1922     mode = GET_MODE (op0);
1923   if (mode == VOIDmode)
1924     mode = GET_MODE (op1);
1925
1926   // We need to have a mode to do something useful here.
1927   if (mode == VOIDmode)
1928     return;
1929
1930   // Currently, we don't deal with floats here.
1931   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
1932     return;
1933
1934   // Make sure that the constant operand is the second operand.
1935   if (CONST_INT_P (op0) && !CONST_INT_P (op1))
1936     {
1937       std::swap (op0, op1);
1938       cmp = swap_condition (cmp);
1939     }
1940
1941   if (CONST_INT_P (op1))
1942     {
1943       /* Try to adjust the constant operand in such a way that available
1944          comparison insns can be utilized better and the constant can be
1945          loaded with a 'mov #imm,Rm' insn.  This avoids a load from the
1946          constant pool.  */
1947       const HOST_WIDE_INT val = INTVAL (op1);
1948
1949       /* x > -1           --> x >= 0
1950          x > 0xFFFFFF7F   --> x >= 0xFFFFFF80
1951          x <= -1          --> x < 0
1952          x <= 0xFFFFFF7F  --> x < 0xFFFFFF80  */
1953       if ((val == -1 || val == -0x81) && (cmp == GT || cmp == LE))
1954         {
1955           cmp = cmp == GT ? GE : LT;
1956           op1 = gen_int_mode (val + 1, mode);
1957         }
1958
1959       /* x >= 1     --> x > 0
1960          x >= 0x80  --> x > 0x7F
1961          x < 1      --> x <= 0
1962          x < 0x80   --> x <= 0x7F  */
1963       else if ((val == 1 || val == 0x80) && (cmp == GE || cmp == LT))
1964         {
1965           cmp = cmp == GE ? GT : LE;
1966           op1 = gen_int_mode (val - 1, mode);
1967         }
1968
1969       /* unsigned x >= 1  --> x != 0
1970          unsigned x < 1   --> x == 0  */
1971       else if (val == 1 && (cmp == GEU || cmp == LTU))
1972         {
1973           cmp = cmp == GEU ? NE : EQ;
1974           op1 = CONST0_RTX (mode);
1975         }
1976
1977       /* unsigned x >= 0x80  --> unsigned x > 0x7F
1978          unsigned x < 0x80   --> unsigned x < 0x7F  */
1979       else if (val == 0x80 && (cmp == GEU || cmp == LTU))
1980         {
1981           cmp = cmp == GEU ? GTU : LEU;
1982           op1 = gen_int_mode (val - 1, mode);
1983         }
1984
1985       /* unsigned x > 0   --> x != 0
1986          unsigned x <= 0  --> x == 0  */
1987       else if (val == 0 && (cmp == GTU || cmp == LEU))
1988         cmp = cmp == GTU ? NE : EQ;
1989
1990       /* unsigned x > 0x7FFFFFFF   --> signed x < 0
1991          unsigned x <= 0x7FFFFFFF  --> signed x >= 0  */
1992       else if (mode == SImode && (cmp == GTU || cmp == LEU)
1993                && val == 0x7FFFFFFF)
1994         {
1995           cmp = cmp == GTU ? LT : GE;
1996           op1 = const0_rtx;
1997         }
1998
1999       /* unsigned x >= 0x80000000  --> signed x < 0
2000          unsigned x < 0x80000000   --> signed x >= 0  */
2001       else if (mode == SImode && (cmp == GEU || cmp == LTU)
2002                && (unsigned HOST_WIDE_INT)val
2003                    == ((unsigned HOST_WIDE_INT)0x7FFFFFFF + 1))
2004         {
2005           cmp = cmp == GEU ? LT : GE;
2006           op1 = const0_rtx;
2007         }
2008     }
2009 }
2010
2011 /* This function implements the canonicalize_comparison target hook.
2012    This wrapper around the internally used sh_canonicalize_comparison
2013    function is needed to do the enum rtx_code <-> int conversion.
2014    Target hooks cannot use enum rtx_code in its definition.  */
2015 static void
2016 sh_canonicalize_comparison (int *code, rtx *op0, rtx *op1,
2017                             bool op0_preserve_value)
2018 {
2019   enum rtx_code tmp_code = (enum rtx_code)*code;
2020   sh_canonicalize_comparison (tmp_code, *op0, *op1,
2021                               VOIDmode, op0_preserve_value);
2022   *code = (int)tmp_code;
2023 }
2024
2025 enum rtx_code
2026 prepare_cbranch_operands (rtx *operands, enum machine_mode mode,
2027                           enum rtx_code comparison)
2028 {
2029   /* The scratch reg is only available when this is invoked from within
2030      the cbranchdi4_i splitter, through expand_cbranchdi4.  */
2031   rtx scratch = NULL_RTX;
2032
2033   if (comparison == LAST_AND_UNUSED_RTX_CODE)
2034     comparison = GET_CODE (operands[0]);
2035   else
2036     scratch = operands[4];
2037
2038   sh_canonicalize_comparison (comparison, operands[1], operands[2],
2039                               mode, false);
2040
2041   /* Notice that this function is also invoked after reload by
2042      the cbranchdi4_i pattern, through expand_cbranchdi4.  */
2043   rtx op1 = operands[1];
2044
2045   if (can_create_pseudo_p ())
2046     operands[1] = force_reg (mode, op1);
2047   /* When we are handling DImode comparisons, we want to keep constants so
2048      that we can optimize the component comparisons; however, memory loads
2049      are better issued as a whole so that they can be scheduled well.
2050      SImode equality comparisons allow I08 constants, but only when they
2051      compare r0.  Hence, if operands[1] has to be loaded from somewhere else
2052      into a register, that register might as well be r0, and we allow the
2053      constant.  If it is already in a register, this is likely to be
2054      allocated to a different hard register, thus we load the constant into
2055      a register unless it is zero.  */
2056   if (!REG_P (operands[2])
2057       && (!CONST_INT_P (operands[2])
2058           || (mode == SImode && operands[2] != CONST0_RTX (SImode)
2059               && ((comparison != EQ && comparison != NE)
2060                   || (REG_P (op1) && REGNO (op1) != R0_REG)
2061                   || !satisfies_constraint_I08 (operands[2])))))
2062     {
2063       if (scratch && GET_MODE (scratch) == mode)
2064         {
2065           emit_move_insn (scratch, operands[2]);
2066           operands[2] = scratch;
2067         }
2068       else if (can_create_pseudo_p ())
2069         operands[2] = force_reg (mode, operands[2]);
2070     }
2071   return comparison;
2072 }
2073
2074 void
2075 expand_cbranchsi4 (rtx *operands, enum rtx_code comparison, int probability)
2076 {
2077   rtx (*branch_expander) (rtx) = gen_branch_true;
2078   comparison = prepare_cbranch_operands (operands, SImode, comparison);
2079   switch (comparison)
2080     {
2081     case NE: case LT: case LE: case LTU: case LEU:
2082       comparison = reverse_condition (comparison);
2083       branch_expander = gen_branch_false;
2084     default: ;
2085     }
2086   emit_insn (gen_rtx_SET (VOIDmode, get_t_reg_rtx (),
2087                           gen_rtx_fmt_ee (comparison, SImode,
2088                                           operands[1], operands[2])));
2089   rtx jump = emit_jump_insn (branch_expander (operands[3]));
2090   if (probability >= 0)
2091     add_reg_note (jump, REG_BR_PROB, GEN_INT (probability));
2092 }
2093
2094 /* ??? How should we distribute probabilities when more than one branch
2095    is generated.  So far we only have some ad-hoc observations:
2096    - If the operands are random, they are likely to differ in both parts.
2097    - If comparing items in a hash chain, the operands are random or equal;
2098      operation should be EQ or NE.
2099    - If items are searched in an ordered tree from the root, we can expect
2100      the highpart to be unequal about half of the time; operation should be
2101      an inequality comparison, operands non-constant, and overall probability
2102      about 50%.  Likewise for quicksort.
2103    - Range checks will be often made against constants.  Even if we assume for
2104      simplicity an even distribution of the non-constant operand over a
2105      sub-range here, the same probability could be generated with differently
2106      wide sub-ranges - as long as the ratio of the part of the subrange that
2107      is before the threshold to the part that comes after the threshold stays
2108      the same.  Thus, we can't really tell anything here;
2109      assuming random distribution is at least simple.
2110  */
2111 bool
2112 expand_cbranchdi4 (rtx *operands, enum rtx_code comparison)
2113 {
2114   enum rtx_code msw_taken, msw_skip, lsw_taken;
2115   rtx skip_label = NULL_RTX;
2116   rtx op1h, op1l, op2h, op2l;
2117   int num_branches;
2118   int prob, rev_prob;
2119   int msw_taken_prob = -1, msw_skip_prob = -1, lsw_taken_prob = -1;
2120   rtx scratch = operands[4];
2121
2122   comparison = prepare_cbranch_operands (operands, DImode, comparison);
2123   op1h = gen_highpart_mode (SImode, DImode, operands[1]);
2124   op2h = gen_highpart_mode (SImode, DImode, operands[2]);
2125   op1l = gen_lowpart (SImode, operands[1]);
2126   op2l = gen_lowpart (SImode, operands[2]);
2127   msw_taken = msw_skip = lsw_taken = LAST_AND_UNUSED_RTX_CODE;
2128   prob = split_branch_probability;
2129   rev_prob = REG_BR_PROB_BASE - prob;
2130   switch (comparison)
2131     {
2132     /* ??? Should we use the cmpeqdi_t pattern for equality comparisons?
2133        That costs 1 cycle more when the first branch can be predicted taken,
2134        but saves us mispredicts because only one branch needs prediction.
2135        It also enables generating the cmpeqdi_t-1 pattern.  */
2136     case EQ:
2137       if (TARGET_CMPEQDI_T)
2138         {
2139           emit_insn (gen_cmpeqdi_t (operands[1], operands[2]));
2140           emit_jump_insn (gen_branch_true (operands[3]));
2141           return true;
2142         }
2143       msw_skip = NE;
2144       lsw_taken = EQ;
2145       if (prob >= 0)
2146         {
2147           // If we had more precision, we'd use rev_prob - (rev_prob >> 32) .
2148           msw_skip_prob = rev_prob;
2149           if (REG_BR_PROB_BASE <= 65535)
2150             lsw_taken_prob = prob ? REG_BR_PROB_BASE : 0;
2151           else
2152             {
2153               gcc_assert (HOST_BITS_PER_WIDEST_INT >= 64);
2154               lsw_taken_prob
2155                 = (prob
2156                    ? (REG_BR_PROB_BASE
2157                       - ((HOST_WIDEST_INT) REG_BR_PROB_BASE * rev_prob
2158                          / ((HOST_WIDEST_INT) prob << 32)))
2159                    : 0);
2160             }
2161         }
2162       break;
2163     case NE:
2164       if (TARGET_CMPEQDI_T)
2165         {
2166           emit_insn (gen_cmpeqdi_t (operands[1], operands[2]));
2167           emit_jump_insn (gen_branch_false (operands[3]));
2168           return true;
2169         }
2170       msw_taken = NE;
2171       msw_taken_prob = prob;
2172       lsw_taken = NE;
2173       lsw_taken_prob = 0;
2174       break;
2175     case GTU: case GT:
2176       msw_taken = comparison;
2177       if (CONST_INT_P (op2l) && INTVAL (op2l) == -1)
2178         break;
2179       if (comparison != GTU || op2h != CONST0_RTX (SImode))
2180         msw_skip = swap_condition (msw_taken);
2181       lsw_taken = GTU;
2182       break;
2183     case GEU: case GE:
2184       if (op2l == CONST0_RTX (SImode))
2185         msw_taken = comparison;
2186       else
2187         {
2188           msw_taken = comparison == GE ? GT : GTU;
2189           msw_skip = swap_condition (msw_taken);
2190           lsw_taken = GEU;
2191         }
2192       break;
2193     case LTU: case LT:
2194       msw_taken = comparison;
2195       if (op2l == CONST0_RTX (SImode))
2196         break;
2197       msw_skip = swap_condition (msw_taken);
2198       lsw_taken = LTU;
2199       break;
2200     case LEU: case LE:
2201       if (CONST_INT_P (op2l) && INTVAL (op2l) == -1)
2202         msw_taken = comparison;
2203       else
2204         {
2205           lsw_taken = LEU;
2206           if (comparison == LE)
2207             msw_taken = LT;
2208           else if (op2h != CONST0_RTX (SImode))
2209             msw_taken = LTU;
2210           else
2211             {
2212               msw_skip = swap_condition (LTU);
2213               break;
2214             }
2215           msw_skip = swap_condition (msw_taken);
2216         }
2217       break;
2218     default: return false;
2219     }
2220   num_branches = ((msw_taken != LAST_AND_UNUSED_RTX_CODE)
2221                   + (msw_skip != LAST_AND_UNUSED_RTX_CODE)
2222                   + (lsw_taken != LAST_AND_UNUSED_RTX_CODE));
2223   if (comparison != EQ && comparison != NE && num_branches > 1)
2224     {
2225       if (!CONSTANT_P (operands[2])
2226           && prob >= (int) (REG_BR_PROB_BASE * 3 / 8U)
2227           && prob <= (int) (REG_BR_PROB_BASE * 5 / 8U))
2228         {
2229           msw_taken_prob = prob / 2U;
2230           msw_skip_prob
2231             = REG_BR_PROB_BASE * rev_prob / (REG_BR_PROB_BASE + rev_prob);
2232           lsw_taken_prob = prob;
2233         }
2234       else
2235         {
2236           msw_taken_prob = prob;
2237           msw_skip_prob = REG_BR_PROB_BASE;
2238           /* ??? If we have a constant op2h, should we use that when
2239              calculating lsw_taken_prob?  */
2240           lsw_taken_prob = prob;
2241         }
2242     }
2243   operands[1] = op1h;
2244   operands[2] = op2h;
2245   operands[4] = NULL_RTX;
2246   if (reload_completed
2247       && ! arith_reg_or_0_operand (op2h, SImode)
2248       && (true_regnum (op1h) || (comparison != EQ && comparison != NE))
2249       && (msw_taken != LAST_AND_UNUSED_RTX_CODE
2250           || msw_skip != LAST_AND_UNUSED_RTX_CODE))
2251     {
2252       emit_move_insn (scratch, operands[2]);
2253       operands[2] = scratch;
2254     }
2255   if (msw_taken != LAST_AND_UNUSED_RTX_CODE)
2256     expand_cbranchsi4 (operands, msw_taken, msw_taken_prob);
2257   if (msw_skip != LAST_AND_UNUSED_RTX_CODE)
2258     {
2259       rtx taken_label = operands[3];
2260
2261       /* Operands were possibly modified, but msw_skip doesn't expect this.
2262          Always use the original ones.  */
2263       if (msw_taken != LAST_AND_UNUSED_RTX_CODE)
2264         {
2265           operands[1] = op1h;
2266           operands[2] = op2h;
2267           if (reload_completed
2268               && ! arith_reg_or_0_operand (op2h, SImode)
2269               && (true_regnum (op1h) || (comparison != EQ && comparison != NE)))
2270             {
2271               emit_move_insn (scratch, operands[2]);
2272               operands[2] = scratch;
2273             }
2274         }
2275
2276       operands[3] = skip_label = gen_label_rtx ();
2277       expand_cbranchsi4 (operands, msw_skip, msw_skip_prob);
2278       operands[3] = taken_label;
2279     }
2280   operands[1] = op1l;
2281   operands[2] = op2l;
2282   if (lsw_taken != LAST_AND_UNUSED_RTX_CODE)
2283     {
2284       if (reload_completed
2285           && ! arith_reg_or_0_operand (op2l, SImode)
2286           && (true_regnum (op1l) || (lsw_taken != EQ && lsw_taken != NE)))
2287         {
2288           emit_move_insn (scratch, operands[2]);
2289           operands[2] = scratch;
2290         }
2291       expand_cbranchsi4 (operands, lsw_taken, lsw_taken_prob);
2292     }
2293   if (msw_skip != LAST_AND_UNUSED_RTX_CODE)
2294     emit_label (skip_label);
2295   return true;
2296 }
2297
2298 /* Given an operand, return 1 if the evaluated operand plugged into an
2299    if_then_else will result in a branch_true, 0 if branch_false, or
2300    -1 if neither nor applies.  The truth table goes like this:
2301
2302        op   | cmpval |   code  | result
2303    ---------+--------+---------+--------------------
2304       T (0) |   0    |  EQ (1) |  0 = 0 ^ (0 == 1)
2305       T (0) |   1    |  EQ (1) |  1 = 0 ^ (1 == 1)
2306       T (0) |   0    |  NE (0) |  1 = 0 ^ (0 == 0)
2307       T (0) |   1    |  NE (0) |  0 = 0 ^ (1 == 0)
2308      !T (1) |   0    |  EQ (1) |  1 = 1 ^ (0 == 1)
2309      !T (1) |   1    |  EQ (1) |  0 = 1 ^ (1 == 1)
2310      !T (1) |   0    |  NE (0) |  0 = 1 ^ (0 == 0)
2311      !T (1) |   1    |  NE (0) |  1 = 1 ^ (1 == 0)  */
2312 int
2313 sh_eval_treg_value (rtx op)
2314 {
2315   enum rtx_code code = GET_CODE (op);
2316   if ((code != EQ && code != NE) || !CONST_INT_P (XEXP (op, 1)))
2317     return -1;
2318
2319   int cmpop = code == EQ ? 1 : 0;
2320   int cmpval = INTVAL (XEXP (op, 1));
2321   if (cmpval != 0 && cmpval != 1)
2322     return -1;
2323
2324   int t;
2325   if (t_reg_operand (XEXP (op, 0), GET_MODE (XEXP (op, 0))))
2326     t = 0;
2327   else if (negt_reg_operand (XEXP (op, 0), GET_MODE (XEXP (op, 0))))
2328     t = 1;
2329   else
2330     return -1;
2331   
2332   return t ^ (cmpval == cmpop);
2333 }
2334
2335 /* Emit INSN, possibly in a PARALLEL with an USE of fpscr for SH4.  */
2336
2337 static void
2338 sh_emit_set_t_insn (rtx insn, enum machine_mode mode)
2339 {
2340   if ((TARGET_SH4 || TARGET_SH2A) && GET_MODE_CLASS (mode) == MODE_FLOAT)
2341     {
2342       insn = gen_rtx_PARALLEL (VOIDmode,
2343                        gen_rtvec (2, insn,
2344                                   gen_rtx_USE (VOIDmode, get_fpscr_rtx ())));
2345       (mode == SFmode ? emit_sf_insn : emit_df_insn) (insn);
2346     }
2347   else
2348     emit_insn (insn);
2349 }
2350
2351 /* Prepare the operands for an scc instruction; make sure that the
2352    compare has been done and the result is in T_REG.  */
2353 void
2354 sh_emit_scc_to_t (enum rtx_code code, rtx op0, rtx op1)
2355 {
2356   rtx t_reg = get_t_reg_rtx ();
2357   enum rtx_code oldcode = code;
2358   enum machine_mode mode;
2359
2360   /* First need a compare insn.  */
2361   switch (code)
2362     {
2363     case NE:
2364       /* It isn't possible to handle this case.  */
2365       gcc_unreachable ();
2366     case LT:
2367       code = GT;
2368       break;
2369     case LE:
2370       code = GE;
2371       break;
2372     case LTU:
2373       code = GTU;
2374       break;
2375     case LEU:
2376       code = GEU;
2377       break;
2378     default:
2379       break;
2380     }
2381   if (code != oldcode)
2382     {
2383       rtx tmp = op0;
2384       op0 = op1;
2385       op1 = tmp;
2386     }
2387
2388   mode = GET_MODE (op0);
2389   if (mode == VOIDmode)
2390     mode = GET_MODE (op1);
2391
2392   op0 = force_reg (mode, op0);
2393   if ((code != EQ && code != NE
2394        && (op1 != const0_rtx
2395            || code == GTU  || code == GEU || code == LTU || code == LEU))
2396       || (mode == DImode && op1 != const0_rtx)
2397       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
2398     op1 = force_reg (mode, op1);
2399
2400   sh_emit_set_t_insn (gen_rtx_SET (VOIDmode, t_reg,
2401                                    gen_rtx_fmt_ee (code, SImode, op0, op1)),
2402                       mode);
2403 }
2404
2405 rtx
2406 sh_emit_cheap_store_flag (enum machine_mode mode, enum rtx_code code,
2407                           rtx op0, rtx op1)
2408 {
2409   rtx target = gen_reg_rtx (SImode);
2410   rtx tmp;
2411
2412   gcc_assert (TARGET_SHMEDIA);
2413   switch (code)
2414     {
2415     case EQ:
2416     case GT:
2417     case LT:
2418     case UNORDERED:
2419     case GTU:
2420     case LTU:
2421       tmp = gen_rtx_fmt_ee (code, SImode, op0, op1);
2422       emit_insn (gen_cstore4_media (target, tmp, op0, op1));
2423       code = NE;
2424       break;
2425
2426     case NE:
2427     case GE:
2428     case LE:
2429     case ORDERED:
2430     case GEU:
2431     case LEU:
2432       tmp = gen_rtx_fmt_ee (reverse_condition (code), mode, op0, op1);
2433       emit_insn (gen_cstore4_media (target, tmp, op0, op1));
2434       code = EQ;
2435       break;
2436
2437     case UNEQ:
2438     case UNGE:
2439     case UNGT:
2440     case UNLE:
2441     case UNLT:
2442     case LTGT:
2443       return NULL_RTX;
2444
2445     default:
2446       gcc_unreachable ();
2447     }
2448
2449   if (mode == DImode)
2450     {
2451       rtx t2 = gen_reg_rtx (DImode);
2452       emit_insn (gen_extendsidi2 (t2, target));
2453       target = t2;
2454     }
2455
2456   return gen_rtx_fmt_ee (code, VOIDmode, target, const0_rtx);
2457 }
2458
2459 /* Called from the md file, set up the operands of a compare instruction.  */
2460 void
2461 sh_emit_compare_and_branch (rtx *operands, enum machine_mode mode)
2462 {
2463   enum rtx_code code = GET_CODE (operands[0]);
2464   enum rtx_code branch_code;
2465   rtx op0 = operands[1];
2466   rtx op1 = operands[2];
2467   rtx insn, tem;
2468   bool need_ccmpeq = false;
2469
2470   if (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT)
2471     {
2472       op0 = force_reg (mode, op0);
2473       op1 = force_reg (mode, op1);
2474     }
2475   else
2476     {
2477       if (code != EQ || mode == DImode)
2478         {
2479           /* Force args into regs, since we can't use constants here.  */
2480           op0 = force_reg (mode, op0);
2481           if (op1 != const0_rtx || code == GTU  || code == GEU)
2482             op1 = force_reg (mode, op1);
2483         }
2484     }
2485
2486   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
2487     {
2488       if (code == LT
2489           || (code == LE && TARGET_IEEE && TARGET_SH2E)
2490           || (code == GE && !(TARGET_IEEE && TARGET_SH2E)))
2491         {
2492           tem = op0, op0 = op1, op1 = tem;
2493           code = swap_condition (code);
2494         }
2495
2496       /* GE becomes fcmp/gt+fcmp/eq, for SH2E and TARGET_IEEE only.  */
2497       if (code == GE)
2498         {
2499           gcc_assert (TARGET_IEEE && TARGET_SH2E);
2500           need_ccmpeq = true;
2501           code = GT;
2502         }
2503
2504       /* Now we can have EQ, NE, GT, LE.  NE and LE are then transformed
2505          to EQ/GT respectively.  */
2506       gcc_assert (code == EQ || code == GT || code == NE || code == LE);
2507     }
2508
2509   switch (code)
2510     {
2511     case EQ:
2512     case GT:
2513     case GE:
2514     case GTU:
2515     case GEU:
2516       branch_code = code;
2517       break;
2518     case NE:
2519     case LT:
2520     case LE:
2521     case LTU:
2522     case LEU:
2523       branch_code = reverse_condition (code);
2524       break;
2525     default:
2526       gcc_unreachable ();
2527     }
2528
2529   insn = gen_rtx_SET (VOIDmode,
2530                       get_t_reg_rtx (),
2531                       gen_rtx_fmt_ee (branch_code, SImode, op0, op1));
2532
2533   sh_emit_set_t_insn (insn, mode);
2534   if (need_ccmpeq)
2535     sh_emit_set_t_insn (gen_ieee_ccmpeqsf_t (op0, op1), mode);
2536
2537   if (branch_code == code)
2538     emit_jump_insn (gen_branch_true (operands[3]));
2539   else
2540     emit_jump_insn (gen_branch_false (operands[3]));
2541 }
2542
2543 void
2544 sh_emit_compare_and_set (rtx *operands, enum machine_mode mode)
2545 {
2546   enum rtx_code code = GET_CODE (operands[1]);
2547   rtx op0 = operands[2];
2548   rtx op1 = operands[3];
2549   rtx lab = NULL_RTX;
2550   bool invert = false;
2551   rtx tem;
2552
2553   op0 = force_reg (mode, op0);
2554   if ((code != EQ && code != NE
2555        && (op1 != const0_rtx
2556            || code == GTU  || code == GEU || code == LTU || code == LEU))
2557       || (mode == DImode && op1 != const0_rtx)
2558       || (TARGET_SH2E && GET_MODE_CLASS (mode) == MODE_FLOAT))
2559     op1 = force_reg (mode, op1);
2560
2561   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
2562     {
2563       if (code == LT || code == LE)
2564         {
2565           code = swap_condition (code);
2566           tem = op0, op0 = op1, op1 = tem;
2567         }
2568       if (code == GE)
2569         {
2570           if (TARGET_IEEE)
2571             {
2572               lab = gen_label_rtx ();
2573               sh_emit_scc_to_t (EQ, op0, op1);
2574               emit_jump_insn (gen_branch_true (lab));
2575               code = GT;
2576            }
2577           else
2578             {
2579               code = LT;
2580               invert = true;
2581             }
2582         }
2583     }
2584
2585   if (code == NE)
2586     {
2587       code = EQ;
2588       invert = true;
2589     }
2590
2591   sh_emit_scc_to_t (code, op0, op1);
2592   if (lab)
2593     emit_label (lab);
2594   if (invert)
2595     emit_insn (gen_movnegt (operands[0], get_t_reg_rtx ()));
2596   else
2597     emit_move_insn (operands[0], get_t_reg_rtx ());
2598 }
2599 \f
2600 /* Functions to output assembly code.  */
2601
2602 /* Return a sequence of instructions to perform DI or DF move.
2603
2604    Since the SH cannot move a DI or DF in one instruction, we have
2605    to take care when we see overlapping source and dest registers.  */
2606 const char *
2607 output_movedouble (rtx insn ATTRIBUTE_UNUSED, rtx operands[],
2608                    enum machine_mode mode)
2609 {
2610   rtx dst = operands[0];
2611   rtx src = operands[1];
2612
2613   if (MEM_P (dst)
2614       && GET_CODE (XEXP (dst, 0)) == PRE_DEC)
2615     return     "mov.l   %T1,%0" "\n"
2616            "    mov.l   %1,%0";
2617
2618   if (register_operand (dst, mode)
2619       && register_operand (src, mode))
2620     {
2621       if (REGNO (src) == MACH_REG)
2622         return         "sts     mach,%S0" "\n"
2623                "        sts     macl,%R0";
2624
2625       /* When mov.d r1,r2 do r2->r3 then r1->r2;
2626          when mov.d r1,r0 do r1->r0 then r2->r1.  */
2627       if (REGNO (src) + 1 == REGNO (dst))
2628         return         "mov     %T1,%T0" "\n"
2629                "        mov     %1,%0";
2630       else
2631         return         "mov     %1,%0" "\n"
2632                "        mov     %T1,%T0";
2633     }
2634   else if (CONST_INT_P (src))
2635     {
2636       if (INTVAL (src) < 0)
2637         output_asm_insn ("mov   #-1,%S0", operands);
2638       else
2639         output_asm_insn ("mov   #0,%S0", operands);
2640
2641       return "mov       %1,%R0";
2642     }
2643   else if (MEM_P (src))
2644     {
2645       int ptrreg = -1;
2646       int dreg = REGNO (dst);
2647       rtx inside = XEXP (src, 0);
2648
2649       switch (GET_CODE (inside))
2650         {
2651         case REG:
2652           ptrreg = REGNO (inside);
2653           break;
2654
2655         case SUBREG:
2656           ptrreg = subreg_regno (inside);
2657           break;
2658
2659         case PLUS:
2660           ptrreg = REGNO (XEXP (inside, 0));
2661           /* ??? A r0+REG address shouldn't be possible here, because it isn't
2662              an offsettable address.  Unfortunately, offsettable addresses use
2663              QImode to check the offset, and a QImode offsettable address
2664              requires r0 for the other operand, which is not currently
2665              supported, so we can't use the 'o' constraint.
2666              Thus we must check for and handle r0+REG addresses here.
2667              We punt for now, since this is likely very rare.  */
2668           gcc_assert (!REG_P (XEXP (inside, 1)));
2669           break;
2670           
2671         case LABEL_REF:
2672           return       "mov.l   %1,%0" "\n"
2673                  "      mov.l   %1+4,%T0";
2674         case POST_INC:
2675           return       "mov.l   %1,%0" "\n"
2676                  "      mov.l   %1,%T0";
2677         default:
2678           gcc_unreachable ();
2679         }
2680
2681       /* Work out the safe way to copy.  Copy into the second half first.  */
2682       if (dreg == ptrreg)
2683         return         "mov.l   %T1,%T0" "\n"
2684                "        mov.l   %1,%0";
2685     }
2686
2687   return       "mov.l   %1,%0" "\n"
2688          "      mov.l   %T1,%T0";
2689 }
2690
2691 /* Print an instruction which would have gone into a delay slot after
2692    another instruction, but couldn't because the other instruction expanded
2693    into a sequence where putting the slot insn at the end wouldn't work.  */
2694 static void
2695 print_slot (rtx insn)
2696 {
2697   final_scan_insn (XVECEXP (insn, 0, 1), asm_out_file, optimize, 1, NULL);
2698
2699   INSN_DELETED_P (XVECEXP (insn, 0, 1)) = 1;
2700 }
2701
2702 const char *
2703 output_far_jump (rtx insn, rtx op)
2704 {
2705   struct { rtx lab, reg, op; } this_jmp;
2706   rtx braf_base_lab = NULL_RTX;
2707   const char *jump;
2708   int far;
2709   int offset = branch_dest (insn) - INSN_ADDRESSES (INSN_UID (insn));
2710   rtx prev;
2711
2712   this_jmp.lab = gen_label_rtx ();
2713
2714   if (TARGET_SH2
2715       && offset >= -32764
2716       && offset - get_attr_length (insn) <= 32766)
2717     {
2718       far = 0;
2719       jump =   "mov.w   %O0,%1" "\n"
2720              "  braf    %1";
2721     }
2722   else
2723     {
2724       far = 1;
2725       if (flag_pic)
2726         {
2727           if (TARGET_SH2)
2728             jump =     "mov.l   %O0,%1" "\n"
2729                    "    braf    %1";
2730           else
2731             jump =     "mov.l   r0,@-r15"       "\n"
2732                    "    mova    %O0,r0"         "\n"
2733                    "    mov.l   @r0,%1"         "\n"
2734                    "    add     r0,%1"          "\n"
2735                    "    mov.l   @r15+,r0"       "\n"
2736                    "    jmp     @%1";
2737         }
2738       else
2739         jump =         "mov.l   %O0,%1" "\n"
2740                "        jmp     @%1";
2741     }
2742   /* If we have a scratch register available, use it.  */
2743   if (NONJUMP_INSN_P ((prev = prev_nonnote_insn (insn)))
2744       && INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
2745     {
2746       this_jmp.reg = SET_DEST (XVECEXP (PATTERN (prev), 0, 0));
2747       if (REGNO (this_jmp.reg) == R0_REG && flag_pic && ! TARGET_SH2)
2748         jump =         "mov.l   r1,@-r15"       "\n"
2749                "        mova    %O0,r0"         "\n"
2750                "        mov.l   @r0,r1"         "\n"
2751                "        add     r1,r0"          "\n"
2752                "        mov.l   @r15+,r1"       "\n"
2753                "        jmp     @%1";
2754       output_asm_insn (jump, &this_jmp.lab);
2755       if (dbr_sequence_length ())
2756         print_slot (final_sequence);
2757       else
2758         output_asm_insn ("nop", 0);
2759     }
2760   else
2761     {
2762       /* Output the delay slot insn first if any.  */
2763       if (dbr_sequence_length ())
2764         print_slot (final_sequence);
2765
2766       this_jmp.reg = gen_rtx_REG (SImode, 13);
2767       /* We must keep the stack aligned to 8-byte boundaries on SH5.
2768          Fortunately, MACL is fixed and call-clobbered, and we never
2769          need its value across jumps, so save r13 in it instead of in
2770          the stack.  */
2771       if (TARGET_SH5)
2772         output_asm_insn ("lds   r13,macl", 0);
2773       else
2774         output_asm_insn ("mov.l r13,@-r15", 0);
2775       output_asm_insn (jump, &this_jmp.lab);
2776       if (TARGET_SH5)
2777         output_asm_insn ("sts   macl,r13", 0);
2778       else
2779         output_asm_insn ("mov.l @r15+,r13", 0);
2780     }
2781   if (far && flag_pic && TARGET_SH2)
2782     {
2783       braf_base_lab = gen_label_rtx ();
2784       (*targetm.asm_out.internal_label) (asm_out_file, "L",
2785                                  CODE_LABEL_NUMBER (braf_base_lab));
2786     }
2787   if (far)
2788     output_asm_insn (".align    2", 0);
2789   (*targetm.asm_out.internal_label) (asm_out_file, "L", CODE_LABEL_NUMBER (this_jmp.lab));
2790   this_jmp.op = op;
2791   if (far && flag_pic)
2792     {
2793       if (TARGET_SH2)
2794         this_jmp.lab = braf_base_lab;
2795       output_asm_insn (".long   %O2-%O0", &this_jmp.lab);
2796     }
2797   else
2798     output_asm_insn (far ? ".long       %O2" : ".word %O2-%O0", &this_jmp.lab);
2799   return "";
2800 }
2801
2802 /* Local label counter, used for constants in the pool and inside
2803    pattern branches.  */
2804 static int lf = 100;
2805
2806 /* Output code for ordinary branches.  */
2807 const char *
2808 output_branch (int logic, rtx insn, rtx *operands)
2809 {
2810   switch (get_attr_length (insn))
2811     {
2812     case 6:
2813       /* This can happen if filling the delay slot has caused a forward
2814          branch to exceed its range (we could reverse it, but only
2815          when we know we won't overextend other branches; this should
2816          best be handled by relaxation).
2817          It can also happen when other condbranches hoist delay slot insn
2818          from their destination, thus leading to code size increase.
2819          But the branch will still be in the range -4092..+4098 bytes.  */
2820       if (! TARGET_RELAX)
2821         {
2822           int label = lf++;
2823           /* The call to print_slot will clobber the operands.  */
2824           rtx op0 = operands[0];
2825
2826           /* If the instruction in the delay slot is annulled (true), then
2827              there is no delay slot where we can put it now.  The only safe
2828              place for it is after the label.  final will do that by default.  */
2829
2830           if (final_sequence
2831               && ! INSN_ANNULLED_BRANCH_P (XVECEXP (final_sequence, 0, 0))
2832               && get_attr_length (XVECEXP (final_sequence, 0, 1)))
2833             {
2834               asm_fprintf (asm_out_file, "\tb%s%ss\t%LLF%d\n", logic ? "f" : "t",
2835                            ASSEMBLER_DIALECT ? "/" : ".", label);
2836               print_slot (final_sequence);
2837             }
2838           else
2839             asm_fprintf (asm_out_file, "\tb%s\t%LLF%d\n", logic ? "f" : "t", label);
2840
2841           output_asm_insn ("bra\t%l0", &op0);
2842           fprintf (asm_out_file, "\tnop\n");
2843           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
2844
2845           return "";
2846         }
2847       /* When relaxing, handle this like a short branch.  The linker
2848          will fix it up if it still doesn't fit after relaxation.  */
2849     case 2:
2850       return logic ? "bt%.\t%l0" : "bf%.\t%l0";
2851
2852       /* These are for SH2e, in which we have to account for the
2853          extra nop because of the hardware bug in annulled branches.  */
2854     case 8:
2855       if (! TARGET_RELAX)
2856         {
2857           int label = lf++;
2858
2859           gcc_assert (!final_sequence
2860                       || !(INSN_ANNULLED_BRANCH_P
2861                            (XVECEXP (final_sequence, 0, 0))));
2862           asm_fprintf (asm_out_file, "b%s%ss\t%LLF%d\n",
2863                        logic ? "f" : "t",
2864                        ASSEMBLER_DIALECT ? "/" : ".", label);
2865           fprintf (asm_out_file, "\tnop\n");
2866           output_asm_insn ("bra\t%l0", operands);
2867           fprintf (asm_out_file, "\tnop\n");
2868           (*targetm.asm_out.internal_label) (asm_out_file, "LF", label);
2869
2870           return "";
2871         }
2872       /* When relaxing, fall through.  */
2873     case 4:
2874       {
2875         char buffer[10];
2876
2877         sprintf (buffer, "b%s%ss\t%%l0",
2878                  logic ? "t" : "f",
2879                  ASSEMBLER_DIALECT ? "/" : ".");
2880         output_asm_insn (buffer, &operands[0]);
2881         return "nop";
2882       }
2883
2884     default:
2885       /* There should be no longer branches now - that would
2886          indicate that something has destroyed the branches set
2887          up in machine_dependent_reorg.  */
2888       gcc_unreachable ();
2889     }
2890 }
2891
2892 /* Output a code sequence for INSN using TEMPL with OPERANDS; but before,
2893    fill in operands 9 as a label to the successor insn.
2894    We try to use jump threading where possible.
2895    IF CODE matches the comparison in the IF_THEN_ELSE of a following jump,
2896    we assume the jump is taken.  I.e. EQ means follow jmp and bf, NE means
2897    follow jmp and bt, if the address is in range.  */
2898 const char *
2899 output_branchy_insn (enum rtx_code code, const char *templ,
2900                      rtx insn, rtx *operands)
2901 {
2902   rtx next_insn = NEXT_INSN (insn);
2903
2904   if (next_insn && JUMP_P (next_insn) && condjump_p (next_insn))
2905     {
2906       rtx src = SET_SRC (PATTERN (next_insn));
2907       if (GET_CODE (src) == IF_THEN_ELSE && GET_CODE (XEXP (src, 0)) != code)
2908         {
2909           /* Following branch not taken */
2910           operands[9] = gen_label_rtx ();
2911           emit_label_after (operands[9], next_insn);
2912           INSN_ADDRESSES_NEW (operands[9],
2913                               INSN_ADDRESSES (INSN_UID (next_insn))
2914                               + get_attr_length (next_insn));
2915           return templ;
2916         }
2917       else
2918         {
2919           int offset = (branch_dest (next_insn)
2920                         - INSN_ADDRESSES (INSN_UID (next_insn)) + 4);
2921           if (offset >= -252 && offset <= 258)
2922             {
2923               if (GET_CODE (src) == IF_THEN_ELSE)
2924                 /* branch_true */
2925                 src = XEXP (src, 1);
2926               operands[9] = src;
2927               return templ;
2928             }
2929         }
2930     }
2931   operands[9] = gen_label_rtx ();
2932   emit_label_after (operands[9], insn);
2933   INSN_ADDRESSES_NEW (operands[9],
2934                       INSN_ADDRESSES (INSN_UID (insn))
2935                       + get_attr_length (insn));
2936   return templ;
2937 }
2938
2939 const char *
2940 output_ieee_ccmpeq (rtx insn, rtx *operands)
2941 {
2942   return output_branchy_insn (NE,      "bt      %l9" "\n"
2943                                   "     fcmp/eq %1,%0",
2944                               insn, operands);
2945 }
2946 \f
2947 /* Output the start of the assembler file.  */
2948 static void
2949 sh_file_start (void)
2950 {
2951   default_file_start ();
2952
2953   if (TARGET_ELF)
2954     /* We need to show the text section with the proper
2955        attributes as in TEXT_SECTION_ASM_OP, before dwarf2out
2956        emits it without attributes in TEXT_SECTION_ASM_OP, else GAS
2957        will complain.  We can teach GAS specifically about the
2958        default attributes for our choice of text section, but
2959        then we would have to change GAS again if/when we change
2960        the text section name.  */
2961     fprintf (asm_out_file, "%s\n", TEXT_SECTION_ASM_OP);
2962   else
2963     /* Switch to the data section so that the coffsem symbol
2964        isn't in the text section.  */
2965     switch_to_section (data_section);
2966
2967   if (TARGET_LITTLE_ENDIAN)
2968     fputs ("\t.little\n", asm_out_file);
2969
2970   if (!TARGET_ELF)
2971     {
2972       if (TARGET_SHCOMPACT)
2973         fputs ("\t.mode\tSHcompact\n", asm_out_file);
2974       else if (TARGET_SHMEDIA)
2975         fprintf (asm_out_file, "\t.mode\tSHmedia\n\t.abi\t%i\n",
2976                  TARGET_SHMEDIA64 ? 64 : 32);
2977     }
2978 }
2979 \f
2980 /* Check if PAT includes UNSPEC_CALLER unspec pattern.  */
2981 static bool
2982 unspec_caller_rtx_p (rtx pat)
2983 {
2984   rtx base, offset;
2985   int i;
2986
2987   split_const (pat, &base, &offset);
2988   if (GET_CODE (base) == UNSPEC)
2989     {
2990       if (XINT (base, 1) == UNSPEC_CALLER)
2991         return true;
2992       for (i = 0; i < XVECLEN (base, 0); i++)
2993         if (unspec_caller_rtx_p (XVECEXP (base, 0, i)))
2994           return true;
2995     }
2996   return false;
2997 }
2998
2999 /* Indicate that INSN cannot be duplicated.  This is true for insn
3000    that generates a unique label.  */
3001 static bool
3002 sh_cannot_copy_insn_p (rtx insn)
3003 {
3004   rtx pat;
3005
3006   if (!reload_completed || !flag_pic)
3007     return false;
3008
3009   if (!NONJUMP_INSN_P (insn))
3010     return false;
3011   if (asm_noperands (insn) >= 0)
3012     return false;
3013
3014   pat = PATTERN (insn);
3015   if (GET_CODE (pat) != SET)
3016     return false;
3017   pat = SET_SRC (pat);
3018
3019   if (unspec_caller_rtx_p (pat))
3020     return true;
3021
3022   return false;
3023 }
3024 \f
3025 /* Number of instructions used to make an arithmetic right shift by N.  */
3026 static const char ashiftrt_insns[] =
3027   { 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};
3028
3029 /* Description of a logical left or right shift, when expanded to a sequence
3030    of 1/2/8/16 shifts.
3031    Notice that one bit right shifts clobber the T bit.  One bit left shifts
3032    are done with an 'add Rn,Rm' insn and thus do not clobber the T bit.  */
3033 enum
3034 {
3035   ASHL_CLOBBERS_T = 1 << 0,
3036   LSHR_CLOBBERS_T = 1 << 1
3037 };
3038
3039 struct ashl_lshr_sequence
3040 {
3041   char insn_count;
3042   char amount[6];
3043   char clobbers_t;
3044 };
3045
3046 static const struct ashl_lshr_sequence ashl_lshr_seq[32] =
3047 {
3048   { 0, { 0 },               0 },                // 0
3049   { 1, { 1 },               LSHR_CLOBBERS_T },
3050   { 1, { 2 },               0 },
3051   { 2, { 2, 1 },            LSHR_CLOBBERS_T },
3052   { 2, { 2, 2 },            0 },                // 4
3053   { 3, { 2, 1, 2 },         LSHR_CLOBBERS_T },
3054   { 3, { 2, 2, 2 },         0 },
3055   { 4, { 2, 2, 1, 2 },      LSHR_CLOBBERS_T },
3056   { 1, { 8 },               0 },                // 8
3057   { 2, { 8, 1 },            LSHR_CLOBBERS_T },
3058   { 2, { 8, 2 },            0 },
3059   { 3, { 8, 1, 2 },         LSHR_CLOBBERS_T },
3060   { 3, { 8, 2, 2 },         0 },                // 12
3061   { 4, { 8, 2, 1, 2 },      LSHR_CLOBBERS_T },
3062   { 3, { 8, -2, 8 },        0 },
3063   { 3, { 8, -1, 8 },        ASHL_CLOBBERS_T },
3064   { 1, { 16 },              0 },                // 16
3065   { 2, { 16, 1 },           LSHR_CLOBBERS_T },
3066   { 2, { 16, 2 },           0 },
3067   { 3, { 16, 1, 2 },        LSHR_CLOBBERS_T },
3068   { 3, { 16, 2, 2 },        0 },                // 20
3069   { 4, { 16, 2, 1, 2 },     LSHR_CLOBBERS_T },
3070   { 3, { 16, -2, 8 },       0 },
3071   { 3, { 16, -1, 8 },       ASHL_CLOBBERS_T },
3072   { 2, { 16, 8 },           0 },                // 24
3073   { 3, { 16, 1, 8 },        LSHR_CLOBBERS_T },
3074   { 3, { 16, 8, 2 },        0 },
3075   { 4, { 16, 8, 1, 2 },     LSHR_CLOBBERS_T },
3076   { 4, { 16, 8, 2, 2 },     0 },                // 28
3077   { 4, { 16, -1, -2, 16 },  ASHL_CLOBBERS_T },
3078   { 3, { 16, -2, 16 },      0 },
3079
3080   /* For a right shift by 31 a 2 insn shll-movt sequence can be used.
3081      For a left shift by 31 a 2 insn and-rotl sequences can be used.
3082      However, the shift-and combiner code needs this entry here to be in
3083      terms of real shift insns.  */
3084   { 3, { 16, -1, 16 },      ASHL_CLOBBERS_T }
3085 };
3086
3087 /* Individual shift amounts for shift amounts < 16, up to three highmost
3088    bits might be clobbered.  This is typically used when combined with some
3089    kind of sign or zero extension.  */
3090 static const struct ashl_lshr_sequence ext_ashl_lshr_seq[32] =
3091 {
3092   { 0, { 0 },               0 },                // 0
3093   { 1, { 1 },               LSHR_CLOBBERS_T },
3094   { 1, { 2 },               0 },
3095   { 2, { 2, 1 },            LSHR_CLOBBERS_T },
3096   { 2, { 2, 2 },            0 },                // 4
3097   { 3, { 2, 1, 2 },         LSHR_CLOBBERS_T },
3098   { 2, { 8, -2 },           0 },
3099   { 2, { 8, -1 },           ASHL_CLOBBERS_T },
3100   { 1, { 8 },               0 },                // 8
3101   { 2, { 8, 1 },            LSHR_CLOBBERS_T },
3102   { 2, { 8, 2 },            0 },
3103   { 3, { 8, 1, 2 },         LSHR_CLOBBERS_T },
3104   { 3, { 8, 2, 2 },         0 },                // 12
3105   { 3, { 16, -2, -1 },      ASHL_CLOBBERS_T },
3106   { 2, { 16, -2 },          0 },
3107   { 2, { 16, -1 },          ASHL_CLOBBERS_T },
3108   { 1, { 16 },              0 },                // 16
3109   { 2, { 16, 1 },           LSHR_CLOBBERS_T },
3110   { 2, { 16, 2 },           0 },
3111   { 3, { 16, 1, 2 },        LSHR_CLOBBERS_T },
3112   { 3, { 16, 2, 2 },        0 },                // 20
3113   { 4, { 16, 2, 1, 2 },     LSHR_CLOBBERS_T },
3114   { 3, { 16, -2, 8 },       0 },
3115   { 3, { 16, -1, 8 },       ASHL_CLOBBERS_T },
3116   { 2, { 16, 8 },           0 },                // 24
3117   { 3, { 16, 1, 8 },        LSHR_CLOBBERS_T },
3118   { 3, { 16, 8, 2 },        0 },
3119   { 4, { 16, 8, 1, 2 },     LSHR_CLOBBERS_T },
3120   { 4, { 16, 8, 2, 2 },     0 },                // 28
3121   { 4, { 16, -1, -2, 16 },  ASHL_CLOBBERS_T },
3122   { 3, { 16, -2, 16 },      0 },
3123   { 3, { 16, -1, 16 },      ASHL_CLOBBERS_T }
3124 };
3125
3126 /* Return true if a shift left consisting of 1/2/8/16 shift instructions
3127    will clobber the T bit.  */
3128 bool
3129 sh_ashlsi_clobbers_t_reg_p (rtx shift_amount)
3130 {
3131   gcc_assert (CONST_INT_P (shift_amount));
3132   
3133   const int shift_amount_i = INTVAL (shift_amount) & 31;
3134
3135   /* Special case for shift count of 31: use and-rotl sequence.  */
3136   if (shift_amount_i == 31)
3137     return true;
3138
3139   return (ashl_lshr_seq[shift_amount_i].clobbers_t
3140           & ASHL_CLOBBERS_T) != 0;
3141 }
3142
3143 /* Return true if a logical right shift consisting of 1/2/8/16 shift
3144    instructions will clobber the T bit.  */
3145 bool
3146 sh_lshrsi_clobbers_t_reg_p (rtx shift_amount)
3147 {
3148   gcc_assert (CONST_INT_P (shift_amount));
3149
3150   const int shift_amount_i = INTVAL (shift_amount) & 31;
3151  
3152   /* Special case for shift count of 31: use shll-movt sequence.  */
3153   if (shift_amount_i == 31)
3154     return true;
3155
3156   return (ashl_lshr_seq[shift_amount_i].clobbers_t
3157           & LSHR_CLOBBERS_T) != 0;
3158 }
3159
3160 /* Return true if it is potentially beneficial to use a dynamic shift
3161    instruction (shad / shar) instead of a combination of 1/2/8/16 
3162    shift instructions for the specified shift count.
3163    If dynamic shifts are not available, always return false.  */
3164 bool
3165 sh_dynamicalize_shift_p (rtx count)
3166 {
3167   gcc_assert (CONST_INT_P (count));
3168
3169   const int shift_amount_i = INTVAL (count) & 31;
3170   int insn_count;
3171
3172   /* For left and right shifts, there are shorter 2 insn sequences for
3173      shift amounts of 31.  */
3174   if (shift_amount_i == 31)
3175     insn_count = 2;
3176   else
3177     insn_count = ashl_lshr_seq[shift_amount_i].insn_count;
3178
3179   return TARGET_DYNSHIFT && (insn_count > 1 + SH_DYNAMIC_SHIFT_COST);
3180 }
3181
3182 /* Assuming we have a value that has been sign-extended by at least one bit,
3183    can we use the ext_shift_amounts with the last shift turned to an
3184    arithmetic shift to shift it by N without data loss, and quicker than by
3185    other means?  */
3186 #define EXT_SHIFT_SIGNED(n) (((n) | 8) == 15)
3187
3188 /* Return the cost of a shift.  */
3189 static inline int
3190 shiftcosts (rtx x)
3191 {
3192   int value;
3193
3194   if (TARGET_SHMEDIA)
3195     return 1;
3196
3197   if (GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
3198     {
3199       if (GET_MODE (x) == DImode
3200           && CONST_INT_P (XEXP (x, 1))
3201           && INTVAL (XEXP (x, 1)) == 1)
3202         return 2;
3203
3204       /* Everything else is invalid, because there is no pattern for it.  */
3205       return -1;
3206     }
3207   /* If shift by a non constant, then this will be expensive.  */
3208   if (!CONST_INT_P (XEXP (x, 1)))
3209     return SH_DYNAMIC_SHIFT_COST;
3210
3211   /* Otherwise, return the true cost in instructions.  Cope with out of range
3212      shift counts more or less arbitrarily.  */
3213   value = INTVAL (XEXP (x, 1)) & 31;
3214
3215   if (GET_CODE (x) == ASHIFTRT)
3216     {
3217       int cost = ashiftrt_insns[value];
3218       /* If dynamic shifts are available and profitable in this case, then we
3219          put the constant in a reg and use shad.  */
3220       if (cost > 1 + SH_DYNAMIC_SHIFT_COST)
3221         cost = 1 + SH_DYNAMIC_SHIFT_COST;
3222       return cost;
3223     }
3224   else
3225     return ashl_lshr_seq[value].insn_count;
3226 }
3227
3228 /* Return the cost of an AND/XOR/IOR operation.  */
3229 static inline int
3230 and_xor_ior_costs (rtx x, int code)
3231 {
3232   /* On SH1-4 we have only max. SImode operations.
3233      Double the cost for modes > SImode.  */
3234   const int cost_scale = !TARGET_SHMEDIA
3235                          && GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD
3236                          ? 2 : 1;
3237
3238   /* A logical operation with two registers is a single cycle
3239      instruction.  */
3240   if (!CONST_INT_P (XEXP (x, 1)))
3241     return 1 * cost_scale;
3242
3243   int i = INTVAL (XEXP (x, 1));
3244
3245   if (TARGET_SHMEDIA)
3246     {
3247       if (satisfies_constraint_I10 (XEXP (x, 1))
3248           || satisfies_constraint_J16 (XEXP (x, 1)))
3249         return 1;
3250       else
3251         return 1 + rtx_cost (XEXP (x, 1), AND, 1, !optimize_size);
3252     }
3253
3254   /* These constants are single cycle extu.[bw] instructions.  */
3255   if ((i == 0xff || i == 0xffff) && code == AND)
3256     return 1 * cost_scale;
3257   /* Constants that can be used in an instruction as an immediate are
3258      a single cycle, but this requires r0, so make it a little more
3259      expensive.  */
3260   if (CONST_OK_FOR_K08 (i))
3261     return 2 * cost_scale;
3262   /* Constants that can be loaded with a mov immediate need one more cycle.
3263      This case is probably unnecessary.  */
3264   if (CONST_OK_FOR_I08 (i))
3265     return 2 * cost_scale;
3266   /* Any other constant requires an additional 2 cycle pc-relative load.
3267      This case is probably unnecessary.  */
3268   return 3 * cost_scale;
3269 }
3270
3271 /* Return the cost of an addition or a subtraction.  */
3272 static inline int
3273 addsubcosts (rtx x)
3274 {
3275   /* On SH1-4 we have only max. SImode operations.
3276      Double the cost for modes > SImode.  */
3277   const int cost_scale = !TARGET_SHMEDIA
3278                          && GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD
3279                          ? 2 : 1;
3280
3281   /* Adding a register is a single cycle insn.  */
3282   if (REG_P (XEXP (x, 1))
3283       || GET_CODE (XEXP (x, 1)) == SUBREG)
3284     return 1 * cost_scale;
3285
3286   /* Likewise for small constants.  */
3287   if (CONST_INT_P (XEXP (x, 1))
3288       && CONST_OK_FOR_ADD (INTVAL (XEXP (x, 1))))
3289     return 1 * cost_scale;
3290
3291   if (TARGET_SHMEDIA)
3292     switch (GET_CODE (XEXP (x, 1)))
3293       {
3294       case CONST:
3295       case LABEL_REF:
3296       case SYMBOL_REF:
3297         return TARGET_SHMEDIA64 ? 5 : 3;
3298
3299       case CONST_INT:
3300         if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1))))
3301           return 2;
3302         else if (CONST_OK_FOR_I16 (INTVAL (XEXP (x, 1)) >> 16))
3303           return 3;
3304         else if (CONST_OK_FOR_I16 ((INTVAL (XEXP (x, 1)) >> 16) >> 16))
3305           return 4;
3306
3307         /* Fall through.  */
3308       default:
3309         return 5;
3310       }
3311
3312   /* Any other constant requires a 2 cycle pc-relative load plus an
3313      addition.  */
3314   return 3 * cost_scale;
3315 }
3316
3317 /* Return the cost of a multiply.  */
3318 static inline int
3319 multcosts (rtx x ATTRIBUTE_UNUSED)
3320 {
3321   if (sh_multcost >= 0)
3322     return sh_multcost;
3323   if (TARGET_SHMEDIA)
3324     /* ??? We have a mul insn, but it has a latency of three, and doesn't
3325        accept constants.  Ideally, we would use a cost of one or two and
3326        add the cost of the operand, but disregard the latter when inside loops
3327        and loop invariant code motion is still to follow.
3328        Using a multiply first and splitting it later if it's a loss
3329        doesn't work because of different sign / zero extension semantics
3330        of multiplies vs. shifts.  */
3331     return optimize_size ? 2 : 3;
3332
3333   if (TARGET_SH2)
3334     {
3335       /* We have a mul insn, so we can never take more than the mul and the
3336          read of the mac reg, but count more because of the latency and extra
3337          reg usage.  */
3338       if (optimize_size)
3339         return 2;
3340       return 3;
3341     }
3342
3343   /* If we're aiming at small code, then just count the number of
3344      insns in a multiply call sequence.  */
3345   if (optimize_size)
3346     return 5;
3347
3348   /* Otherwise count all the insns in the routine we'd be calling too.  */
3349   return 20;
3350 }
3351
3352 /* Compute a (partial) cost for rtx X.  Return true if the complete
3353    cost has been computed, and false if subexpressions should be
3354    scanned.  In either case, *TOTAL contains the cost result.  */
3355 static bool
3356 sh_rtx_costs (rtx x, int code, int outer_code, int opno ATTRIBUTE_UNUSED,
3357               int *total, bool speed ATTRIBUTE_UNUSED)
3358 {
3359   switch (code)
3360     {
3361       /* The lower-subreg pass decides whether to split multi-word regs
3362          into individual regs by looking at the cost for a SET of certain
3363          modes with the following patterns:
3364            (set (reg) (reg)) 
3365            (set (reg) (const_int 0))
3366          On machines that support vector-move operations a multi-word move
3367          is the same cost as individual reg move.  On SH there is no
3368          vector-move, so we have to provide the correct cost in the number
3369          of move insns to load/store the reg of the mode in question.  */
3370     case SET:
3371       if (register_operand (SET_DEST (x), VOIDmode)
3372             && (register_operand (SET_SRC (x), VOIDmode)
3373                 || satisfies_constraint_Z (SET_SRC (x))))
3374         {
3375           const enum machine_mode mode = GET_MODE (SET_DEST (x));
3376           *total = COSTS_N_INSNS (GET_MODE_SIZE (mode)
3377                                   / mov_insn_size (mode, TARGET_SH2A));
3378           return true;
3379         }
3380       return false;
3381
3382     /* The cost of a mem access is mainly the cost of the address mode.  */
3383     case MEM:
3384       *total = sh_address_cost (XEXP (x, 0), GET_MODE (x), MEM_ADDR_SPACE (x),
3385                                 true);
3386       return true;
3387
3388     /* The cost of a sign or zero extend depends on whether the source is a
3389        reg or a mem.  In case of a mem take the address into acount.  */
3390     case SIGN_EXTEND:
3391       if (REG_P (XEXP (x, 0)))
3392         {
3393           *total = COSTS_N_INSNS (1);
3394           return true;
3395         }
3396       if (MEM_P (XEXP (x, 0)))
3397         {
3398           *total = sh_address_cost (XEXP (XEXP (x, 0), 0),
3399                                     GET_MODE (XEXP (x, 0)),
3400                                     MEM_ADDR_SPACE (XEXP (x, 0)), true);
3401           return true;
3402         }
3403       return false;
3404
3405     case ZERO_EXTEND:
3406       if (REG_P (XEXP (x, 0)))
3407         {
3408           *total = COSTS_N_INSNS (1);
3409           return true;
3410         }
3411       else if (TARGET_SH2A && MEM_P (XEXP (x, 0))
3412                && (GET_MODE (XEXP (x, 0)) == QImode
3413                    || GET_MODE (XEXP (x, 0)) == HImode))
3414         {
3415           /* Handle SH2A's movu.b and movu.w insn.  */
3416           *total = sh_address_cost (XEXP (XEXP (x, 0), 0), 
3417                                     GET_MODE (XEXP (x, 0)), 
3418                                     MEM_ADDR_SPACE (XEXP (x, 0)), true);
3419           return true;
3420         }
3421       return false;
3422
3423     /* mems for SFmode and DFmode can be inside a parallel due to
3424        the way the fpscr is handled.  */
3425     case PARALLEL:
3426       for (int i = 0; i < XVECLEN (x, 0); i++)
3427         {
3428           rtx xx = XVECEXP (x, 0, i);
3429           if (GET_CODE (xx) == SET && MEM_P (XEXP (xx, 0)))
3430             {
3431               *total = sh_address_cost (XEXP (XEXP (xx, 0), 0), 
3432                                         GET_MODE (XEXP (xx, 0)),
3433                                         MEM_ADDR_SPACE (XEXP (xx, 0)), true);
3434               return true;
3435             }
3436           if (GET_CODE (xx) == SET && MEM_P (XEXP (xx, 1)))
3437             {
3438               *total = sh_address_cost (XEXP (XEXP (xx, 1), 0),
3439                                         GET_MODE (XEXP (xx, 1)),
3440                                         MEM_ADDR_SPACE (XEXP (xx, 1)), true);
3441               return true;
3442             }
3443         }
3444
3445       if (sh_1el_vec (x, VOIDmode))
3446         *total = outer_code != SET;
3447       else if (sh_rep_vec (x, VOIDmode))
3448         *total = ((GET_MODE_UNIT_SIZE (GET_MODE (x)) + 3) / 4
3449                   + (outer_code != SET));
3450       else
3451         *total = COSTS_N_INSNS (3) + (outer_code != SET);
3452       return true;
3453
3454     case CONST_INT:
3455       if (TARGET_SHMEDIA)
3456         {
3457           if (INTVAL (x) == 0)
3458             *total = 0;
3459           else if (outer_code == AND && and_operand ((x), DImode))
3460             *total = 0;
3461           else if ((outer_code == IOR || outer_code == XOR
3462                     || outer_code == PLUS)
3463                    && CONST_OK_FOR_I10 (INTVAL (x)))
3464             *total = 0;
3465           else if (CONST_OK_FOR_I16 (INTVAL (x)))
3466             *total = COSTS_N_INSNS (outer_code != SET);
3467           else if (CONST_OK_FOR_I16 (INTVAL (x) >> 16))
3468             *total = COSTS_N_INSNS ((outer_code != SET) + 1);
3469           else if (CONST_OK_FOR_I16 ((INTVAL (x) >> 16) >> 16))
3470             *total = COSTS_N_INSNS ((outer_code != SET) + 2);
3471           else
3472             *total = COSTS_N_INSNS ((outer_code != SET) + 3);
3473           return true;
3474         }
3475       if (CONST_OK_FOR_I08 (INTVAL (x)))
3476         *total = 0;
3477       else if ((outer_code == AND || outer_code == IOR || outer_code == XOR)
3478                && CONST_OK_FOR_K08 (INTVAL (x)))
3479         *total = 1;
3480       /* prepare_cmp_insn will force costly constants int registers before
3481          the cbranch[sd]i4 patterns can see them, so preserve potentially
3482          interesting ones not covered by I08 above.  */
3483       else if (outer_code == COMPARE
3484                && ((unsigned HOST_WIDE_INT) INTVAL (x)
3485                     == (unsigned HOST_WIDE_INT) 0x7fffffff + 1
3486                     || INTVAL (x) == 0x7fffffff
3487                    || INTVAL (x) == 0x80 || INTVAL (x) == -0x81))
3488         *total = 1;
3489       else
3490         *total = 8;
3491       return true;
3492
3493     case EQ:
3494       /* An and with a constant compared against zero is
3495          most likely going to be a TST #imm, R0 instruction.
3496          Notice that this does not catch the zero_extract variants from
3497          the md file.  */
3498       if (GET_CODE (XEXP (x, 0)) == AND
3499           && CONST_INT_P (XEXP (x, 1)) && INTVAL (XEXP (x, 1)) == 0)
3500         {
3501           *total = 1;
3502           return true;
3503         }
3504       else
3505         return false;
3506
3507     case CONST:
3508     case LABEL_REF:
3509     case SYMBOL_REF:
3510       if (TARGET_SHMEDIA64)
3511         *total = COSTS_N_INSNS (4);
3512       else if (TARGET_SHMEDIA32)
3513         *total = COSTS_N_INSNS (2);
3514       else
3515         *total = 5;
3516       return true;
3517
3518     case CONST_DOUBLE:
3519       if (TARGET_SHMEDIA)
3520         *total = COSTS_N_INSNS (4);
3521       /* prepare_cmp_insn will force costly constants int registers before
3522          the cbranchdi4 pattern can see them, so preserve potentially
3523          interesting ones.  */
3524       else if (outer_code == COMPARE && GET_MODE (x) == DImode)
3525         *total = 1;
3526       else
3527         *total = 10;
3528       return true;
3529
3530     case CONST_VECTOR:
3531     /* FIXME: This looks broken.  Only the last statement has any effect.
3532        Probably this could be folded with the PARALLEL case?  */
3533       if (x == CONST0_RTX (GET_MODE (x)))
3534         *total = 0;
3535       else if (sh_1el_vec (x, VOIDmode))
3536         *total = outer_code != SET;
3537       if (sh_rep_vec (x, VOIDmode))
3538         *total = ((GET_MODE_UNIT_SIZE (GET_MODE (x)) + 3) / 4
3539                   + (outer_code != SET));
3540       *total = COSTS_N_INSNS (3) + (outer_code != SET);
3541       return true;
3542
3543     case PLUS:
3544     case MINUS:
3545       *total = COSTS_N_INSNS (addsubcosts (x));
3546       return true;
3547
3548     case AND:
3549     case XOR:
3550     case IOR:
3551       *total = COSTS_N_INSNS (and_xor_ior_costs (x, code));
3552       return true;
3553
3554     case MULT:
3555       *total = COSTS_N_INSNS (multcosts (x));
3556       return true;
3557
3558     case LT:
3559     case GE:
3560       /* div0s sign comparison.  */
3561       if (GET_CODE (XEXP (x, 0)) == XOR
3562           && REG_P ((XEXP (XEXP (x, 0), 0)))
3563           && REG_P ((XEXP (XEXP (x, 0), 1)))
3564           && satisfies_constraint_Z (XEXP (x, 1)))
3565         {
3566           *total = COSTS_N_INSNS (1);
3567           return true;
3568         }
3569       else
3570         return false;
3571
3572     case LSHIFTRT:
3573       /* div0s sign comparison.  */
3574       if (GET_CODE (XEXP (x, 0)) == XOR
3575           && REG_P ((XEXP (XEXP (x, 0), 0)))
3576           && REG_P ((XEXP (XEXP (x, 0), 1)))
3577           && CONST_INT_P (XEXP (x, 1)) && INTVAL (XEXP (x, 1)) == 31)
3578         {
3579           *total = COSTS_N_INSNS (1);
3580           return true;
3581         }
3582       /* Fall through to shiftcosts.  */
3583     case ASHIFT:
3584     case ASHIFTRT:
3585       {
3586         int cost = shiftcosts (x);
3587         if (cost < 0)
3588           return false;
3589         *total = COSTS_N_INSNS (cost);
3590         return true;
3591       }
3592
3593     case DIV:
3594     case UDIV:
3595     case MOD:
3596     case UMOD:
3597       *total = COSTS_N_INSNS (20);
3598       return true;
3599
3600     case FLOAT:
3601     case FIX:
3602       *total = 100;
3603       return true;
3604
3605     default:
3606       return false;
3607     }
3608 }
3609
3610 /* Determine the size of the fundamental move insn that will be used
3611    for the specified mode.  */
3612 static inline int
3613 mov_insn_size (enum machine_mode mode, bool consider_sh2a)
3614 {
3615   const int mode_sz = GET_MODE_SIZE (mode);
3616
3617   if ((consider_sh2a && TARGET_SH2A_DOUBLE && mode == DFmode)
3618       || (TARGET_FMOVD && mode == DFmode))
3619     return mode_sz;
3620   else
3621     {
3622       /* The max. available mode for actual move insns is SImode.
3623          Larger accesses will be split into multiple loads/stores.  */
3624       const int max_mov_sz = GET_MODE_SIZE (SImode);
3625       return mode_sz >= max_mov_sz ? max_mov_sz : mode_sz;
3626     }
3627 }
3628
3629 /* Determine the maximum possible displacement for a move insn for the
3630    specified mode.  */
3631 static int
3632 max_mov_insn_displacement (enum machine_mode mode, bool consider_sh2a)
3633 {
3634   /* The 4 byte displacement move insns are the same as the 2 byte
3635      versions but take a 12 bit displacement.  All we need to do is to
3636      scale the max. displacement value accordingly.  */
3637   const int disp_scale = consider_sh2a ? (4095 / 15) : 1;
3638
3639   /* SH2A supports FPU move insns with 12 bit displacements.
3640      Other variants to do not support any kind of displacements for
3641      FPU move insns.  */
3642   if (! consider_sh2a && TARGET_FPU_ANY && GET_MODE_CLASS (mode) == MODE_FLOAT)
3643     return 0;
3644   else
3645     {
3646       const int mov_insn_sz = mov_insn_size (mode, consider_sh2a);
3647       const int mode_sz = GET_MODE_SIZE (mode);
3648       int r = 15 * mov_insn_sz * disp_scale;
3649     
3650       /* If the mov insn will be split into multiple loads/stores, the
3651          maximum possible displacement is a bit smaller.  */
3652       if (mode_sz > mov_insn_sz)
3653         r -= mode_sz - mov_insn_sz;
3654       return r;
3655     }
3656 }
3657
3658 /* Determine the alignment mask for a move insn of the
3659    specified mode.  */
3660 static inline int
3661 mov_insn_alignment_mask (enum machine_mode mode, bool consider_sh2a)
3662 {
3663   const int mov_insn_sz = mov_insn_size (mode, consider_sh2a);
3664   return mov_insn_sz > 0 ? (mov_insn_sz - 1) : 0;
3665 }
3666
3667 /* Return the displacement value of a displacement address.  */
3668 static inline HOST_WIDE_INT
3669 disp_addr_displacement (rtx x)
3670 {
3671   gcc_assert (satisfies_constraint_Sdd (x));
3672   return INTVAL (XEXP (XEXP (x, 0), 1));
3673 }
3674
3675 /* Compute the cost of an address.  */
3676 static int
3677 sh_address_cost (rtx x, enum machine_mode mode,
3678                  addr_space_t as ATTRIBUTE_UNUSED, bool speed ATTRIBUTE_UNUSED)
3679 {
3680   /* 'GBR + 0'.  Account one more because of R0 restriction.  */
3681   if (REG_P (x) && REGNO (x) == GBR_REG)
3682     return 2;
3683
3684   /* Simple reg, post-inc, pre-dec addressing.  */
3685   if (REG_P (x) || GET_CODE (x) == POST_INC || GET_CODE (x) == PRE_DEC)
3686     return 1;
3687
3688   /* 'reg + disp' addressing.  */
3689   if (GET_CODE (x) == PLUS
3690       && REG_P (XEXP (x, 0)) && CONST_INT_P (XEXP (x, 1)))
3691     {
3692       /* 'GBR + disp'.  Account one more because of R0 restriction.  */
3693       if (REGNO (XEXP (x, 0)) == GBR_REG
3694           && gbr_displacement (XEXP (x, 1), mode))
3695         return 2;
3696
3697       const HOST_WIDE_INT offset = INTVAL (XEXP (x, 1));
3698
3699       if (offset == 0)
3700         return 1;
3701
3702       /* The displacement would fit into a 2 byte move insn.
3703          HImode and QImode loads/stores with displacement put pressure on
3704          R0 which will most likely require another reg copy.  Thus account
3705          a higher cost for that.  */
3706       if (offset > 0 && offset <= max_mov_insn_displacement (mode, false))
3707         return (mode == HImode || mode == QImode) ? 2 : 1;
3708
3709       /* The displacement would fit into a 4 byte move insn (SH2A).  */
3710       if (TARGET_SH2A
3711           && offset > 0 && offset <= max_mov_insn_displacement (mode, true))
3712         return 2;
3713
3714       /* The displacement is probably out of range and will require extra
3715          calculations.  */
3716       return 3;
3717     }
3718
3719   /* 'reg + reg' addressing.  Account a slightly higher cost because of 
3720      increased pressure on R0.  */
3721   if (GET_CODE (x) == PLUS && ! CONSTANT_P (XEXP (x, 1))
3722       && ! TARGET_SHMEDIA)
3723     return 3;
3724
3725   /* Not sure what it is - probably expensive.  */
3726   return 10;
3727 }
3728
3729 /* Code to expand a shift.  */
3730 static void
3731 gen_ashift (int type, int n, rtx reg)
3732 {
3733   rtx n_rtx;
3734
3735   /* Negative values here come from the shift_amounts array.  */
3736   if (n < 0)
3737     {
3738       if (type == ASHIFT)
3739         type = LSHIFTRT;
3740       else
3741         type = ASHIFT;
3742       n = -n;
3743     }
3744
3745   n_rtx = GEN_INT (n);
3746   gcc_assert (satisfies_constraint_P27 (n_rtx));
3747
3748   switch (type)
3749     {
3750     case ASHIFTRT:
3751       emit_insn (gen_ashrsi3_k (reg, reg, n_rtx));
3752       break;
3753     case LSHIFTRT:
3754       if (n == 1)
3755         emit_insn (gen_shlr (reg, reg));
3756       else
3757         emit_insn (gen_lshrsi3_k (reg, reg, n_rtx));
3758       break;
3759     case ASHIFT:
3760       emit_insn (gen_ashlsi3_k (reg, reg, n_rtx));
3761       break;
3762     default:
3763       gcc_unreachable ();
3764     }
3765 }
3766
3767 /* Code to expand a HImode shift.  */
3768 static void
3769 gen_ashift_hi (int type, int n, rtx reg)
3770 {
3771   /* Negative values here come from the shift_amounts array.  */
3772   if (n < 0)
3773     {
3774       if (type == ASHIFT)
3775         type = LSHIFTRT;
3776       else
3777         type = ASHIFT;
3778       n = -n;
3779     }
3780
3781   switch (type)
3782     {
3783     case ASHIFTRT:
3784     case LSHIFTRT:
3785       /* We don't have HImode right shift operations because using the
3786          ordinary 32 bit shift instructions for that doesn't generate proper
3787          zero/sign extension.
3788          gen_ashift_hi is only called in contexts where we know that the
3789          sign extension works out correctly.  */
3790       {
3791         int offset = 0;
3792         if (GET_CODE (reg) == SUBREG)
3793           {
3794             offset = SUBREG_BYTE (reg);
3795             reg = SUBREG_REG (reg);
3796           }
3797         gen_ashift (type, n, gen_rtx_SUBREG (SImode, reg, offset));
3798         break;
3799       }
3800     case ASHIFT:
3801       emit_insn (gen_ashlhi3_k (reg, reg, GEN_INT (n)));
3802       break;
3803     }
3804 }
3805
3806 /* Output RTL to split a constant shift into its component SH constant
3807    shift instructions.  */
3808 void
3809 gen_shifty_op (int code, rtx *operands)
3810 {
3811   int value = INTVAL (operands[2]);
3812   int max, i;
3813
3814   /* Truncate the shift count in case it is out of bounds.  */
3815   value = value & 31;
3816
3817   if (value == 31)
3818     {
3819       if (code == LSHIFTRT)
3820         {
3821           emit_insn (gen_rotlsi3_1 (operands[0], operands[0]));
3822           emit_insn (gen_movt (operands[0], get_t_reg_rtx ()));
3823           return;
3824         }
3825       else if (code == ASHIFT)
3826         {
3827           /* There is a two instruction sequence for 31 bit left shifts,
3828              but it requires r0.  */
3829           if (REG_P (operands[0]) && REGNO (operands[0]) == 0)
3830             {
3831               emit_insn (gen_andsi3 (operands[0], operands[0], const1_rtx));
3832               emit_insn (gen_rotlsi3_31 (operands[0], operands[0]));
3833               return;
3834             }
3835         }
3836     }
3837   else if (value == 0)
3838     {
3839       /* This can happen even when optimizing, if there were subregs before
3840          reload.  Don't output a nop here, as this is never optimized away;
3841          use a no-op move instead.  */
3842       emit_insn (gen_rtx_SET (VOIDmode, operands[0], operands[0]));
3843       return;
3844     }
3845
3846   max = ashl_lshr_seq[value].insn_count;
3847   for (i = 0; i < max; i++)
3848     gen_ashift (code, ashl_lshr_seq[value].amount[i], operands[0]);
3849 }
3850
3851 /* Same as gen_shifty_op, but optimized for values where the topmost bits
3852    don't matter.  */
3853 void
3854 gen_shifty_hi_op (int code, rtx *operands)
3855 {
3856   int value = INTVAL (operands[2]);
3857   int max, i;
3858   void (*gen_fun) (int, int, rtx);
3859
3860   /* This operation is used by and_shl for SImode values with a few
3861      high bits known to be cleared.  */
3862   value &= 31;
3863   if (value == 0)
3864     {
3865       emit_insn (gen_nop ());
3866       return;
3867     }
3868
3869   gen_fun = GET_MODE (operands[0]) == HImode ? gen_ashift_hi : gen_ashift;
3870   if (code == ASHIFT)
3871     {
3872       max = ext_ashl_lshr_seq[value].insn_count;
3873       for (i = 0; i < max; i++)
3874         gen_fun (code, ext_ashl_lshr_seq[value].amount[i], operands[0]);
3875     }
3876   else
3877     /* When shifting right, emit the shifts in reverse order, so that
3878        solitary negative values come first.  */
3879     for (i = ext_ashl_lshr_seq[value].insn_count - 1; i >= 0; i--)
3880       gen_fun (code, ext_ashl_lshr_seq[value].amount[i], operands[0]);
3881 }
3882
3883 /* Output RTL for an arithmetic right shift.
3884    ??? Rewrite to use super-optimizer sequences.  */
3885 bool
3886 expand_ashiftrt (rtx *operands)
3887 {
3888   rtx wrk;
3889   char func[18];
3890   int value;
3891
3892   if (TARGET_DYNSHIFT)
3893     {
3894       if (!CONST_INT_P (operands[2]))
3895         {
3896           rtx count = copy_to_mode_reg (SImode, operands[2]);
3897           emit_insn (gen_negsi2 (count, count));
3898           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
3899           return true;
3900         }
3901       else if (ashiftrt_insns[INTVAL (operands[2]) & 31]
3902                > 1 + SH_DYNAMIC_SHIFT_COST)
3903         {
3904           rtx count
3905             = force_reg (SImode, GEN_INT (- (INTVAL (operands[2]) & 31)));
3906           emit_insn (gen_ashrsi3_d (operands[0], operands[1], count));
3907           return true;
3908         }
3909     }
3910   if (!CONST_INT_P (operands[2]))
3911     return false;
3912
3913   value = INTVAL (operands[2]) & 31;
3914
3915   if (value == 31)
3916     {
3917       /* If we are called from abs expansion, arrange things so that we
3918          we can use a single MT instruction that doesn't clobber the source,
3919          if LICM can hoist out the load of the constant zero.  */
3920       if (currently_expanding_to_rtl)
3921         {
3922           emit_insn (gen_cmpgtsi_t (force_reg (SImode, CONST0_RTX (SImode)),
3923                                     operands[1]));
3924           emit_insn (gen_mov_neg_si_t (operands[0], get_t_reg_rtx ()));
3925           return true;
3926         }
3927       emit_insn (gen_ashrsi2_31 (operands[0], operands[1]));
3928       return true;
3929     }
3930   else if (value >= 16 && value <= 19)
3931     {
3932       wrk = gen_reg_rtx (SImode);
3933       emit_insn (gen_ashrsi2_16 (wrk, operands[1]));
3934       value -= 16;
3935       while (value--)
3936         gen_ashift (ASHIFTRT, 1, wrk);
3937       emit_move_insn (operands[0], wrk);
3938       return true;
3939     }
3940   /* Expand a short sequence inline, longer call a magic routine.  */
3941   else if (value <= 5)
3942     {
3943       wrk = gen_reg_rtx (SImode);
3944       emit_move_insn (wrk, operands[1]);
3945       while (value--)
3946         gen_ashift (ASHIFTRT, 1, wrk);
3947       emit_move_insn (operands[0], wrk);
3948       return true;
3949     }
3950
3951   wrk = gen_reg_rtx (Pmode);
3952
3953   /* Load the value into an arg reg and call a helper.  */
3954   emit_move_insn (gen_rtx_REG (SImode, 4), operands[1]);
3955   sprintf (func, "__ashiftrt_r4_%d", value);
3956   function_symbol (wrk, func, SFUNC_STATIC);
3957   emit_insn (gen_ashrsi3_n (GEN_INT (value), wrk));
3958   emit_move_insn (operands[0], gen_rtx_REG (SImode, 4));
3959   return true;
3960 }
3961
3962 /* Try to find a good way to implement the combiner pattern
3963   [(set (match_operand:SI 0 "register_operand" "r")
3964         (and:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
3965                            (match_operand:SI 2 "const_int_operand" "n"))
3966                 (match_operand:SI 3 "const_int_operand" "n"))) .
3967   LEFT_RTX is operand 2 in the above pattern, and MASK_RTX is operand 3.
3968   return 0 for simple right / left or left/right shift combination.
3969   return 1 for a combination of shifts with zero_extend.
3970   return 2 for a combination of shifts with an AND that needs r0.
3971   return 3 for a combination of shifts with an AND that needs an extra
3972     scratch register, when the three highmost bits of the AND mask are clear.
3973   return 4 for a combination of shifts with an AND that needs an extra
3974     scratch register, when any of the three highmost bits of the AND mask
3975     is set.
3976   If ATTRP is set, store an initial right shift width in ATTRP[0],
3977   and the instruction length in ATTRP[1] .  These values are not valid
3978   when returning 0.
3979   When ATTRP is set and returning 1, ATTRP[2] gets set to the index into
3980   shift_amounts for the last shift value that is to be used before the
3981   sign extend.  */
3982 int
3983 shl_and_kind (rtx left_rtx, rtx mask_rtx, int *attrp)
3984 {
3985   unsigned HOST_WIDE_INT mask, lsb, mask2, lsb2;
3986   int left = INTVAL (left_rtx), right;
3987   int best = 0;
3988   int cost, best_cost = 10000;
3989   int best_right = 0, best_len = 0;
3990   int i;
3991   int can_ext;
3992
3993   if (left < 0 || left > 31)
3994     return 0;
3995   if (CONST_INT_P (mask_rtx))
3996     mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> left;
3997   else
3998     mask = (unsigned HOST_WIDE_INT) GET_MODE_MASK (SImode) >> left;
3999   /* Can this be expressed as a right shift / left shift pair?  */
4000   lsb = ((mask ^ (mask - 1)) >> 1) + 1;
4001   right = exact_log2 (lsb);
4002   mask2 = ~(mask + lsb - 1);
4003   lsb2 = ((mask2 ^ (mask2 - 1)) >> 1) + 1;
4004   /* mask has no zeroes but trailing zeroes <==> ! mask2 */
4005   if (! mask2)
4006     best_cost = ashl_lshr_seq[right].insn_count
4007                 + ashl_lshr_seq[right + left].insn_count;
4008   /* mask has no trailing zeroes <==> ! right */
4009   else if (! right && mask2 == ~(lsb2 - 1))
4010     {
4011       int late_right = exact_log2 (lsb2);
4012       best_cost = ashl_lshr_seq[left + late_right].insn_count
4013                   + ashl_lshr_seq[late_right].insn_count;
4014     }
4015   /* Try to use zero extend.  */
4016   if (mask2 == ~(lsb2 - 1))
4017     {
4018       int width, first;
4019
4020       for (width = 8; width <= 16; width += 8)
4021         {
4022           /* Can we zero-extend right away?  */
4023           if (lsb2 == (unsigned HOST_WIDE_INT) 1 << width)
4024             {
4025               cost = 1 + ext_ashl_lshr_seq[right].insn_count
4026                        + ext_ashl_lshr_seq[left + right].insn_count;
4027               if (cost < best_cost)
4028                 {
4029                   best = 1;
4030                   best_cost = cost;
4031                   best_right = right;
4032                   best_len = cost;
4033                   if (attrp)
4034                     attrp[2] = -1;
4035                 }
4036               continue;
4037             }
4038           /* ??? Could try to put zero extend into initial right shift,
4039              or even shift a bit left before the right shift.  */
4040           /* Determine value of first part of left shift, to get to the
4041              zero extend cut-off point.  */
4042           first = width - exact_log2 (lsb2) + right;
4043           if (first >= 0 && right + left - first >= 0)
4044             {
4045               cost = ext_ashl_lshr_seq[right].insn_count
4046                      + ext_ashl_lshr_seq[first].insn_count + 1
4047                      + ext_ashl_lshr_seq[right + left - first].insn_count;
4048
4049               if (cost < best_cost)
4050                 {
4051                   best = 1;
4052                   best_cost = cost;
4053                   best_right = right;
4054                   best_len = cost;
4055                   if (attrp)
4056                     attrp[2] = first;
4057                 }
4058             }
4059         }
4060     }
4061   /* Try to use r0 AND pattern */
4062   for (i = 0; i <= 2; i++)
4063     {
4064       if (i > right)
4065         break;
4066       if (! CONST_OK_FOR_K08 (mask >> i))
4067         continue;
4068       cost = (i != 0) + 2 + ext_ashl_lshr_seq[left + i].insn_count;
4069       if (cost < best_cost)
4070         {
4071           best = 2;
4072           best_cost = cost;
4073           best_right = i;
4074           best_len = cost - 1;
4075         }
4076     }
4077   /* Try to use a scratch register to hold the AND operand.  */
4078   can_ext = ((mask << left) & ((unsigned HOST_WIDE_INT) 3 << 30)) == 0;
4079   for (i = 0; i <= 2; i++)
4080     {
4081       if (i > right)
4082         break;
4083       cost = (i != 0) + (CONST_OK_FOR_I08 (mask >> i) ? 2 : 3)
4084              + (can_ext
4085                 ? ext_ashl_lshr_seq
4086                 : ashl_lshr_seq)[left + i].insn_count;
4087       if (cost < best_cost)
4088         {
4089           best = 4 - can_ext;
4090           best_cost = cost;
4091           best_right = i;
4092           best_len = cost - 1 - ! CONST_OK_FOR_I08 (mask >> i);
4093         }
4094     }
4095
4096   if (attrp)
4097     {
4098       attrp[0] = best_right;
4099       attrp[1] = best_len;
4100     }
4101   return best;
4102 }
4103
4104 /* This is used in length attributes of the unnamed instructions
4105    corresponding to shl_and_kind return values of 1 and 2.  */
4106 int
4107 shl_and_length (rtx insn)
4108 {
4109   rtx set_src, left_rtx, mask_rtx;
4110   int attributes[3];
4111
4112   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
4113   left_rtx = XEXP (XEXP (set_src, 0), 1);
4114   mask_rtx = XEXP (set_src, 1);
4115   shl_and_kind (left_rtx, mask_rtx, attributes);
4116   return attributes[1];
4117 }
4118
4119 /* This is used in length attribute of the and_shl_scratch instruction.  */
4120 int
4121 shl_and_scr_length (rtx insn)
4122 {
4123   rtx set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
4124   int len = ashl_lshr_seq[INTVAL (XEXP (set_src, 1)) & 31].insn_count;
4125   rtx op = XEXP (set_src, 0);
4126   len += ashl_lshr_seq[INTVAL (XEXP (op, 1)) & 31].insn_count + 1;
4127   op = XEXP (XEXP (op, 0), 0);
4128   return len + ashl_lshr_seq[INTVAL (XEXP (op, 1)) & 31].insn_count;
4129 }
4130
4131 /* Generate rtl for instructions for which shl_and_kind advised a particular
4132    method of generating them, i.e. returned zero.  */
4133 bool
4134 gen_shl_and (rtx dest, rtx left_rtx, rtx mask_rtx, rtx source)
4135 {
4136   int attributes[3];
4137   unsigned HOST_WIDE_INT mask;
4138   int kind = shl_and_kind (left_rtx, mask_rtx, attributes);
4139   int right, total_shift;
4140   void (*shift_gen_fun) (int, rtx *) = gen_shifty_hi_op;
4141
4142   right = attributes[0];
4143   total_shift = INTVAL (left_rtx) + right;
4144   mask = (unsigned HOST_WIDE_INT) INTVAL (mask_rtx) >> total_shift;
4145   switch (kind)
4146     {
4147     default:
4148       return true;
4149     case 1:
4150       {
4151         int first = attributes[2];
4152         rtx operands[3];
4153
4154         if (first < 0)
4155           {
4156             emit_insn ((mask << right) <= 0xff
4157                        ? gen_zero_extendqisi2 (dest,
4158                                                gen_lowpart (QImode, source))
4159                        : gen_zero_extendhisi2 (dest,
4160                                                gen_lowpart (HImode, source)));
4161             source = dest;
4162           }
4163         if (source != dest)
4164           emit_insn (gen_movsi (dest, source));
4165         operands[0] = dest;
4166         if (right)
4167           {
4168             operands[2] = GEN_INT (right);
4169             gen_shifty_hi_op (LSHIFTRT, operands);
4170           }
4171         if (first > 0)
4172           {
4173             operands[2] = GEN_INT (first);
4174             gen_shifty_hi_op (ASHIFT, operands);
4175             total_shift -= first;
4176             mask <<= first;
4177           }
4178         if (first >= 0)
4179           emit_insn (mask <= 0xff
4180                      ? gen_zero_extendqisi2 (dest, gen_lowpart (QImode, dest))
4181                      : gen_zero_extendhisi2 (dest, gen_lowpart (HImode, dest)));
4182         if (total_shift > 0)
4183           {
4184             operands[2] = GEN_INT (total_shift);
4185             gen_shifty_hi_op (ASHIFT, operands);
4186           }
4187         break;
4188       }
4189     case 4:
4190       shift_gen_fun = gen_shifty_op;
4191     case 3:
4192       /* If the topmost bit that matters is set, set the topmost bits
4193          that don't matter.  This way, we might be able to get a shorter
4194          signed constant.  */
4195       if (mask & ((HOST_WIDE_INT) 1 << (31 - total_shift)))
4196         mask |= (HOST_WIDE_INT) ~0 << (31 - total_shift);
4197     case 2:
4198       /* Don't expand fine-grained when combining, because that will
4199          make the pattern fail.  */
4200       if (currently_expanding_to_rtl
4201           || reload_in_progress || reload_completed)
4202         {
4203           rtx operands[3];
4204
4205           /* Cases 3 and 4 should be handled by this split
4206              only while combining  */
4207           gcc_assert (kind <= 2);
4208           if (right)
4209             {
4210               emit_insn (gen_lshrsi3 (dest, source, GEN_INT (right)));
4211               source = dest;
4212             }
4213           emit_insn (gen_andsi3 (dest, source, GEN_INT (mask)));
4214           if (total_shift)
4215             {
4216               operands[0] = dest;
4217               operands[1] = dest;
4218               operands[2] = GEN_INT (total_shift);
4219               shift_gen_fun (ASHIFT, operands);
4220             }
4221           break;
4222         }
4223       else
4224         {
4225           int neg = 0;
4226           if (kind != 4 && total_shift < 16)
4227             {
4228               neg = -ext_ashl_lshr_seq[total_shift].amount[1];
4229               if (neg > 0)
4230                 neg -= ext_ashl_lshr_seq[total_shift].amount[2];
4231               else
4232                 neg = 0;
4233             }
4234           emit_insn (gen_and_shl_scratch (dest, source,
4235                                           GEN_INT (right),
4236                                           GEN_INT (mask),
4237                                           GEN_INT (total_shift + neg),
4238                                           GEN_INT (neg)));
4239           emit_insn (gen_movsi (dest, dest));
4240           break;
4241         }
4242     }
4243   return false;
4244 }
4245
4246 /* Try to find a good way to implement the combiner pattern
4247   [(set (match_operand:SI 0 "register_operand" "=r")
4248         (sign_extract:SI (ashift:SI (match_operand:SI 1 "register_operand" "r")
4249                                     (match_operand:SI 2 "const_int_operand" "n")
4250                          (match_operand:SI 3 "const_int_operand" "n")
4251                          (const_int 0)))
4252    (clobber (reg:SI T_REG))]
4253   LEFT_RTX is operand 2 in the above pattern, and SIZE_RTX is operand 3.
4254   return 0 for simple left / right shift combination.
4255   return 1 for left shift / 8 bit sign extend / left shift.
4256   return 2 for left shift / 16 bit sign extend / left shift.
4257   return 3 for left shift / 8 bit sign extend / shift / sign extend.
4258   return 4 for left shift / 16 bit sign extend / shift / sign extend.
4259   return 5 for left shift / 16 bit sign extend / right shift
4260   return 6 for < 8 bit sign extend / left shift.
4261   return 7 for < 8 bit sign extend / left shift / single right shift.
4262   If COSTP is nonzero, assign the calculated cost to *COSTP.  */
4263 int
4264 shl_sext_kind (rtx left_rtx, rtx size_rtx, int *costp)
4265 {
4266   int left, size, insize, ext;
4267   int cost = 0, best_cost;
4268   int kind;
4269
4270   left = INTVAL (left_rtx);
4271   size = INTVAL (size_rtx);
4272   insize = size - left;
4273   gcc_assert (insize > 0);
4274   /* Default to left / right shift.  */
4275   kind = 0;
4276   best_cost = ashl_lshr_seq[32 - insize].insn_count
4277               + ashl_lshr_seq[32 - size].insn_count;
4278   if (size <= 16)
4279     {
4280       /* 16 bit shift / sign extend / 16 bit shift */
4281       cost = ashl_lshr_seq[16 - insize].insn_count + 1
4282              + ashl_lshr_seq[16 - size].insn_count;
4283       /* If ashiftrt_insns[16 - size] is 8, this choice will be overridden
4284          below, by alternative 3 or something even better.  */
4285       if (cost < best_cost)
4286         {
4287           kind = 5;
4288           best_cost = cost;
4289         }
4290     }
4291   /* Try a plain sign extend between two shifts.  */
4292   for (ext = 16; ext >= insize; ext -= 8)
4293     {
4294       if (ext <= size)
4295         {
4296           cost = ext_ashl_lshr_seq[ext - insize].insn_count + 1
4297                  + ashl_lshr_seq[size - ext].insn_count;
4298           if (cost < best_cost)
4299             {
4300               kind = ext / (unsigned) 8;
4301               best_cost = cost;
4302             }
4303         }
4304       /* Check if we can do a sloppy shift with a final signed shift
4305          restoring the sign.  */
4306       if (EXT_SHIFT_SIGNED (size - ext))
4307         cost = ext_ashl_lshr_seq[ext - insize].insn_count
4308                + ext_ashl_lshr_seq[size - ext].insn_count + 1;
4309       /* If not, maybe it's still cheaper to do the second shift sloppy,
4310          and do a final sign extend?  */
4311       else if (size <= 16)
4312         cost = ext_ashl_lshr_seq[ext - insize].insn_count + 1
4313           + ext_ashl_lshr_seq[size > ext ? size - ext : ext - size].insn_count
4314           + 1;
4315       else
4316         continue;
4317       if (cost < best_cost)
4318         {
4319           kind = ext / (unsigned) 8 + 2;
4320           best_cost = cost;
4321         }
4322     }
4323   /* Check if we can sign extend in r0 */
4324   if (insize < 8)
4325     {
4326       cost = 3 + ashl_lshr_seq[left].insn_count;
4327       if (cost < best_cost)
4328         {
4329           kind = 6;
4330           best_cost = cost;
4331         }
4332       /* Try the same with a final signed shift.  */
4333       if (left < 31)
4334         {
4335           cost = 3 + ext_ashl_lshr_seq[left + 1].insn_count + 1;
4336           if (cost < best_cost)
4337             {
4338               kind = 7;
4339               best_cost = cost;
4340             }
4341         }
4342     }
4343   if (TARGET_DYNSHIFT)
4344     {
4345       /* Try to use a dynamic shift.  */
4346       cost = ashl_lshr_seq[32 - insize].insn_count + 1 + SH_DYNAMIC_SHIFT_COST;
4347       if (cost < best_cost)
4348         {
4349           kind = 0;
4350           best_cost = cost;
4351         }
4352     }
4353   if (costp)
4354     *costp = cost;
4355   return kind;
4356 }
4357
4358 /* Function to be used in the length attribute of the instructions
4359    implementing this pattern.  */
4360 int
4361 shl_sext_length (rtx insn)
4362 {
4363   rtx set_src, left_rtx, size_rtx;
4364   int cost;
4365
4366   set_src = SET_SRC (XVECEXP (PATTERN (insn), 0, 0));
4367   left_rtx = XEXP (XEXP (set_src, 0), 1);
4368   size_rtx = XEXP (set_src, 1);
4369   shl_sext_kind (left_rtx, size_rtx, &cost);
4370   return cost;
4371 }
4372
4373 /* Generate rtl for this pattern */
4374 bool
4375 gen_shl_sext (rtx dest, rtx left_rtx, rtx size_rtx, rtx source)
4376 {
4377   int kind;
4378   int left, size, insize, cost;
4379   rtx operands[3];
4380
4381   kind = shl_sext_kind (left_rtx, size_rtx, &cost);
4382   left = INTVAL (left_rtx);
4383   size = INTVAL (size_rtx);
4384   insize = size - left;
4385   switch (kind)
4386     {
4387     case 1:
4388     case 2:
4389     case 3:
4390     case 4:
4391       {
4392         int ext = kind & 1 ? 8 : 16;
4393         int shift2 = size - ext;
4394
4395         /* Don't expand fine-grained when combining, because that will
4396            make the pattern fail.  */
4397         if (! currently_expanding_to_rtl
4398             && ! reload_in_progress && ! reload_completed)
4399           {
4400             emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
4401             emit_insn (gen_movsi (dest, source));
4402             break;
4403           }
4404         if (dest != source)
4405           emit_insn (gen_movsi (dest, source));
4406         operands[0] = dest;
4407         if (ext - insize)
4408           {
4409             operands[2] = GEN_INT (ext - insize);
4410             gen_shifty_hi_op (ASHIFT, operands);
4411           }
4412         emit_insn (kind & 1
4413                    ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
4414                    : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
4415         if (kind <= 2)
4416           {
4417             if (shift2)
4418               {
4419                 operands[2] = GEN_INT (shift2);
4420                 gen_shifty_op (ASHIFT, operands);
4421               }
4422           }
4423         else
4424           {
4425             if (shift2 > 0)
4426               {
4427                 if (EXT_SHIFT_SIGNED (shift2))
4428                   {
4429                     operands[2] = GEN_INT (shift2 + 1);
4430                     gen_shifty_op (ASHIFT, operands);
4431                     operands[2] = const1_rtx;
4432                     gen_shifty_op (ASHIFTRT, operands);
4433                     break;
4434                   }
4435                 operands[2] = GEN_INT (shift2);
4436                 gen_shifty_hi_op (ASHIFT, operands);
4437               }
4438             else if (shift2)
4439               {
4440                 operands[2] = GEN_INT (-shift2);
4441                 gen_shifty_hi_op (LSHIFTRT, operands);
4442               }
4443             emit_insn (size <= 8
4444                        ? gen_extendqisi2 (dest, gen_lowpart (QImode, dest))
4445                        : gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
4446           }
4447         break;
4448       }
4449     case 5:
4450       {
4451         int i = 16 - size;
4452         if (! currently_expanding_to_rtl
4453             && ! reload_in_progress && ! reload_completed)
4454           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
4455         else
4456           {
4457             operands[0] = dest;
4458             operands[2] = GEN_INT (16 - insize);
4459             gen_shifty_hi_op (ASHIFT, operands);
4460             emit_insn (gen_extendhisi2 (dest, gen_lowpart (HImode, dest)));
4461           }
4462         /* Don't use gen_ashrsi3 because it generates new pseudos.  */
4463         while (--i >= 0)
4464           gen_ashift (ASHIFTRT, 1, dest);
4465         break;
4466       }
4467     case 6:
4468     case 7:
4469       /* Don't expand fine-grained when combining, because that will
4470          make the pattern fail.  */
4471       if (! currently_expanding_to_rtl
4472           && ! reload_in_progress && ! reload_completed)
4473         {
4474           emit_insn (gen_shl_sext_ext (dest, source, left_rtx, size_rtx));
4475           emit_insn (gen_movsi (dest, source));
4476           break;
4477         }
4478       emit_insn (gen_andsi3 (dest, source, GEN_INT ((1 << insize) - 1)));
4479       emit_insn (gen_xorsi3 (dest, dest, GEN_INT (1 << (insize - 1))));
4480       emit_insn (gen_addsi3 (dest, dest, GEN_INT (-1 << (insize - 1))));
4481       operands[0] = dest;
4482       operands[2] = kind == 7 ? GEN_INT (left + 1) : left_rtx;
4483       gen_shifty_op (ASHIFT, operands);
4484       if (kind == 7)
4485         emit_insn (gen_ashrsi3_k (dest, dest, const1_rtx));
4486       break;
4487     default:
4488       return true;
4489     }
4490   return false;
4491 }
4492
4493 /* Prefix a symbol_ref name with "datalabel".  */
4494 rtx
4495 gen_datalabel_ref (rtx sym)
4496 {
4497   const char *str;
4498
4499   if (GET_CODE (sym) == LABEL_REF)
4500     return gen_rtx_CONST (GET_MODE (sym),
4501                           gen_rtx_UNSPEC (GET_MODE (sym),
4502                                           gen_rtvec (1, sym),
4503                                           UNSPEC_DATALABEL));
4504
4505   gcc_assert (GET_CODE (sym) == SYMBOL_REF);
4506
4507   str = XSTR (sym, 0);
4508   /* Share all SYMBOL_REF strings with the same value - that is important
4509      for cse.  */
4510   str = IDENTIFIER_POINTER (get_identifier (str));
4511   XSTR (sym, 0) = str;
4512
4513   return sym;
4514 }
4515
4516 \f
4517 static alloc_pool label_ref_list_pool;
4518
4519 typedef struct label_ref_list_d
4520 {
4521   rtx label;
4522   struct label_ref_list_d *next;
4523 } *label_ref_list_t;
4524
4525 /* The SH cannot load a large constant into a register, constants have to
4526    come from a pc relative load.  The reference of a pc relative load
4527    instruction must be less than 1k in front of the instruction.  This
4528    means that we often have to dump a constant inside a function, and
4529    generate code to branch around it.
4530
4531    It is important to minimize this, since the branches will slow things
4532    down and make things bigger.
4533
4534    Worst case code looks like:
4535
4536    mov.l L1,rn
4537    bra   L2
4538    nop
4539    align
4540    L1:   .long value
4541    L2:
4542    ..
4543
4544    mov.l L3,rn
4545    bra   L4
4546    nop
4547    align
4548    L3:   .long value
4549    L4:
4550    ..
4551
4552    We fix this by performing a scan before scheduling, which notices which
4553    instructions need to have their operands fetched from the constant table
4554    and builds the table.
4555
4556    The algorithm is:
4557
4558    scan, find an instruction which needs a pcrel move.  Look forward, find the
4559    last barrier which is within MAX_COUNT bytes of the requirement.
4560    If there isn't one, make one.  Process all the instructions between
4561    the find and the barrier.
4562
4563    In the above example, we can tell that L3 is within 1k of L1, so
4564    the first move can be shrunk from the 3 insn+constant sequence into
4565    just 1 insn, and the constant moved to L3 to make:
4566
4567    mov.l        L1,rn
4568    ..
4569    mov.l        L3,rn
4570    bra          L4
4571    nop
4572    align
4573    L3:.long value
4574    L4:.long value
4575
4576    Then the second move becomes the target for the shortening process.  */
4577
4578 typedef struct
4579 {
4580   rtx value;                    /* Value in table.  */
4581   rtx label;                    /* Label of value.  */
4582   label_ref_list_t wend;        /* End of window.  */
4583   enum machine_mode mode;       /* Mode of value.  */
4584
4585   /* True if this constant is accessed as part of a post-increment
4586      sequence.  Note that HImode constants are never accessed in this way.  */
4587   bool part_of_sequence_p;
4588 } pool_node;
4589
4590 /* The maximum number of constants that can fit into one pool, since
4591    constants in the range 0..510 are at least 2 bytes long, and in the
4592    range from there to 1018 at least 4 bytes.  */
4593
4594 #define MAX_POOL_SIZE 372
4595 static pool_node pool_vector[MAX_POOL_SIZE];
4596 static int pool_size;
4597 static rtx pool_window_label;
4598 static int pool_window_last;
4599
4600 static int max_labelno_before_reorg;
4601
4602 /* ??? If we need a constant in HImode which is the truncated value of a
4603    constant we need in SImode, we could combine the two entries thus saving
4604    two bytes.  Is this common enough to be worth the effort of implementing
4605    it?  */
4606
4607 /* ??? This stuff should be done at the same time that we shorten branches.
4608    As it is now, we must assume that all branches are the maximum size, and
4609    this causes us to almost always output constant pools sooner than
4610    necessary.  */
4611
4612 /* Add a constant to the pool and return its label.  */
4613 static rtx
4614 add_constant (rtx x, enum machine_mode mode, rtx last_value)
4615 {
4616   int i;
4617   rtx lab, new_rtx;
4618   label_ref_list_t ref, newref;
4619
4620   /* First see if we've already got it.  */
4621   for (i = 0; i < pool_size; i++)
4622     {
4623       if (x->code == pool_vector[i].value->code
4624           && mode == pool_vector[i].mode)
4625         {
4626           if (x->code == CODE_LABEL)
4627             {
4628               if (XINT (x, 3) != XINT (pool_vector[i].value, 3))
4629                 continue;
4630             }
4631           if (rtx_equal_p (x, pool_vector[i].value))
4632             {
4633               lab = new_rtx = 0;
4634               if (! last_value
4635                   || ! i
4636                   || ! rtx_equal_p (last_value, pool_vector[i-1].value))
4637                 {
4638                   new_rtx = gen_label_rtx ();
4639                   LABEL_REFS (new_rtx) = pool_vector[i].label;
4640                   pool_vector[i].label = lab = new_rtx;
4641                 }
4642               if (lab && pool_window_label)
4643                 {
4644                   newref = (label_ref_list_t) pool_alloc (label_ref_list_pool);
4645                   newref->label = pool_window_label;
4646                   ref = pool_vector[pool_window_last].wend;
4647                   newref->next = ref;
4648                   pool_vector[pool_window_last].wend = newref;
4649                 }
4650               if (new_rtx)
4651                 pool_window_label = new_rtx;
4652               pool_window_last = i;
4653               return lab;
4654             }
4655         }
4656     }
4657
4658   /* Need a new one.  */
4659   pool_vector[pool_size].value = x;
4660   if (last_value && rtx_equal_p (last_value, pool_vector[pool_size - 1].value))
4661     {
4662       lab = 0;
4663       pool_vector[pool_size - 1].part_of_sequence_p = true;
4664     }
4665   else
4666     lab = gen_label_rtx ();
4667   pool_vector[pool_size].mode = mode;
4668   pool_vector[pool_size].label = lab;
4669   pool_vector[pool_size].wend = NULL;
4670   pool_vector[pool_size].part_of_sequence_p = (lab == 0);
4671   if (lab && pool_window_label)
4672     {
4673       newref = (label_ref_list_t) pool_alloc (label_ref_list_pool);
4674       newref->label = pool_window_label;
4675       ref = pool_vector[pool_window_last].wend;
4676       newref->next = ref;
4677       pool_vector[pool_window_last].wend = newref;
4678     }
4679   if (lab)
4680     pool_window_label = lab;
4681   pool_window_last = pool_size;
4682   pool_size++;
4683   return lab;
4684 }
4685
4686 /* Output the literal table.  START, if nonzero, is the first instruction
4687    this table is needed for, and also indicates that there is at least one
4688    casesi_worker_2 instruction; We have to emit the operand3 labels from
4689    these insns at a 4-byte  aligned position.  BARRIER is the barrier
4690    after which we are to place the table.  */
4691 static void
4692 dump_table (rtx start, rtx barrier)
4693 {
4694   rtx scan = barrier;
4695   int i;
4696   bool need_align = true;
4697   rtx lab;
4698   label_ref_list_t ref;
4699   bool have_df = false;
4700
4701   /* Do two passes, first time dump out the HI sized constants.  */
4702
4703   for (i = 0; i < pool_size; i++)
4704     {
4705       pool_node *p = &pool_vector[i];
4706
4707       if (p->mode == HImode)
4708         {
4709           if (need_align)
4710             {
4711               scan = emit_insn_after (gen_align_2 (), scan);
4712               need_align = false;
4713             }
4714           for (lab = p->label; lab; lab = LABEL_REFS (lab))
4715             scan = emit_label_after (lab, scan);
4716           scan = emit_insn_after (gen_consttable_2 (p->value, const0_rtx),
4717                                   scan);
4718           for (ref = p->wend; ref; ref = ref->next)
4719             {
4720               lab = ref->label;
4721               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
4722             }
4723         }
4724       else if (p->mode == DFmode)
4725         have_df = true;
4726     }
4727
4728   need_align = true;
4729
4730   if (start)
4731     {
4732       scan = emit_insn_after (gen_align_4 (), scan);
4733       need_align = false;
4734       for (; start != barrier; start = NEXT_INSN (start))
4735         if (NONJUMP_INSN_P (start)
4736             && recog_memoized (start) == CODE_FOR_casesi_worker_2)
4737           {
4738             rtx src = SET_SRC (XVECEXP (PATTERN (start), 0, 0));
4739             rtx lab = XEXP (XVECEXP (src, 0, 3), 0);
4740
4741             scan = emit_label_after (lab, scan);
4742           }
4743     }
4744   if (TARGET_FMOVD && TARGET_ALIGN_DOUBLE && have_df)
4745     {
4746       rtx align_insn = NULL_RTX;
4747
4748       scan = emit_label_after (gen_label_rtx (), scan);
4749       scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
4750       need_align = false;
4751
4752       for (i = 0; i < pool_size; i++)
4753         {
4754           pool_node *p = &pool_vector[i];
4755
4756           switch (p->mode)
4757             {
4758             case HImode:
4759               break;
4760             case SImode:
4761             case SFmode:
4762               if (align_insn && !p->part_of_sequence_p)
4763                 {
4764                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
4765                     emit_label_before (lab, align_insn);
4766                   emit_insn_before (gen_consttable_4 (p->value, const0_rtx),
4767                                     align_insn);
4768                   for (ref = p->wend; ref; ref = ref->next)
4769                     {
4770                       lab = ref->label;
4771                       emit_insn_before (gen_consttable_window_end (lab),
4772                                         align_insn);
4773                     }
4774                   delete_insn (align_insn);
4775                   align_insn = NULL_RTX;
4776                   continue;
4777                 }
4778               else
4779                 {
4780                   for (lab = p->label; lab; lab = LABEL_REFS (lab))
4781                     scan = emit_label_after (lab, scan);
4782                   scan = emit_insn_after (gen_consttable_4 (p->value,
4783                                                             const0_rtx), scan);
4784                   need_align = ! need_align;
4785                 }
4786               break;
4787             case DFmode:
4788               if (need_align)
4789                 {
4790                   scan = emit_insn_after (gen_align_log (GEN_INT (3)), scan);
4791                   align_insn = scan;
4792                   need_align = false;
4793                 }
4794             case DImode:
4795               for (lab = p->label; lab; lab = LABEL_REFS (lab))
4796                 scan = emit_label_after (lab, scan);
4797               scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
4798                                       scan);
4799               break;
4800             default:
4801               gcc_unreachable ();
4802             }
4803
4804           if (p->mode != HImode)
4805             {
4806               for (ref = p->wend; ref; ref = ref->next)
4807                 {
4808                   lab = ref->label;
4809                   scan = emit_insn_after (gen_consttable_window_end (lab),
4810                                           scan);
4811                 }
4812             }
4813         }
4814
4815       pool_size = 0;
4816     }
4817
4818   for (i = 0; i < pool_size; i++)
4819     {
4820       pool_node *p = &pool_vector[i];
4821
4822       switch (p->mode)
4823         {
4824         case HImode:
4825           break;
4826         case SImode:
4827         case SFmode:
4828           if (need_align)
4829             {
4830               need_align = false;
4831               scan = emit_label_after (gen_label_rtx (), scan);
4832               scan = emit_insn_after (gen_align_4 (), scan);
4833             }
4834           for (lab = p->label; lab; lab = LABEL_REFS (lab))
4835             scan = emit_label_after (lab, scan);
4836           scan = emit_insn_after (gen_consttable_4 (p->value, const0_rtx),
4837                                   scan);
4838           break;
4839         case DFmode:
4840         case DImode:
4841           if (need_align)
4842             {
4843               need_align = false;
4844               scan = emit_label_after (gen_label_rtx (), scan);
4845               scan = emit_insn_after (gen_align_4 (), scan);
4846             }
4847           for (lab = p->label; lab; lab = LABEL_REFS (lab))
4848             scan = emit_label_after (lab, scan);
4849           scan = emit_insn_after (gen_consttable_8 (p->value, const0_rtx),
4850                                   scan);
4851           break;
4852         default:
4853           gcc_unreachable ();
4854         }
4855
4856       if (p->mode != HImode)
4857         {
4858           for (ref = p->wend; ref; ref = ref->next)
4859             {
4860               lab = ref->label;
4861               scan = emit_insn_after (gen_consttable_window_end (lab), scan);
4862             }
4863         }
4864     }
4865
4866   scan = emit_insn_after (gen_consttable_end (), scan);
4867   scan = emit_barrier_after (scan);
4868   pool_size = 0;
4869   pool_window_label = NULL_RTX;
4870   pool_window_last = 0;
4871 }
4872
4873 #define MOVA_LABELREF(mova) XVECEXP (SET_SRC (PATTERN (mova)), 0, 0)
4874
4875 /* Nonzero if the insn is a move instruction which needs to be fixed.  */
4876
4877 /* ??? For a DImode/DFmode moves, we don't need to fix it if each half of the
4878    CONST_DOUBLE input value is CONST_OK_FOR_I08.  For a SFmode move, we don't
4879    need to fix it if the input value is CONST_OK_FOR_I08.  */
4880 static bool
4881 broken_move (rtx insn)
4882 {
4883   if (NONJUMP_INSN_P (insn))
4884     {
4885       rtx pat = PATTERN (insn);
4886       if (GET_CODE (pat) == PARALLEL)
4887         pat = XVECEXP (pat, 0, 0);
4888       if (GET_CODE (pat) == SET
4889           /* We can load any 8-bit value if we don't care what the high
4890              order bits end up as.  */
4891           && GET_MODE (SET_DEST (pat)) != QImode
4892           && (CONSTANT_P (SET_SRC (pat))
4893               || (GET_CODE (SET_SRC (pat)) == UNSPEC_VOLATILE
4894                   && XINT (SET_SRC (pat), 1) ==  UNSPECV_SP_SWITCH_B)
4895               /* Match mova_const.  */
4896               || (GET_CODE (SET_SRC (pat)) == UNSPEC
4897                   && XINT (SET_SRC (pat), 1) == UNSPEC_MOVA
4898                   && GET_CODE (XVECEXP (SET_SRC (pat), 0, 0)) == CONST))
4899           && ! (TARGET_SH2E
4900                 && GET_CODE (SET_SRC (pat)) == CONST_DOUBLE
4901                 && (fp_zero_operand (SET_SRC (pat))
4902                     || fp_one_operand (SET_SRC (pat)))
4903                 /* In general we don't know the current setting of fpscr, so
4904                    disable fldi.
4905                    There is an exception if this was a register-register move
4906                    before reload - and hence it was ascertained that we have
4907                    single precision setting - and in a post-reload optimization
4908                    we changed this to do a constant load.  In that case
4909                    we don't have an r0 clobber, hence we must use fldi.  */
4910                 && (TARGET_FMOVD
4911                     || (GET_CODE (XEXP (XVECEXP (PATTERN (insn), 0, 2), 0))
4912                         == SCRATCH))
4913                 && REG_P (SET_DEST (pat))
4914                 && FP_REGISTER_P (REGNO (SET_DEST (pat))))
4915           && ! (TARGET_SH2A
4916                 && GET_MODE (SET_DEST (pat)) == SImode
4917                 && (satisfies_constraint_I20 (SET_SRC (pat))
4918                    || satisfies_constraint_I28 (SET_SRC (pat))))
4919           && ! satisfies_constraint_I08 (SET_SRC (pat)))
4920         return true;
4921     }
4922
4923   return false;
4924 }
4925
4926 /* Return true if the specified insn is a mova insn.  */
4927 static bool
4928 mova_p (rtx insn)
4929 {
4930   return (NONJUMP_INSN_P (insn)
4931           && GET_CODE (PATTERN (insn)) == SET
4932           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
4933           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_MOVA
4934           /* Don't match mova_const.  */
4935           && GET_CODE (MOVA_LABELREF (insn)) == LABEL_REF);
4936 }
4937
4938 /* Fix up a mova from a switch that went out of range.  */
4939 static void
4940 fixup_mova (rtx mova)
4941 {
4942   PUT_MODE (XEXP (MOVA_LABELREF (mova), 0), QImode);
4943   if (! flag_pic)
4944     {
4945       SET_SRC (PATTERN (mova)) = MOVA_LABELREF (mova);
4946       INSN_CODE (mova) = -1;
4947     }
4948   else
4949     {
4950       rtx worker = mova;
4951       rtx lab = gen_label_rtx ();
4952       rtx wpat, wpat0, wpat1, wsrc, target, base, diff;
4953
4954       do
4955         {
4956           worker = NEXT_INSN (worker);
4957           gcc_assert (worker
4958                       && !LABEL_P (worker)
4959                       && !JUMP_P (worker));
4960         } while (NOTE_P (worker)
4961                  || recog_memoized (worker) != CODE_FOR_casesi_worker_1);
4962       wpat = PATTERN (worker);
4963       wpat0 = XVECEXP (wpat, 0, 0);
4964       wpat1 = XVECEXP (wpat, 0, 1);
4965       wsrc = SET_SRC (wpat0);
4966       PATTERN (worker) = (gen_casesi_worker_2
4967                           (SET_DEST (wpat0), XVECEXP (wsrc, 0, 1),
4968                            XEXP (XVECEXP (wsrc, 0, 2), 0), lab,
4969                            XEXP (wpat1, 0)));
4970       INSN_CODE (worker) = -1;
4971       target = XVECEXP (SET_SRC (PATTERN (mova)), 0, 0);
4972       base = gen_rtx_LABEL_REF (Pmode, lab);
4973       diff = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, target, base), UNSPEC_SYMOFF);
4974       SET_SRC (PATTERN (mova)) = gen_rtx_CONST (Pmode, diff);
4975       INSN_CODE (mova) = -1;
4976     }
4977 }
4978
4979 /* NEW_MOVA is a mova we've just encountered while scanning forward.  Update
4980    *num_mova, and check if the new mova is not nested within the first one.
4981    return 0 if *first_mova was replaced, 1 if new_mova was replaced,
4982    2 if new_mova has been assigned to *first_mova, -1 otherwise..  */
4983 static int
4984 untangle_mova (int *num_mova, rtx *first_mova, rtx new_mova)
4985 {
4986   int n_addr = 0; /* Initialization to shut up spurious warning.  */
4987   int f_target, n_target = 0; /* Likewise.  */
4988
4989   if (optimize)
4990     {
4991       /* If NEW_MOVA has no address yet, it will be handled later.  */
4992       if (INSN_ADDRESSES_SIZE() <= (unsigned) INSN_UID (new_mova))
4993         return -1;
4994
4995       n_addr = INSN_ADDRESSES (INSN_UID (new_mova));
4996       n_target = INSN_ADDRESSES (INSN_UID (XEXP (MOVA_LABELREF (new_mova), 0)));
4997       if (n_addr > n_target || n_addr + 1022 < n_target)
4998         {
4999           /* Change the mova into a load.
5000              broken_move will then return true for it.  */
5001           fixup_mova (new_mova);
5002           return 1;
5003         }
5004     }
5005   if (!(*num_mova)++)
5006     {
5007       *first_mova = new_mova;
5008       return 2;
5009     }
5010   if (!optimize
5011       || ((f_target
5012            = INSN_ADDRESSES (INSN_UID (XEXP (MOVA_LABELREF (*first_mova), 0))))
5013           >= n_target))
5014     return -1;
5015
5016   (*num_mova)--;
5017   if (f_target - INSN_ADDRESSES (INSN_UID (*first_mova))
5018       > n_target - n_addr)
5019     {
5020       fixup_mova (*first_mova);
5021       return 0;
5022     }
5023   else
5024     {
5025       fixup_mova (new_mova);
5026       return 1;
5027     }
5028 }
5029
5030 /* Find the last barrier from insn FROM which is close enough to hold the
5031    constant pool.  If we can't find one, then create one near the end of
5032    the range.  */
5033 static rtx
5034 find_barrier (int num_mova, rtx mova, rtx from)
5035 {
5036   int count_si = 0;
5037   int count_hi = 0;
5038   int found_hi = 0;
5039   int found_si = 0;
5040   int found_di = 0;
5041   int hi_align = 2;
5042   int si_align = 2;
5043   int leading_mova = num_mova;
5044   rtx barrier_before_mova = NULL_RTX;
5045   rtx found_barrier = NULL_RTX;
5046   rtx good_barrier = NULL_RTX;
5047   int si_limit;
5048   int hi_limit;
5049   rtx orig = from;
5050   rtx last_got = NULL_RTX;
5051   rtx last_symoff = NULL_RTX;
5052
5053   /* For HImode: range is 510, add 4 because pc counts from address of
5054      second instruction after this one, subtract 2 for the jump instruction
5055      that we may need to emit before the table, subtract 2 for the instruction
5056      that fills the jump delay slot (in very rare cases, reorg will take an
5057      instruction from after the constant pool or will leave the delay slot
5058      empty).  This gives 510.
5059      For SImode: range is 1020, add 4 because pc counts from address of
5060      second instruction after this one, subtract 2 in case pc is 2 byte
5061      aligned, subtract 2 for the jump instruction that we may need to emit
5062      before the table, subtract 2 for the instruction that fills the jump
5063      delay slot.  This gives 1018.  */
5064
5065   /* The branch will always be shortened now that the reference address for
5066      forward branches is the successor address, thus we need no longer make
5067      adjustments to the [sh]i_limit for -O0.  */
5068
5069   si_limit = 1018;
5070   hi_limit = 510;
5071
5072   while (from && count_si < si_limit && count_hi < hi_limit)
5073     {
5074       int inc = get_attr_length (from);
5075       int new_align = 1;
5076
5077       /* If this is a label that existed at the time of the compute_alignments
5078          call, determine the alignment.  N.B.  When find_barrier recurses for
5079          an out-of-reach mova, we might see labels at the start of previously
5080          inserted constant tables.  */
5081       if (LABEL_P (from)
5082           && CODE_LABEL_NUMBER (from) <= max_labelno_before_reorg)
5083         {
5084           if (optimize)
5085             new_align = 1 << label_to_alignment (from);
5086           else if (BARRIER_P (prev_nonnote_insn (from)))
5087             new_align = 1 << barrier_align (from);
5088           else
5089             new_align = 1;
5090           inc = 0;
5091         }
5092       /* In case we are scanning a constant table because of recursion, check
5093          for explicit alignments.  If the table is long, we might be forced
5094          to emit the new table in front of it; the length of the alignment
5095          might be the last straw.  */
5096       else if (NONJUMP_INSN_P (from)
5097                && GET_CODE (PATTERN (from)) == UNSPEC_VOLATILE
5098                && XINT (PATTERN (from), 1) == UNSPECV_ALIGN)
5099         new_align = INTVAL (XVECEXP (PATTERN (from), 0, 0));
5100       /* When we find the end of a constant table, paste the new constant
5101          at the end.  That is better than putting it in front because
5102          this way, we don't need extra alignment for adding a 4-byte-aligned
5103          mov(a) label to a 2/4 or 8/4 byte aligned table.  */
5104       else if (NONJUMP_INSN_P (from)
5105                && GET_CODE (PATTERN (from)) == UNSPEC_VOLATILE
5106                && XINT (PATTERN (from), 1) == UNSPECV_CONST_END)
5107         return from;
5108
5109       if (BARRIER_P (from))
5110         {
5111           rtx next;
5112
5113           found_barrier = from;
5114
5115           /* If we are at the end of the function, or in front of an alignment
5116              instruction, we need not insert an extra alignment.  We prefer
5117              this kind of barrier.  */
5118           if (barrier_align (from) > 2)
5119             good_barrier = from;
5120
5121           /* If we are at the end of a hot/cold block, dump the constants
5122              here.  */
5123           next = NEXT_INSN (from);
5124           if (next
5125               && NOTE_P (next)
5126               && NOTE_KIND (next) == NOTE_INSN_SWITCH_TEXT_SECTIONS)
5127             break;
5128         }
5129
5130       if (broken_move (from))
5131         {
5132           rtx pat, src, dst;
5133           enum machine_mode mode;
5134
5135           pat = PATTERN (from);
5136           if (GET_CODE (pat) == PARALLEL)
5137             pat = XVECEXP (pat, 0, 0);
5138           src = SET_SRC (pat);
5139           dst = SET_DEST (pat);
5140           mode = GET_MODE (dst);
5141
5142           /* GOT pcrelat setting comes in pair of
5143              mova       .L8,r0
5144              mov.l      .L8,r12
5145              instructions.  (plus add r0,r12).
5146              Remember if we see one without the other.  */
5147           if (GET_CODE (src) == UNSPEC && PIC_ADDR_P (XVECEXP (src, 0, 0)))
5148             last_got = last_got ? NULL_RTX : from;
5149           else if (PIC_ADDR_P (src))
5150             last_got = last_got ? NULL_RTX : from;
5151
5152           /* We must explicitly check the mode, because sometimes the
5153              front end will generate code to load unsigned constants into
5154              HImode targets without properly sign extending them.  */
5155           if (mode == HImode
5156               || (mode == SImode && satisfies_constraint_I16 (src)
5157                   && REGNO (dst) != FPUL_REG))
5158             {
5159               found_hi += 2;
5160               /* We put the short constants before the long constants, so
5161                  we must count the length of short constants in the range
5162                  for the long constants.  */
5163               /* ??? This isn't optimal, but is easy to do.  */
5164               si_limit -= 2;
5165             }
5166           else
5167             {
5168               /* We dump DF/DI constants before SF/SI ones, because
5169                  the limit is the same, but the alignment requirements
5170                  are higher.  We may waste up to 4 additional bytes
5171                  for alignment, and the DF/DI constant may have
5172                  another SF/SI constant placed before it.  */
5173               if (TARGET_SHCOMPACT
5174                   && ! found_di
5175                   && (mode == DFmode || mode == DImode))
5176                 {
5177                   found_di = 1;
5178                   si_limit -= 8;
5179                 }
5180               while (si_align > 2 && found_si + si_align - 2 > count_si)
5181                 si_align >>= 1;
5182               if (found_si > count_si)
5183                 count_si = found_si;
5184               found_si += GET_MODE_SIZE (mode);
5185               if (num_mova)
5186                 si_limit -= GET_MODE_SIZE (mode);
5187             }
5188         }
5189
5190       if (mova_p (from))
5191         {
5192           switch (untangle_mova (&num_mova, &mova, from))
5193             {
5194               case 1:
5195                 if (flag_pic)
5196                   {
5197                     rtx src = SET_SRC (PATTERN (from));
5198                     if (GET_CODE (src) == CONST
5199                         && GET_CODE (XEXP (src, 0)) == UNSPEC
5200                         && XINT (XEXP (src, 0), 1) == UNSPEC_SYMOFF)
5201                       last_symoff = from;
5202                   }
5203                 break;
5204               case 0:   return find_barrier (0, 0, mova);
5205               case 2:
5206                 {
5207                   leading_mova = 0;
5208                   barrier_before_mova
5209                     = good_barrier ? good_barrier : found_barrier;
5210                 }
5211               default:  break;
5212             }
5213           if (found_si > count_si)
5214             count_si = found_si;
5215         }
5216       else if (JUMP_TABLE_DATA_P (from))
5217         {
5218           if ((num_mova > 1 && GET_MODE (prev_nonnote_insn (from)) == VOIDmode)
5219               || (num_mova
5220                   && (prev_nonnote_insn (from)
5221                       == XEXP (MOVA_LABELREF (mova), 0))))
5222             num_mova--;
5223           if (barrier_align (next_real_insn (from)) == align_jumps_log)
5224             {
5225               /* We have just passed the barrier in front of the
5226                  ADDR_DIFF_VEC, which is stored in found_barrier.  Since
5227                  the ADDR_DIFF_VEC is accessed as data, just like our pool
5228                  constants, this is a good opportunity to accommodate what
5229                  we have gathered so far.
5230                  If we waited any longer, we could end up at a barrier in
5231                  front of code, which gives worse cache usage for separated
5232                  instruction / data caches.  */
5233               good_barrier = found_barrier;
5234               break;
5235             }
5236           else
5237             {
5238               rtx body = PATTERN (from);
5239               inc = XVECLEN (body, 1) * GET_MODE_SIZE (GET_MODE (body));
5240             }
5241         }
5242       /* For the SH1, we generate alignments even after jumps-around-jumps.  */
5243       else if (JUMP_P (from)
5244                && ! TARGET_SH2
5245                && ! optimize_size)
5246         new_align = 4;
5247
5248       /* There is a possibility that a bf is transformed into a bf/s by the
5249          delay slot scheduler.  */
5250       if (JUMP_P (from) && !JUMP_TABLE_DATA_P (from) 
5251           && get_attr_type (from) == TYPE_CBRANCH
5252           && ! sequence_insn_p (from))
5253         inc += 2;
5254
5255       if (found_si)
5256         {
5257           count_si += inc;
5258           if (new_align > si_align)
5259             {
5260               si_limit -= (count_si - 1) & (new_align - si_align);
5261               si_align = new_align;
5262             }
5263           count_si = (count_si + new_align - 1) & -new_align;
5264         }
5265       if (found_hi)
5266         {
5267           count_hi += inc;
5268           if (new_align > hi_align)
5269             {
5270               hi_limit -= (count_hi - 1) & (new_align - hi_align);
5271               hi_align = new_align;
5272             }
5273           count_hi = (count_hi + new_align - 1) & -new_align;
5274         }
5275       from = NEXT_INSN (from);
5276     }
5277
5278   if (num_mova)
5279     {
5280       if (leading_mova)
5281         {
5282           /* Try as we might, the leading mova is out of range.  Change
5283              it into a load (which will become a pcload) and retry.  */
5284           fixup_mova (mova);
5285           return find_barrier (0, 0, mova);
5286         }
5287       else
5288         {
5289           /* Insert the constant pool table before the mova instruction,
5290              to prevent the mova label reference from going out of range.  */
5291           from = mova;
5292           good_barrier = found_barrier = barrier_before_mova;
5293         }
5294     }
5295
5296   if (found_barrier)
5297     {
5298       if (good_barrier && next_real_insn (found_barrier))
5299         found_barrier = good_barrier;
5300     }
5301   else
5302     {
5303       /* We didn't find a barrier in time to dump our stuff,
5304          so we'll make one.  */
5305       rtx label = gen_label_rtx ();
5306
5307       /* Don't emit a constant table in the middle of insns for
5308          casesi_worker_2.  This is a bit overkill but is enough
5309          because casesi_worker_2 wouldn't appear so frequently.  */
5310       if (last_symoff)
5311         from = last_symoff;
5312
5313       /* If we exceeded the range, then we must back up over the last
5314          instruction we looked at.  Otherwise, we just need to undo the
5315          NEXT_INSN at the end of the loop.  */
5316       if (PREV_INSN (from) != orig
5317           && (count_hi > hi_limit || count_si > si_limit))
5318         from = PREV_INSN (PREV_INSN (from));
5319       else
5320         from = PREV_INSN (from);
5321
5322       /* Don't emit a constant table int the middle of global pointer setting,
5323          since that that would move the addressing base GOT into another table. 
5324          We need the first mov instruction before the _GLOBAL_OFFSET_TABLE_
5325          in the pool anyway, so just move up the whole constant pool.
5326
5327          However, avoid doing so when the last single GOT mov is the starting
5328          insn itself. Going past above the start insn would create a negative
5329          offset, causing errors.  */
5330       if (last_got && last_got != orig)
5331         from = PREV_INSN (last_got);
5332
5333       /* Don't insert the constant pool table at the position which
5334          may be the landing pad.  */
5335       if (flag_exceptions
5336           && CALL_P (from)
5337           && find_reg_note (from, REG_EH_REGION, NULL_RTX))
5338         from = PREV_INSN (from);
5339
5340       /* Walk back to be just before any jump or label.
5341          Putting it before a label reduces the number of times the branch
5342          around the constant pool table will be hit.  Putting it before
5343          a jump makes it more likely that the bra delay slot will be
5344          filled.  */
5345       while (NOTE_P (from) || JUMP_P (from)
5346              || LABEL_P (from))
5347         from = PREV_INSN (from);
5348
5349       /* Make sure we do not split between a call and its corresponding
5350          CALL_ARG_LOCATION note.  */
5351       if (CALL_P (from))
5352         {
5353           rtx next = NEXT_INSN (from);
5354           if (next && NOTE_P (next)
5355               && NOTE_KIND (next) == NOTE_INSN_CALL_ARG_LOCATION)
5356             from = next;
5357         }
5358
5359       from = emit_jump_insn_after (gen_jump (label), from);
5360       JUMP_LABEL (from) = label;
5361       LABEL_NUSES (label) = 1;
5362       found_barrier = emit_barrier_after (from);
5363       emit_label_after (label, found_barrier);
5364     }
5365
5366   return found_barrier;
5367 }
5368
5369 /* If the instruction INSN is implemented by a special function, and we can
5370    positively find the register that is used to call the sfunc, and this
5371    register is not used anywhere else in this instruction - except as the
5372    destination of a set, return this register; else, return 0.  */
5373 rtx
5374 sfunc_uses_reg (rtx insn)
5375 {
5376   int i;
5377   rtx pattern, part, reg_part, reg;
5378
5379   if (!NONJUMP_INSN_P (insn))
5380     return NULL_RTX;
5381   pattern = PATTERN (insn);
5382   if (GET_CODE (pattern) != PARALLEL || get_attr_type (insn) != TYPE_SFUNC)
5383     return NULL_RTX;
5384
5385   for (reg_part = NULL_RTX, i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
5386     {
5387       part = XVECEXP (pattern, 0, i);
5388       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == SImode)
5389         reg_part = part;
5390     }
5391   if (! reg_part)
5392     return NULL_RTX;
5393   reg = XEXP (reg_part, 0);
5394   for (i = XVECLEN (pattern, 0) - 1; i >= 0; i--)
5395     {
5396       part = XVECEXP (pattern, 0, i);
5397       if (part == reg_part || GET_CODE (part) == CLOBBER)
5398         continue;
5399       if (reg_mentioned_p (reg, ((GET_CODE (part) == SET
5400                                   && REG_P (SET_DEST (part)))
5401                                  ? SET_SRC (part) : part)))
5402         return NULL_RTX;
5403     }
5404   return reg;
5405 }
5406
5407 /* See if the only way in which INSN uses REG is by calling it, or by
5408    setting it while calling it.  Set *SET to a SET rtx if the register
5409    is set by INSN.  */
5410 static bool
5411 noncall_uses_reg (rtx reg, rtx insn, rtx *set)
5412 {
5413   rtx pattern, reg2;
5414
5415   *set = NULL_RTX;
5416
5417   reg2 = sfunc_uses_reg (insn);
5418   if (reg2 && REGNO (reg2) == REGNO (reg))
5419     {
5420       pattern = single_set (insn);
5421       if (pattern
5422           && REG_P (SET_DEST (pattern))
5423           && REGNO (reg) == REGNO (SET_DEST (pattern)))
5424         *set = pattern;
5425       return false;
5426     }
5427   if (!CALL_P (insn))
5428     {
5429       /* We don't use rtx_equal_p because we don't care if the mode is
5430          different.  */
5431       pattern = single_set (insn);
5432       if (pattern
5433           && REG_P (SET_DEST (pattern))
5434           && REGNO (reg) == REGNO (SET_DEST (pattern)))
5435         {
5436           rtx par, part;
5437           int i;
5438
5439           *set = pattern;
5440           par = PATTERN (insn);
5441           if (GET_CODE (par) == PARALLEL)
5442             for (i = XVECLEN (par, 0) - 1; i >= 0; i--)
5443               {
5444                 part = XVECEXP (par, 0, i);
5445                 if (GET_CODE (part) != SET && reg_mentioned_p (reg, part))
5446                   return true;
5447               }
5448           return reg_mentioned_p (reg, SET_SRC (pattern));
5449         }
5450
5451       return true;
5452     }
5453
5454   pattern = PATTERN (insn);
5455
5456   if (GET_CODE (pattern) == PARALLEL)
5457     {
5458       int i;
5459
5460       for (i = XVECLEN (pattern, 0) - 1; i >= 1; i--)
5461         if (reg_mentioned_p (reg, XVECEXP (pattern, 0, i)))
5462           return true;
5463       pattern = XVECEXP (pattern, 0, 0);
5464     }
5465
5466   if (GET_CODE (pattern) == SET)
5467     {
5468       if (reg_mentioned_p (reg, SET_DEST (pattern)))
5469         {
5470           /* We don't use rtx_equal_p, because we don't care if the
5471              mode is different.  */
5472           if (!REG_P (SET_DEST (pattern))
5473               || REGNO (reg) != REGNO (SET_DEST (pattern)))
5474             return true;
5475
5476           *set = pattern;
5477         }
5478
5479       pattern = SET_SRC (pattern);
5480     }
5481
5482   if (GET_CODE (pattern) != CALL
5483       || !MEM_P (XEXP (pattern, 0))
5484       || ! rtx_equal_p (reg, XEXP (XEXP (pattern, 0), 0)))
5485     return true;
5486
5487   return false;
5488 }
5489
5490 /* Given a X, a pattern of an insn or a part of it, return a mask of used
5491    general registers.  Bits 0..15 mean that the respective registers
5492    are used as inputs in the instruction.  Bits 16..31 mean that the
5493    registers 0..15, respectively, are used as outputs, or are clobbered.
5494    IS_DEST should be set to 16 if X is the destination of a SET, else to 0.  */
5495 int
5496 regs_used (rtx x, int is_dest)
5497 {
5498   enum rtx_code code;
5499   const char *fmt;
5500   int i, used = 0;
5501
5502   if (! x)
5503     return used;
5504   code = GET_CODE (x);
5505   switch (code)
5506     {
5507     case REG:
5508       if (REGNO (x) < 16)
5509         return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
5510                 << (REGNO (x) + is_dest));
5511       return 0;
5512     case SUBREG:
5513       {
5514         rtx y = SUBREG_REG (x);
5515
5516         if (!REG_P (y))
5517           break;
5518         if (REGNO (y) < 16)
5519           return (((1 << HARD_REGNO_NREGS (0, GET_MODE (x))) - 1)
5520                   << (REGNO (y) +
5521                       subreg_regno_offset (REGNO (y),
5522                                            GET_MODE (y),
5523                                            SUBREG_BYTE (x),
5524                                            GET_MODE (x)) + is_dest));
5525         return 0;
5526       }
5527     case SET:
5528       return regs_used (SET_SRC (x), 0) | regs_used (SET_DEST (x), 16);
5529     case RETURN:
5530       /* If there was a return value, it must have been indicated with USE.  */
5531       return 0x00ffff00;
5532     case CLOBBER:
5533       is_dest = 1;
5534       break;
5535     case MEM:
5536       is_dest = 0;
5537       break;
5538     case CALL:
5539       used |= 0x00ff00f0;
5540       break;
5541     default:
5542       break;
5543     }
5544
5545   fmt = GET_RTX_FORMAT (code);
5546
5547   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5548     {
5549       if (fmt[i] == 'E')
5550         {
5551           int j;
5552           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
5553             used |= regs_used (XVECEXP (x, i, j), is_dest);
5554         }
5555       else if (fmt[i] == 'e')
5556         used |= regs_used (XEXP (x, i), is_dest);
5557     }
5558   return used;
5559 }
5560
5561 /* Create an instruction that prevents redirection of a conditional branch
5562    to the destination of the JUMP with address ADDR.
5563    If the branch needs to be implemented as an indirect jump, try to find
5564    a scratch register for it.
5565    If NEED_BLOCK is 0, don't do anything unless we need a scratch register.
5566    If any preceding insn that doesn't fit into a delay slot is good enough,
5567    pass 1.  Pass 2 if a definite blocking insn is needed.
5568    -1 is used internally to avoid deep recursion.
5569    If a blocking instruction is made or recognized, return it.  */
5570 static rtx
5571 gen_block_redirect (rtx jump, int addr, int need_block)
5572 {
5573   int dead = 0;
5574   rtx prev = prev_nonnote_insn (jump);
5575   rtx dest;
5576
5577   /* First, check if we already have an instruction that satisfies our need.  */
5578   if (prev && NONJUMP_INSN_P (prev) && ! INSN_DELETED_P (prev))
5579     {
5580       if (INSN_CODE (prev) == CODE_FOR_indirect_jump_scratch)
5581         return prev;
5582       if (GET_CODE (PATTERN (prev)) == USE
5583           || GET_CODE (PATTERN (prev)) == CLOBBER
5584           || get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
5585         prev = jump;
5586       else if ((need_block &= ~1) < 0)
5587         return prev;
5588       else if (recog_memoized (prev) == CODE_FOR_block_branch_redirect)
5589         need_block = 0;
5590     }
5591   if (GET_CODE (PATTERN (jump)) == RETURN)
5592     {
5593       if (! need_block)
5594         return prev;
5595       /* Reorg even does nasty things with return insns that cause branches
5596          to go out of range - see find_end_label and callers.  */
5597       return emit_insn_before (gen_block_branch_redirect (const0_rtx) , jump);
5598     }
5599   /* We can't use JUMP_LABEL here because it might be undefined
5600      when not optimizing.  */
5601   dest = XEXP (SET_SRC (PATTERN (jump)), 0);
5602   /* If the branch is out of range, try to find a scratch register for it.  */
5603   if (optimize
5604       && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
5605           > 4092 + 4098))
5606     {
5607       rtx scan;
5608       /* Don't look for the stack pointer as a scratch register,
5609          it would cause trouble if an interrupt occurred.  */
5610       unsigned attempt = 0x7fff, used;
5611       int jump_left = flag_expensive_optimizations + 1;
5612
5613       /* It is likely that the most recent eligible instruction is wanted for
5614          the delay slot.  Therefore, find out which registers it uses, and
5615          try to avoid using them.  */
5616
5617       for (scan = jump; (scan = PREV_INSN (scan)); )
5618         {
5619           enum rtx_code code;
5620
5621           if (INSN_DELETED_P (scan))
5622             continue;
5623           code = GET_CODE (scan);
5624           if (code == CODE_LABEL || code == JUMP_INSN)
5625             break;
5626           if (code == INSN
5627               && GET_CODE (PATTERN (scan)) != USE
5628               && GET_CODE (PATTERN (scan)) != CLOBBER
5629               && get_attr_in_delay_slot (scan) == IN_DELAY_SLOT_YES)
5630             {
5631               attempt &= ~regs_used (PATTERN (scan), 0);
5632               break;
5633             }
5634         }
5635       for (used = dead = 0, scan = JUMP_LABEL (jump);
5636            (scan = NEXT_INSN (scan)); )
5637         {
5638           enum rtx_code code;
5639
5640           if (INSN_DELETED_P (scan))
5641             continue;
5642           code = GET_CODE (scan);
5643           if (INSN_P (scan))
5644             {
5645               used |= regs_used (PATTERN (scan), 0);
5646               if (code == CALL_INSN)
5647                 used |= regs_used (CALL_INSN_FUNCTION_USAGE (scan), 0);
5648               dead |= (used >> 16) & ~used;
5649               if (dead & attempt)
5650                 {
5651                   dead &= attempt;
5652                   break;
5653                 }
5654               if (code == JUMP_INSN)
5655                 {
5656                   if (jump_left-- && simplejump_p (scan))
5657                     scan = JUMP_LABEL (scan);
5658                   else
5659                     break;
5660                 }
5661             }
5662         }
5663       /* Mask out the stack pointer again, in case it was
5664          the only 'free' register we have found.  */
5665       dead &= 0x7fff;
5666     }
5667   /* If the immediate destination is still in range, check for possible
5668      threading with a jump beyond the delay slot insn.
5669      Don't check if we are called recursively; the jump has been or will be
5670      checked in a different invocation then.  */
5671
5672   else if (optimize && need_block >= 0)
5673     {
5674       rtx next = next_active_insn (next_active_insn (dest));
5675       if (next && JUMP_P (next)
5676           && GET_CODE (PATTERN (next)) == SET
5677           && recog_memoized (next) == CODE_FOR_jump_compact)
5678         {
5679           dest = JUMP_LABEL (next);
5680           if (dest
5681               && (INSN_ADDRESSES (INSN_UID (dest)) - addr + (unsigned) 4092
5682                   > 4092 + 4098))
5683             gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), -1);
5684         }
5685     }
5686
5687   if (dead)
5688     {
5689       rtx reg = gen_rtx_REG (SImode, exact_log2 (dead & -dead));
5690
5691       /* It would be nice if we could convert the jump into an indirect
5692          jump / far branch right now, and thus exposing all constituent
5693          instructions to further optimization.  However, reorg uses
5694          simplejump_p to determine if there is an unconditional jump where
5695          it should try to schedule instructions from the target of the
5696          branch; simplejump_p fails for indirect jumps even if they have
5697          a JUMP_LABEL.  */
5698       rtx insn = emit_insn_before (gen_indirect_jump_scratch
5699                                    (reg, GEN_INT (unspec_bbr_uid++)),
5700                                    jump);
5701       /* ??? We would like this to have the scope of the jump, but that
5702          scope will change when a delay slot insn of an inner scope is added.
5703          Hence, after delay slot scheduling, we'll have to expect
5704          NOTE_INSN_BLOCK_END notes between the indirect_jump_scratch and
5705          the jump.  */
5706
5707       INSN_LOCATION (insn) = INSN_LOCATION (jump);
5708       INSN_CODE (insn) = CODE_FOR_indirect_jump_scratch;
5709       return insn;
5710     }
5711   else if (need_block)
5712     /* We can't use JUMP_LABEL here because it might be undefined
5713        when not optimizing.  */
5714     return emit_insn_before (gen_block_branch_redirect
5715                              (GEN_INT (unspec_bbr_uid++)),
5716                              jump);
5717   return prev;
5718 }
5719
5720 #define CONDJUMP_MIN -252
5721 #define CONDJUMP_MAX 262
5722 struct far_branch
5723 {
5724   /* A label (to be placed) in front of the jump
5725      that jumps to our ultimate destination.  */
5726   rtx near_label;
5727   /* Where we are going to insert it if we cannot move the jump any farther,
5728      or the jump itself if we have picked up an existing jump.  */
5729   rtx insert_place;
5730   /* The ultimate destination.  */
5731   rtx far_label;
5732   struct far_branch *prev;
5733   /* If the branch has already been created, its address;
5734      else the address of its first prospective user.  */
5735   int address;
5736 };
5737
5738 static void gen_far_branch (struct far_branch *);
5739 enum mdep_reorg_phase_e mdep_reorg_phase;
5740 static void
5741 gen_far_branch (struct far_branch *bp)
5742 {
5743   rtx insn = bp->insert_place;
5744   rtx jump;
5745   rtx label = gen_label_rtx ();
5746   int ok;
5747
5748   emit_label_after (label, insn);
5749   if (bp->far_label)
5750     {
5751       jump = emit_jump_insn_after (gen_jump (bp->far_label), insn);
5752       LABEL_NUSES (bp->far_label)++;
5753     }
5754   else
5755     jump = emit_jump_insn_after (gen_return (), insn);
5756
5757   /* Emit a barrier so that reorg knows that any following instructions
5758      are not reachable via a fall-through path.
5759      But don't do this when not optimizing, since we wouldn't suppress the
5760      alignment for the barrier then, and could end up with out-of-range
5761      pc-relative loads.  */
5762   if (optimize)
5763     emit_barrier_after (jump);
5764   emit_label_after (bp->near_label, insn);
5765
5766   if (bp->far_label)
5767     JUMP_LABEL (jump) = bp->far_label;
5768   else
5769     {
5770       rtx pat = PATTERN (jump);
5771       gcc_assert (ANY_RETURN_P (pat));
5772       JUMP_LABEL (jump) = pat;
5773     }
5774
5775   ok = invert_jump (insn, label, 1);
5776   gcc_assert (ok);
5777
5778   /* If we are branching around a jump (rather than a return), prevent
5779      reorg from using an insn from the jump target as the delay slot insn -
5780      when reorg did this, it pessimized code (we rather hide the delay slot)
5781      and it could cause branches to go out of range.  */
5782   if (bp->far_label)
5783     (emit_insn_after
5784      (gen_stuff_delay_slot
5785       (GEN_INT (unspec_bbr_uid++),
5786        GEN_INT (recog_memoized (insn) == CODE_FOR_branch_false)),
5787       insn));
5788   /* Prevent reorg from undoing our splits.  */
5789   gen_block_redirect (jump, bp->address += 2, 2);
5790 }
5791
5792 /* Fix up ADDR_DIFF_VECs.  */
5793 void
5794 fixup_addr_diff_vecs (rtx first)
5795 {
5796   rtx insn;
5797
5798   for (insn = first; insn; insn = NEXT_INSN (insn))
5799     {
5800       rtx vec_lab, pat, prev, prevpat, x, braf_label;
5801
5802       if (!JUMP_P (insn)
5803           || GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
5804         continue;
5805       pat = PATTERN (insn);
5806       vec_lab = XEXP (XEXP (pat, 0), 0);
5807
5808       /* Search the matching casesi_jump_2.  */
5809       for (prev = vec_lab; ; prev = PREV_INSN (prev))
5810         {
5811           if (!JUMP_P (prev))
5812             continue;
5813           prevpat = PATTERN (prev);
5814           if (GET_CODE (prevpat) != PARALLEL || XVECLEN (prevpat, 0) != 2)
5815             continue;
5816           x = XVECEXP (prevpat, 0, 1);
5817           if (GET_CODE (x) != USE)
5818             continue;
5819           x = XEXP (x, 0);
5820           if (GET_CODE (x) == LABEL_REF && XEXP (x, 0) == vec_lab)
5821             break;
5822         }
5823       /* FIXME: This is a bug in the optimizer, but it seems harmless
5824          to just avoid panicing.  */
5825       if (!prev)
5826         continue;
5827
5828       /* Emit the reference label of the braf where it belongs, right after
5829          the casesi_jump_2 (i.e. braf).  */
5830       braf_label = XEXP (XEXP (SET_SRC (XVECEXP (prevpat, 0, 0)), 1), 0);
5831       emit_label_after (braf_label, prev);
5832
5833       /* Fix up the ADDR_DIF_VEC to be relative
5834          to the reference address of the braf.  */
5835       XEXP (XEXP (pat, 0), 0) = braf_label;
5836     }
5837 }
5838
5839 /* BARRIER_OR_LABEL is either a BARRIER or a CODE_LABEL immediately following
5840    a barrier.  Return the base 2 logarithm of the desired alignment.  */
5841 int
5842 barrier_align (rtx barrier_or_label)
5843 {
5844   rtx next = next_real_insn (barrier_or_label), pat, prev;
5845
5846   if (! next)
5847     return 0;
5848
5849   pat = PATTERN (next);
5850
5851   if (GET_CODE (pat) == ADDR_DIFF_VEC)
5852     return 2;
5853
5854   if (GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_ALIGN)
5855     /* This is a barrier in front of a constant table.  */
5856     return 0;
5857
5858   prev = prev_real_insn (barrier_or_label);
5859   if (GET_CODE (PATTERN (prev)) == ADDR_DIFF_VEC)
5860     {
5861       pat = PATTERN (prev);
5862       /* If this is a very small table, we want to keep the alignment after
5863          the table to the minimum for proper code alignment.  */
5864       return ((optimize_size
5865                || ((unsigned) XVECLEN (pat, 1) * GET_MODE_SIZE (GET_MODE (pat))
5866                    <= (unsigned) 1 << (CACHE_LOG - 2)))
5867               ? 1 << TARGET_SHMEDIA : align_jumps_log);
5868     }
5869
5870   if (optimize_size)
5871     return 0;
5872
5873   if (! TARGET_SH2 || ! optimize)
5874     return align_jumps_log;
5875
5876   /* When fixing up pcloads, a constant table might be inserted just before
5877      the basic block that ends with the barrier.  Thus, we can't trust the
5878      instruction lengths before that.  */
5879   if (mdep_reorg_phase > SH_FIXUP_PCLOAD)
5880     {
5881       /* Check if there is an immediately preceding branch to the insn beyond
5882          the barrier.  We must weight the cost of discarding useful information
5883          from the current cache line when executing this branch and there is
5884          an alignment, against that of fetching unneeded insn in front of the
5885          branch target when there is no alignment.  */
5886
5887       /* There are two delay_slot cases to consider.  One is the simple case
5888          where the preceding branch is to the insn beyond the barrier (simple
5889          delay slot filling), and the other is where the preceding branch has
5890          a delay slot that is a duplicate of the insn after the barrier
5891          (fill_eager_delay_slots) and the branch is to the insn after the insn
5892          after the barrier.  */
5893
5894       /* PREV is presumed to be the JUMP_INSN for the barrier under
5895          investigation.  Skip to the insn before it.  */
5896
5897       int slot, credit;
5898       bool jump_to_next = false;
5899
5900       prev = prev_real_insn (prev);
5901
5902       for (slot = 2, credit = (1 << (CACHE_LOG - 2)) + 2;
5903            credit >= 0 && prev && NONJUMP_INSN_P (prev);
5904            prev = prev_real_insn (prev))
5905         {
5906           jump_to_next = false;
5907           if (GET_CODE (PATTERN (prev)) == USE
5908               || GET_CODE (PATTERN (prev)) == CLOBBER)
5909             continue;
5910           if (GET_CODE (PATTERN (prev)) == SEQUENCE)
5911             {
5912               prev = XVECEXP (PATTERN (prev), 0, 1);
5913               if (INSN_UID (prev) == INSN_UID (next))
5914                 {
5915                   /* Delay slot was filled with insn at jump target.  */
5916                   jump_to_next = true;
5917                   continue;
5918                 }
5919             }
5920
5921           if (slot &&
5922               get_attr_in_delay_slot (prev) == IN_DELAY_SLOT_YES)
5923             slot = 0;
5924           credit -= get_attr_length (prev);
5925         }
5926       if (prev && jump_to_label_p (prev))
5927         {
5928           rtx x;
5929           if (jump_to_next
5930               || next_real_insn (JUMP_LABEL (prev)) == next
5931               /* If relax_delay_slots() decides NEXT was redundant
5932                  with some previous instruction, it will have
5933                  redirected PREV's jump to the following insn.  */
5934               || JUMP_LABEL (prev) == next_nonnote_insn (next)
5935               /* There is no upper bound on redundant instructions
5936                  that might have been skipped, but we must not put an
5937                  alignment where none had been before.  */
5938               || (x = (NEXT_INSN (NEXT_INSN (PREV_INSN (prev)))),
5939                   (INSN_P (x)
5940                    && (INSN_CODE (x) == CODE_FOR_block_branch_redirect
5941                        || INSN_CODE (x) == CODE_FOR_indirect_jump_scratch
5942                        || INSN_CODE (x) == CODE_FOR_stuff_delay_slot))))
5943             {
5944               rtx pat = PATTERN (prev);
5945               if (GET_CODE (pat) == PARALLEL)
5946                 pat = XVECEXP (pat, 0, 0);
5947               if (credit - slot >= (GET_CODE (SET_SRC (pat)) == PC ? 2 : 0))
5948                 return 0;
5949             }
5950         }
5951     }
5952
5953   return align_jumps_log;
5954 }
5955
5956 /* If we are inside a phony loop, almost any kind of label can turn up as the
5957    first one in the loop.  Aligning a braf label causes incorrect switch
5958    destination addresses; we can detect braf labels because they are
5959    followed by a BARRIER.
5960    Applying loop alignment to small constant or switch tables is a waste
5961    of space, so we suppress this too.  */
5962 int
5963 sh_loop_align (rtx label)
5964 {
5965   rtx next = label;
5966
5967   if (! optimize || optimize_size)
5968     return 0;
5969
5970   do
5971     next = next_nonnote_insn (next);
5972   while (next && LABEL_P (next));
5973
5974   if (! next
5975       || ! INSN_P (next)
5976       || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC
5977       || recog_memoized (next) == CODE_FOR_consttable_2)
5978     return 0;
5979
5980   return align_loops_log;
5981 }
5982
5983 /* Do a final pass over the function, just before delayed branch
5984    scheduling.  */
5985 static void
5986 sh_reorg (void)
5987 {
5988   rtx first, insn, mova = NULL_RTX;
5989   int num_mova;
5990   rtx r0_rtx = gen_rtx_REG (Pmode, 0);
5991   rtx r0_inc_rtx = gen_rtx_POST_INC (Pmode, r0_rtx);
5992
5993   first = get_insns ();
5994   max_labelno_before_reorg = max_label_num ();
5995
5996   /* We must split call insns before introducing `mova's.  If we're
5997      optimizing, they'll have already been split.  Otherwise, make
5998      sure we don't split them too late.  */
5999   if (! optimize)
6000     split_all_insns_noflow ();
6001
6002   if (TARGET_SHMEDIA)
6003     return;
6004
6005   /* If relaxing, generate pseudo-ops to associate function calls with
6006      the symbols they call.  It does no harm to not generate these
6007      pseudo-ops.  However, when we can generate them, it enables the
6008      linker to potentially relax the jsr to a bsr, and eliminate the
6009      register load and, possibly, the constant pool entry.  */
6010
6011   mdep_reorg_phase = SH_INSERT_USES_LABELS;
6012   if (TARGET_RELAX)
6013     {
6014       /* Remove all REG_LABEL_OPERAND notes.  We want to use them for our
6015          own purposes.  This works because none of the remaining passes
6016          need to look at them.
6017
6018          ??? But it may break in the future.  We should use a machine
6019          dependent REG_NOTE, or some other approach entirely.  */
6020       for (insn = first; insn; insn = NEXT_INSN (insn))
6021         {
6022           if (INSN_P (insn))
6023             {
6024               rtx note;
6025
6026               while ((note = find_reg_note (insn, REG_LABEL_OPERAND,
6027                                             NULL_RTX)) != 0)
6028                 remove_note (insn, note);
6029             }
6030         }
6031
6032       for (insn = first; insn; insn = NEXT_INSN (insn))
6033         {
6034           rtx pattern, reg, link, set, scan, dies, label;
6035           int rescan = 0, foundinsn = 0;
6036
6037           if (CALL_P (insn))
6038             {
6039               pattern = PATTERN (insn);
6040
6041               if (GET_CODE (pattern) == PARALLEL)
6042                 pattern = XVECEXP (pattern, 0, 0);
6043               if (GET_CODE (pattern) == SET)
6044                 pattern = SET_SRC (pattern);
6045
6046               if (GET_CODE (pattern) != CALL
6047                   || !MEM_P (XEXP (pattern, 0)))
6048                 continue;
6049
6050               reg = XEXP (XEXP (pattern, 0), 0);
6051             }
6052           else
6053             {
6054               reg = sfunc_uses_reg (insn);
6055               if (! reg)
6056                 continue;
6057             }
6058
6059           if (!REG_P (reg))
6060             continue;
6061
6062           /* Try scanning backward to find where the register is set.  */
6063           link = NULL;
6064           for (scan = PREV_INSN (insn);
6065                scan && !LABEL_P (scan);
6066                scan = PREV_INSN (scan))
6067             {
6068               if (! INSN_P (scan))
6069                 continue;
6070
6071               if (! reg_mentioned_p (reg, scan))
6072                 continue;
6073
6074               if (noncall_uses_reg (reg, scan, &set))
6075                 break;
6076
6077               if (set)
6078                 {
6079                   link = scan;
6080                   break;
6081                 }
6082             }
6083
6084           if (! link)
6085             continue;
6086
6087           /* The register is set at LINK.  */
6088
6089           /* We can only optimize the function call if the register is
6090              being set to a symbol.  In theory, we could sometimes
6091              optimize calls to a constant location, but the assembler
6092              and linker do not support that at present.  */
6093           if (GET_CODE (SET_SRC (set)) != SYMBOL_REF
6094               && GET_CODE (SET_SRC (set)) != LABEL_REF)
6095             continue;
6096
6097           /* Scan forward from LINK to the place where REG dies, and
6098              make sure that the only insns which use REG are
6099              themselves function calls.  */
6100
6101           /* ??? This doesn't work for call targets that were allocated
6102              by reload, since there may not be a REG_DEAD note for the
6103              register.  */
6104
6105           dies = NULL_RTX;
6106           for (scan = NEXT_INSN (link); scan; scan = NEXT_INSN (scan))
6107             {
6108               rtx scanset;
6109
6110               /* Don't try to trace forward past a CODE_LABEL if we haven't
6111                  seen INSN yet.  Ordinarily, we will only find the setting insn
6112                  if it is in the same basic block.  However,
6113                  cross-jumping can insert code labels in between the load and
6114                  the call, and can result in situations where a single call
6115                  insn may have two targets depending on where we came from.  */
6116
6117               if (LABEL_P (scan) && ! foundinsn)
6118                 break;
6119
6120               if (! INSN_P (scan))
6121                 continue;
6122
6123               /* Don't try to trace forward past a JUMP.  To optimize
6124                  safely, we would have to check that all the
6125                  instructions at the jump destination did not use REG.  */
6126
6127               if (JUMP_P (scan))
6128                 break;
6129
6130               if (! reg_mentioned_p (reg, scan))
6131                 continue;
6132
6133               if (noncall_uses_reg (reg, scan, &scanset))
6134                 break;
6135
6136               if (scan == insn)
6137                 foundinsn = 1;
6138
6139               if (scan != insn
6140                   && (CALL_P (scan) || sfunc_uses_reg (scan)))
6141                 {
6142                   /* There is a function call to this register other
6143                      than the one we are checking.  If we optimize
6144                      this call, we need to rescan again below.  */
6145                   rescan = 1;
6146                 }
6147
6148               /* ??? We shouldn't have to worry about SCANSET here.
6149                  We should just be able to check for a REG_DEAD note
6150                  on a function call.  However, the REG_DEAD notes are
6151                  apparently not dependable around libcalls; c-torture
6152                  execute/920501-2 is a test case.  If SCANSET is set,
6153                  then this insn sets the register, so it must have
6154                  died earlier.  Unfortunately, this will only handle
6155                  the cases in which the register is, in fact, set in a
6156                  later insn.  */
6157
6158               /* ??? We shouldn't have to use FOUNDINSN here.
6159                  This dates back to when we used LOG_LINKS to find 
6160                  the most recent insn which sets the register.  */
6161
6162               if (foundinsn
6163                   && (scanset
6164                       || find_reg_note (scan, REG_DEAD, reg)))
6165                 {
6166                   dies = scan;
6167                   break;
6168                 }
6169             }
6170
6171           if (! dies)
6172             {
6173               /* Either there was a branch, or some insn used REG
6174                  other than as a function call address.  */
6175               continue;
6176             }
6177
6178           /* Create a code label, and put it in a REG_LABEL_OPERAND note
6179              on the insn which sets the register, and on each call insn
6180              which uses the register.  In final_prescan_insn we look for
6181              the REG_LABEL_OPERAND notes, and output the appropriate label
6182              or pseudo-op.  */
6183
6184           label = gen_label_rtx ();
6185           add_reg_note (link, REG_LABEL_OPERAND, label);
6186           add_reg_note (insn, REG_LABEL_OPERAND, label);
6187           if (rescan)
6188             {
6189               scan = link;
6190               do
6191                 {
6192                   rtx reg2;
6193
6194                   scan = NEXT_INSN (scan);
6195                   if (scan != insn
6196                       && ((CALL_P (scan)
6197                            && reg_mentioned_p (reg, scan))
6198                           || ((reg2 = sfunc_uses_reg (scan))
6199                               && REGNO (reg2) == REGNO (reg))))
6200                     add_reg_note (scan, REG_LABEL_OPERAND, label);
6201                 }
6202               while (scan != dies);
6203             }
6204         }
6205     }
6206
6207   if (TARGET_SH2)
6208     fixup_addr_diff_vecs (first);
6209
6210   if (optimize)
6211     {
6212       mdep_reorg_phase = SH_SHORTEN_BRANCHES0;
6213       shorten_branches (first);
6214     }
6215
6216   /* Scan the function looking for move instructions which have to be
6217      changed to pc-relative loads and insert the literal tables.  */
6218   label_ref_list_pool = create_alloc_pool ("label references list",
6219                                            sizeof (struct label_ref_list_d),
6220                                            30);
6221   mdep_reorg_phase = SH_FIXUP_PCLOAD;
6222   for (insn = first, num_mova = 0; insn; insn = NEXT_INSN (insn))
6223     {
6224       if (mova_p (insn))
6225         {
6226           /* ??? basic block reordering can move a switch table dispatch
6227              below the switch table.  Check if that has happened.
6228              We only have the addresses available when optimizing; but then,
6229              this check shouldn't be needed when not optimizing.  */
6230           if (!untangle_mova (&num_mova, &mova, insn))
6231             {
6232               insn = mova;
6233               num_mova = 0;
6234             }
6235         }
6236       else if (JUMP_P (insn)
6237                && GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
6238                && num_mova
6239                /* ??? loop invariant motion can also move a mova out of a
6240                   loop.  Since loop does this code motion anyway, maybe we
6241                   should wrap UNSPEC_MOVA into a CONST, so that reload can
6242                   move it back.  */
6243                && ((num_mova > 1
6244                     && GET_MODE (prev_nonnote_insn (insn)) == VOIDmode)
6245                    || (prev_nonnote_insn (insn)
6246                        == XEXP (MOVA_LABELREF (mova), 0))))
6247         {
6248           rtx scan;
6249           int total;
6250
6251           num_mova--;
6252
6253           /* Some code might have been inserted between the mova and
6254              its ADDR_DIFF_VEC.  Check if the mova is still in range.  */
6255           for (scan = mova, total = 0; scan != insn; scan = NEXT_INSN (scan))
6256             total += get_attr_length (scan);
6257
6258           /* range of mova is 1020, add 4 because pc counts from address of
6259              second instruction after this one, subtract 2 in case pc is 2
6260              byte aligned.  Possible alignment needed for the ADDR_DIFF_VEC
6261              cancels out with alignment effects of the mova itself.  */
6262           if (total > 1022)
6263             {
6264               /* Change the mova into a load, and restart scanning
6265                  there.  broken_move will then return true for mova.  */
6266               fixup_mova (mova);
6267               insn = mova;
6268             }
6269         }
6270       if (broken_move (insn)
6271           || (NONJUMP_INSN_P (insn)
6272               && recog_memoized (insn) == CODE_FOR_casesi_worker_2))
6273         {
6274           rtx scan;
6275           /* Scan ahead looking for a barrier to stick the constant table
6276              behind.  */
6277           rtx barrier = find_barrier (num_mova, mova, insn);
6278           rtx last_float_move = NULL_RTX, last_float = 0, *last_float_addr = NULL;
6279           int need_aligned_label = 0;
6280
6281           if (num_mova && ! mova_p (mova))
6282             {
6283               /* find_barrier had to change the first mova into a
6284                  pcload; thus, we have to start with this new pcload.  */
6285               insn = mova;
6286               num_mova = 0;
6287             }
6288           /* Now find all the moves between the points and modify them.  */
6289           for (scan = insn; scan != barrier; scan = NEXT_INSN (scan))
6290             {
6291               if (LABEL_P (scan))
6292                 last_float = 0;
6293               if (NONJUMP_INSN_P (scan)
6294                   && recog_memoized (scan) == CODE_FOR_casesi_worker_2)
6295                 need_aligned_label = 1;
6296               if (broken_move (scan))
6297                 {
6298                   rtx *patp = &PATTERN (scan), pat = *patp;
6299                   rtx src, dst;
6300                   rtx lab;
6301                   rtx newsrc;
6302                   enum machine_mode mode;
6303
6304                   if (GET_CODE (pat) == PARALLEL)
6305                     patp = &XVECEXP (pat, 0, 0), pat = *patp;
6306                   src = SET_SRC (pat);
6307                   dst = SET_DEST (pat);
6308                   mode = GET_MODE (dst);
6309
6310                   if (mode == SImode && satisfies_constraint_I16 (src)
6311                       && REGNO (dst) != FPUL_REG)
6312                     {
6313                       int offset = 0;
6314
6315                       mode = HImode;
6316                       while (GET_CODE (dst) == SUBREG)
6317                         {
6318                           offset += subreg_regno_offset (REGNO (SUBREG_REG (dst)),
6319                                                          GET_MODE (SUBREG_REG (dst)),
6320                                                          SUBREG_BYTE (dst),
6321                                                          GET_MODE (dst));
6322                           dst = SUBREG_REG (dst);
6323                         }
6324                       dst = gen_rtx_REG (HImode, REGNO (dst) + offset);
6325                     }
6326                   if (REG_P (dst) && FP_ANY_REGISTER_P (REGNO (dst)))
6327                     {
6328                       /* This must be an insn that clobbers r0.  */
6329                       rtx *clobberp = &XVECEXP (PATTERN (scan), 0,
6330                                                 XVECLEN (PATTERN (scan), 0)
6331                                                 - 1);
6332                       rtx clobber = *clobberp;
6333
6334                       gcc_assert (GET_CODE (clobber) == CLOBBER
6335                                   && rtx_equal_p (XEXP (clobber, 0), r0_rtx));
6336
6337                       if (last_float
6338                           && reg_set_between_p (r0_rtx, last_float_move, scan))
6339                         last_float = 0;
6340                       if (last_float
6341                           && TARGET_SHCOMPACT
6342                           && GET_MODE_SIZE (mode) != 4
6343                           && GET_MODE_SIZE (GET_MODE (last_float)) == 4)
6344                         last_float = 0;
6345                       lab = add_constant (src, mode, last_float);
6346                       if (lab)
6347                         emit_insn_before (gen_mova (lab), scan);
6348                       else
6349                         {
6350                           /* There will be a REG_UNUSED note for r0 on
6351                              LAST_FLOAT_MOVE; we have to change it to REG_INC,
6352                              lest reorg:mark_target_live_regs will not
6353                              consider r0 to be used, and we end up with delay
6354                              slot insn in front of SCAN that clobbers r0.  */
6355                           rtx note
6356                             = find_regno_note (last_float_move, REG_UNUSED, 0);
6357
6358                           /* If we are not optimizing, then there may not be
6359                              a note.  */
6360                           if (note)
6361                             PUT_REG_NOTE_KIND (note, REG_INC);
6362
6363                           *last_float_addr = r0_inc_rtx;
6364                         }
6365                       last_float_move = scan;
6366                       last_float = src;
6367                       newsrc = gen_const_mem (mode,
6368                                         (((TARGET_SH4 && ! TARGET_FMOVD)
6369                                           || REGNO (dst) == FPUL_REG)
6370                                          ? r0_inc_rtx
6371                                          : r0_rtx));
6372                       last_float_addr = &XEXP (newsrc, 0);
6373
6374                       /* Remove the clobber of r0.  */
6375                       *clobberp = gen_rtx_CLOBBER (GET_MODE (clobber),
6376                                                    gen_rtx_SCRATCH (Pmode));
6377                     }
6378                   /* This is a mova needing a label.  Create it.  */
6379                   else if (GET_CODE (src) == UNSPEC
6380                            && XINT (src, 1) == UNSPEC_MOVA
6381                            && GET_CODE (XVECEXP (src, 0, 0)) == CONST)
6382                     {
6383                       lab = add_constant (XVECEXP (src, 0, 0), mode, 0);
6384                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
6385                       newsrc = gen_rtx_UNSPEC (SImode,
6386                                                gen_rtvec (1, newsrc),
6387                                                UNSPEC_MOVA);
6388                     }
6389                   else if (GET_CODE (src) == UNSPEC_VOLATILE
6390                            && XINT (src, 1) == UNSPECV_SP_SWITCH_B)
6391                     {
6392                       newsrc = XVECEXP (src, 0, 0);
6393                       XVECEXP (src, 0, 0) = gen_const_mem (mode, newsrc);
6394                       INSN_CODE (scan) = -1;
6395                       continue;
6396                     }
6397                   else
6398                     {
6399                       lab = add_constant (src, mode, 0);
6400                       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
6401                       newsrc = gen_const_mem (mode, newsrc);
6402                     }
6403                   *patp = gen_rtx_SET (VOIDmode, dst, newsrc);
6404                   INSN_CODE (scan) = -1;
6405                 }
6406             }
6407           dump_table (need_aligned_label ? insn : 0, barrier);
6408           insn = barrier;
6409         }
6410     }
6411   free_alloc_pool (label_ref_list_pool);
6412   for (insn = first; insn; insn = NEXT_INSN (insn))
6413     PUT_MODE (insn, VOIDmode);
6414
6415   mdep_reorg_phase = SH_SHORTEN_BRANCHES1;
6416   INSN_ADDRESSES_FREE ();
6417   split_branches (first);
6418
6419   /* The INSN_REFERENCES_ARE_DELAYED in sh.h is problematic because it
6420      also has an effect on the register that holds the address of the sfunc.
6421      Insert an extra dummy insn in front of each sfunc that pretends to
6422      use this register.  */
6423   if (flag_delayed_branch)
6424     {
6425       for (insn = first; insn; insn = NEXT_INSN (insn))
6426         {
6427           rtx reg = sfunc_uses_reg (insn);
6428
6429           if (! reg)
6430             continue;
6431           emit_insn_before (gen_use_sfunc_addr (reg), insn);
6432         }
6433     }
6434 #if 0
6435   /* fpscr is not actually a user variable, but we pretend it is for the
6436      sake of the previous optimization passes, since we want it handled like
6437      one.  However, we don't have any debugging information for it, so turn
6438      it into a non-user variable now.  */
6439   if (TARGET_SH4)
6440     REG_USERVAR_P (get_fpscr_rtx ()) = 0;
6441 #endif
6442   mdep_reorg_phase = SH_AFTER_MDEP_REORG;
6443 }
6444
6445 /* Return the UID of the insn that follows the specified label.  */
6446 int
6447 get_dest_uid (rtx label, int max_uid)
6448 {
6449   rtx dest = next_real_insn (label);
6450   int dest_uid;
6451   if (! dest)
6452     /* This can happen for an undefined label.  */
6453     return 0;
6454   dest_uid = INSN_UID (dest);
6455   /* If this is a newly created branch redirection blocking instruction,
6456      we cannot index the branch_uid or insn_addresses arrays with its
6457      uid.  But then, we won't need to, because the actual destination is
6458      the following branch.  */
6459   while (dest_uid >= max_uid)
6460     {
6461       dest = NEXT_INSN (dest);
6462       dest_uid = INSN_UID (dest);
6463     }
6464   if (JUMP_P (dest) && GET_CODE (PATTERN (dest)) == RETURN)
6465     return 0;
6466   return dest_uid;
6467 }
6468
6469 /* Split condbranches that are out of range.  Also add clobbers for
6470    scratch registers that are needed in far jumps.
6471    We do this before delay slot scheduling, so that it can take our
6472    newly created instructions into account.  It also allows us to
6473    find branches with common targets more easily.  */
6474 static void
6475 split_branches (rtx first)
6476 {
6477   rtx insn;
6478   struct far_branch **uid_branch, *far_branch_list = 0;
6479   int max_uid = get_max_uid ();
6480   int ok;
6481
6482   /* Find out which branches are out of range.  */
6483   shorten_branches (first);
6484
6485   uid_branch = (struct far_branch **) alloca (max_uid * sizeof *uid_branch);
6486   memset ((char *) uid_branch, 0, max_uid * sizeof *uid_branch);
6487
6488   for (insn = first; insn; insn = NEXT_INSN (insn))
6489     if (! INSN_P (insn))
6490       continue;
6491     else if (INSN_DELETED_P (insn))
6492       {
6493         /* Shorten_branches would split this instruction again,
6494            so transform it into a note.  */
6495         SET_INSN_DELETED (insn);
6496       }
6497     else if (JUMP_P (insn)
6498              /* Don't mess with ADDR_DIFF_VEC */
6499              && (GET_CODE (PATTERN (insn)) == SET
6500                  || GET_CODE (PATTERN (insn)) == RETURN))
6501       {
6502         enum attr_type type = get_attr_type (insn);
6503         if (type == TYPE_CBRANCH)
6504           {
6505             rtx next, beyond;
6506
6507             if (get_attr_length (insn) > 4)
6508               {
6509                 rtx src = SET_SRC (PATTERN (insn));
6510                 rtx olabel = XEXP (XEXP (src, 1), 0);
6511                 int addr = INSN_ADDRESSES (INSN_UID (insn));
6512                 rtx label = 0;
6513                 int dest_uid = get_dest_uid (olabel, max_uid);
6514                 struct far_branch *bp = uid_branch[dest_uid];
6515
6516                 /* redirect_jump needs a valid JUMP_LABEL, and it might delete
6517                    the label if the LABEL_NUSES count drops to zero.  There is
6518                    always a jump_optimize pass that sets these values, but it
6519                    proceeds to delete unreferenced code, and then if not
6520                    optimizing, to un-delete the deleted instructions, thus
6521                    leaving labels with too low uses counts.  */
6522                 if (! optimize)
6523                   {
6524                     JUMP_LABEL (insn) = olabel;
6525                     LABEL_NUSES (olabel)++;
6526                   }
6527                 if (! bp)
6528                   {
6529                     bp = (struct far_branch *) alloca (sizeof *bp);
6530                     uid_branch[dest_uid] = bp;
6531                     bp->prev = far_branch_list;
6532                     far_branch_list = bp;
6533                     bp->far_label
6534                       = XEXP (XEXP (SET_SRC (PATTERN (insn)), 1), 0);
6535                     LABEL_NUSES (bp->far_label)++;
6536                   }
6537                 else
6538                   {
6539                     label = bp->near_label;
6540                     if (! label && bp->address - addr >= CONDJUMP_MIN)
6541                       {
6542                         rtx block = bp->insert_place;
6543
6544                         if (GET_CODE (PATTERN (block)) == RETURN)
6545                           block = PREV_INSN (block);
6546                         else
6547                           block = gen_block_redirect (block,
6548                                                       bp->address, 2);
6549                         label = emit_label_after (gen_label_rtx (),
6550                                                   PREV_INSN (block));
6551                         bp->near_label = label;
6552                       }
6553                     else if (label && ! NEXT_INSN (label))
6554                       {
6555                         if (addr + 2 - bp->address <= CONDJUMP_MAX)
6556                           bp->insert_place = insn;
6557                         else
6558                           gen_far_branch (bp);
6559                       }
6560                   }
6561                 if (! label
6562                     || (NEXT_INSN (label) && bp->address - addr < CONDJUMP_MIN))
6563                   {
6564                     bp->near_label = label = gen_label_rtx ();
6565                     bp->insert_place = insn;
6566                     bp->address = addr;
6567                   }
6568                 ok = redirect_jump (insn, label, 0);
6569                 gcc_assert (ok);
6570               }
6571             else
6572               {
6573                 /* get_attr_length (insn) == 2 */
6574                 /* Check if we have a pattern where reorg wants to redirect
6575                    the branch to a label from an unconditional branch that
6576                    is too far away.  */
6577                 /* We can't use JUMP_LABEL here because it might be undefined
6578                    when not optimizing.  */
6579                 /* A syntax error might cause beyond to be NULL_RTX.  */
6580                 beyond
6581                   = next_active_insn (XEXP (XEXP (SET_SRC (PATTERN (insn)), 1),
6582                                             0));
6583
6584                 if (beyond
6585                     && (JUMP_P (beyond)
6586                         || ((beyond = next_active_insn (beyond))
6587                             && JUMP_P (beyond)))
6588                     && GET_CODE (PATTERN (beyond)) == SET
6589                     && recog_memoized (beyond) == CODE_FOR_jump_compact
6590                     && ((INSN_ADDRESSES
6591                          (INSN_UID (XEXP (SET_SRC (PATTERN (beyond)), 0)))
6592                          - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
6593                         > 252 + 258 + 2))
6594                   gen_block_redirect (beyond,
6595                                       INSN_ADDRESSES (INSN_UID (beyond)), 1);
6596               }
6597
6598             next = next_active_insn (insn);
6599
6600             if (next
6601                 && (JUMP_P (next)
6602                     || ((next = next_active_insn (next))
6603                         && JUMP_P (next)))
6604                 && GET_CODE (PATTERN (next)) == SET
6605                 && recog_memoized (next) == CODE_FOR_jump_compact
6606                 && ((INSN_ADDRESSES
6607                      (INSN_UID (XEXP (SET_SRC (PATTERN (next)), 0)))
6608                      - INSN_ADDRESSES (INSN_UID (insn)) + (unsigned) 252)
6609                     > 252 + 258 + 2))
6610               gen_block_redirect (next, INSN_ADDRESSES (INSN_UID (next)), 1);
6611           }
6612         else if (type == TYPE_JUMP || type == TYPE_RETURN)
6613           {
6614             int addr = INSN_ADDRESSES (INSN_UID (insn));
6615             rtx far_label = 0;
6616             int dest_uid = 0;
6617             struct far_branch *bp;
6618
6619             if (type == TYPE_JUMP)
6620               {
6621                 far_label = XEXP (SET_SRC (PATTERN (insn)), 0);
6622                 dest_uid = get_dest_uid (far_label, max_uid);
6623                 if (! dest_uid)
6624                   {
6625                     /* Parse errors can lead to labels outside
6626                       the insn stream.  */
6627                     if (! NEXT_INSN (far_label))
6628                       continue;
6629
6630                     if (! optimize)
6631                       {
6632                         JUMP_LABEL (insn) = far_label;
6633                         LABEL_NUSES (far_label)++;
6634                       }
6635                     redirect_jump (insn, ret_rtx, 1);
6636                     far_label = 0;
6637                   }
6638               }
6639             bp = uid_branch[dest_uid];
6640             if (! bp)
6641               {
6642                 bp = (struct far_branch *) alloca (sizeof *bp);
6643                 uid_branch[dest_uid] = bp;
6644                 bp->prev = far_branch_list;
6645                 far_branch_list = bp;
6646                 bp->near_label = 0;
6647                 bp->far_label = far_label;
6648                 if (far_label)
6649                   LABEL_NUSES (far_label)++;
6650               }
6651             else if (bp->near_label && ! NEXT_INSN (bp->near_label))
6652               if (addr - bp->address <= CONDJUMP_MAX)
6653                 emit_label_after (bp->near_label, PREV_INSN (insn));
6654               else
6655                 {
6656                   gen_far_branch (bp);
6657                   bp->near_label = 0;
6658                 }
6659             else
6660               bp->near_label = 0;
6661             bp->address = addr;
6662             bp->insert_place = insn;
6663             if (! far_label)
6664               emit_insn_before (gen_block_branch_redirect (const0_rtx), insn);
6665             else
6666               gen_block_redirect (insn, addr, bp->near_label ? 2 : 0);
6667           }
6668       }
6669   /* Generate all pending far branches,
6670      and free our references to the far labels.  */
6671   while (far_branch_list)
6672     {
6673       if (far_branch_list->near_label
6674           && ! NEXT_INSN (far_branch_list->near_label))
6675         gen_far_branch (far_branch_list);
6676       if (optimize
6677           && far_branch_list->far_label
6678           && ! --LABEL_NUSES (far_branch_list->far_label))
6679         delete_insn (far_branch_list->far_label);
6680       far_branch_list = far_branch_list->prev;
6681     }
6682
6683   /* Instruction length information is no longer valid due to the new
6684      instructions that have been generated.  */
6685   init_insn_lengths ();
6686 }
6687
6688 /* Dump out instruction addresses, which is useful for debugging the
6689    constant pool table stuff.
6690
6691    If relaxing, output the label and pseudo-ops used to link together
6692    calls and the instruction which set the registers.
6693
6694    ??? The addresses printed by this routine for insns are nonsense for
6695    insns which are inside of a sequence where none of the inner insns have
6696    variable length.  This is because the second pass of shorten_branches
6697    does not bother to update them.  */
6698 void
6699 final_prescan_insn (rtx insn, rtx *opvec ATTRIBUTE_UNUSED,
6700                     int noperands ATTRIBUTE_UNUSED)
6701 {
6702   if (TARGET_DUMPISIZE)
6703     fprintf (asm_out_file, "\n! at %04x\n", INSN_ADDRESSES (INSN_UID (insn)));
6704
6705   if (TARGET_RELAX)
6706     {
6707       rtx note;
6708
6709       note = find_reg_note (insn, REG_LABEL_OPERAND, NULL_RTX);
6710       if (note)
6711         {
6712           rtx pattern;
6713
6714           pattern = PATTERN (insn);
6715           if (GET_CODE (pattern) == PARALLEL)
6716             pattern = XVECEXP (pattern, 0, 0);
6717           switch (GET_CODE (pattern))
6718             {
6719             case SET:
6720               if (GET_CODE (SET_SRC (pattern)) != CALL
6721                   && get_attr_type (insn) != TYPE_SFUNC)
6722                 {
6723                   targetm.asm_out.internal_label
6724                     (asm_out_file, "L", CODE_LABEL_NUMBER (XEXP (note, 0)));
6725                   break;
6726                 }
6727               /* else FALLTHROUGH */
6728             case CALL:
6729               asm_fprintf (asm_out_file, "\t.uses %LL%d\n",
6730                            CODE_LABEL_NUMBER (XEXP (note, 0)));
6731               break;
6732
6733             default:
6734               gcc_unreachable ();
6735             }
6736         }
6737     }
6738 }
6739
6740 /* Dump out any constants accumulated in the final pass.  These will
6741    only be labels.  */
6742 const char *
6743 output_jump_label_table (void)
6744 {
6745   int i;
6746
6747   if (pool_size)
6748     {
6749       fprintf (asm_out_file, "\t.align 2\n");
6750       for (i = 0; i < pool_size; i++)
6751         {
6752           pool_node *p = &pool_vector[i];
6753
6754           (*targetm.asm_out.internal_label) (asm_out_file, "L",
6755                                      CODE_LABEL_NUMBER (p->label));
6756           output_asm_insn (".long       %O0", &p->value);
6757         }
6758       pool_size = 0;
6759     }
6760
6761   return "";
6762 }
6763 \f
6764 /* A full frame looks like:
6765
6766    arg-5
6767    arg-4
6768    [ if current_function_anonymous_args
6769    arg-3
6770    arg-2
6771    arg-1
6772    arg-0 ]
6773    saved-fp
6774    saved-r10
6775    saved-r11
6776    saved-r12
6777    saved-pr
6778    local-n
6779    ..
6780    local-1
6781    local-0        <- fp points here.
6782
6783    Number of bytes pushed for anonymous args, used to pass information
6784    between expand_prologue and expand_epilogue.
6785
6786    Adjust the stack by SIZE bytes.  REG holds the rtl of the register to be
6787    adjusted.  If epilogue_p is zero, this is for a prologue; otherwise, it's
6788    for an epilogue and a negative value means that it's for a sibcall
6789    epilogue.  If LIVE_REGS_MASK is nonzero, it points to a HARD_REG_SET of
6790    all the registers that are about to be restored, and hence dead.  */
6791 static void
6792 output_stack_adjust (int size, rtx reg, int epilogue_p,
6793                      HARD_REG_SET *live_regs_mask, bool frame_p)
6794 {
6795   rtx (*emit_fn) (rtx) = frame_p ? &frame_insn : &emit_insn;
6796   if (size)
6797     {
6798       HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
6799
6800 /* This test is bogus, as output_stack_adjust is used to re-align the
6801    stack.  */
6802 #if 0
6803       gcc_assert (!(size % align));
6804 #endif
6805
6806       if (CONST_OK_FOR_ADD (size))
6807         emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size)));
6808       /* Try to do it with two partial adjustments; however, we must make
6809          sure that the stack is properly aligned at all times, in case
6810          an interrupt occurs between the two partial adjustments.  */
6811       else if (CONST_OK_FOR_ADD (size / 2 & -align)
6812                && CONST_OK_FOR_ADD (size - (size / 2 & -align)))
6813         {
6814           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size / 2 & -align)));
6815           emit_fn (GEN_ADD3 (reg, reg, GEN_INT (size - (size / 2 & -align))));
6816         }
6817       else
6818         {
6819           rtx const_reg;
6820           rtx insn;
6821           int temp = epilogue_p ? 7 : (TARGET_SH5 ? 0 : 1);
6822           int i;
6823
6824           /* If TEMP is invalid, we could temporarily save a general
6825              register to MACL.  However, there is currently no need
6826              to handle this case, so just die when we see it.  */
6827           if (epilogue_p < 0
6828               || current_function_interrupt
6829               || ! call_really_used_regs[temp] || fixed_regs[temp])
6830             temp = -1;
6831           if (temp < 0 && ! current_function_interrupt
6832               && (TARGET_SHMEDIA || epilogue_p >= 0))
6833             {
6834               HARD_REG_SET temps;
6835               COPY_HARD_REG_SET (temps, call_used_reg_set);
6836               AND_COMPL_HARD_REG_SET (temps, call_fixed_reg_set);
6837               if (epilogue_p > 0)
6838                 {
6839                   int nreg = 0;
6840                   if (crtl->return_rtx)
6841                     {
6842                       enum machine_mode mode;
6843                       mode = GET_MODE (crtl->return_rtx);
6844                       if (BASE_RETURN_VALUE_REG (mode) == FIRST_RET_REG)
6845                         nreg = HARD_REGNO_NREGS (FIRST_RET_REG, mode);
6846                     }
6847                   for (i = 0; i < nreg; i++)
6848                     CLEAR_HARD_REG_BIT (temps, FIRST_RET_REG + i);
6849                   if (crtl->calls_eh_return)
6850                     {
6851                       CLEAR_HARD_REG_BIT (temps, EH_RETURN_STACKADJ_REGNO);
6852                       for (i = 0; i <= 3; i++)
6853                         CLEAR_HARD_REG_BIT (temps, EH_RETURN_DATA_REGNO (i));
6854                     }
6855                 }
6856               if (TARGET_SHMEDIA && epilogue_p < 0)
6857                 for (i = FIRST_TARGET_REG; i <= LAST_TARGET_REG; i++)
6858                   CLEAR_HARD_REG_BIT (temps, i);
6859               if (epilogue_p <= 0)
6860                 {
6861                   for (i = FIRST_PARM_REG;
6862                        i < FIRST_PARM_REG + NPARM_REGS (SImode); i++)
6863                     CLEAR_HARD_REG_BIT (temps, i);
6864                   if (cfun->static_chain_decl != NULL)
6865                     CLEAR_HARD_REG_BIT (temps, STATIC_CHAIN_REGNUM);
6866                 }
6867               temp = scavenge_reg (&temps);
6868             }
6869           if (temp < 0 && live_regs_mask)
6870             {
6871               HARD_REG_SET temps;
6872
6873               COPY_HARD_REG_SET (temps, *live_regs_mask);
6874               CLEAR_HARD_REG_BIT (temps, REGNO (reg));
6875               temp = scavenge_reg (&temps);
6876             }
6877           if (temp < 0)
6878             {
6879               rtx adj_reg, tmp_reg, mem;
6880               
6881               /* If we reached here, the most likely case is the (sibcall)
6882                  epilogue for non SHmedia.  Put a special push/pop sequence
6883                  for such case as the last resort.  This looks lengthy but
6884                  would not be problem because it seems to be very
6885                  rare.  */
6886               
6887               gcc_assert (!TARGET_SHMEDIA && epilogue_p);
6888               
6889
6890                /* ??? There is still the slight possibility that r4 or
6891                   r5 have been reserved as fixed registers or assigned
6892                   as global registers, and they change during an
6893                   interrupt.  There are possible ways to handle this:
6894                      
6895                   - If we are adjusting the frame pointer (r14), we can do
6896                     with a single temp register and an ordinary push / pop
6897                     on the stack.
6898                   - Grab any call-used or call-saved registers (i.e. not
6899                     fixed or globals) for the temps we need.  We might
6900                     also grab r14 if we are adjusting the stack pointer.
6901                     If we can't find enough available registers, issue
6902                     a diagnostic and die - the user must have reserved
6903                     way too many registers.
6904                  But since all this is rather unlikely to happen and
6905                  would require extra testing, we just die if r4 / r5
6906                  are not available.  */
6907               gcc_assert (!fixed_regs[4] && !fixed_regs[5]
6908                           && !global_regs[4] && !global_regs[5]);
6909
6910               adj_reg = gen_rtx_REG (GET_MODE (reg), 4);
6911               tmp_reg = gen_rtx_REG (GET_MODE (reg), 5);
6912               emit_move_insn (gen_tmp_stack_mem (Pmode, reg), adj_reg);
6913               emit_insn (GEN_MOV (adj_reg, GEN_INT (size)));
6914               emit_insn (GEN_ADD3 (adj_reg, adj_reg, reg));
6915               mem = gen_tmp_stack_mem (Pmode, gen_rtx_PRE_DEC (Pmode, adj_reg));
6916               emit_move_insn (mem, tmp_reg);
6917               emit_move_insn (tmp_reg, gen_tmp_stack_mem (Pmode, reg));
6918               mem = gen_tmp_stack_mem (Pmode, gen_rtx_PRE_DEC (Pmode, adj_reg));
6919               emit_move_insn (mem, tmp_reg);
6920               emit_move_insn (reg, adj_reg);
6921               mem = gen_tmp_stack_mem (Pmode, gen_rtx_POST_INC (Pmode, reg));
6922               emit_move_insn (adj_reg, mem);
6923               mem = gen_tmp_stack_mem (Pmode, gen_rtx_POST_INC (Pmode, reg));
6924               emit_move_insn (tmp_reg, mem);
6925               /* Tell flow the insns that pop r4/r5 aren't dead.  */
6926               emit_use (tmp_reg);
6927               emit_use (adj_reg);
6928               return;
6929             }
6930           const_reg = gen_rtx_REG (GET_MODE (reg), temp);
6931
6932           /* If SIZE is negative, subtract the positive value.
6933              This sometimes allows a constant pool entry to be shared
6934              between prologue and epilogue code.  */
6935           if (size < 0)
6936             {
6937               emit_insn (GEN_MOV (const_reg, GEN_INT (-size)));
6938               insn = emit_fn (GEN_SUB3 (reg, reg, const_reg));
6939             }
6940           else
6941             {
6942               emit_insn (GEN_MOV (const_reg, GEN_INT (size)));
6943               insn = emit_fn (GEN_ADD3 (reg, reg, const_reg));
6944             }
6945           add_reg_note (insn, REG_FRAME_RELATED_EXPR,
6946                         gen_rtx_SET (VOIDmode, reg,
6947                                      gen_rtx_PLUS (SImode, reg,
6948                                                    GEN_INT (size))));
6949         }
6950     }
6951 }
6952
6953 /* Emit the specified insn and mark it as frame related.
6954    FIXME: Rename this to emit_frame_insn.  */
6955 static rtx
6956 frame_insn (rtx x)
6957 {
6958   x = emit_insn (x);
6959   RTX_FRAME_RELATED_P (x) = 1;
6960   return x;
6961 }
6962
6963 /* Output RTL to push register RN onto the stack.  */
6964 static rtx
6965 push (int rn)
6966 {
6967   rtx x;
6968   if (rn == FPUL_REG)
6969     x = gen_push_fpul ();
6970   else if (rn == FPSCR_REG)
6971     x = gen_push_fpscr ();
6972   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD
6973            && ! TARGET_FPU_SINGLE && FP_OR_XD_REGISTER_P (rn))
6974     {
6975       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
6976         return NULL_RTX;
6977       x = gen_push_4 (gen_rtx_REG (DFmode, rn));
6978     }
6979   else if (TARGET_SH2E && FP_REGISTER_P (rn))
6980     x = gen_push_e (gen_rtx_REG (SFmode, rn));
6981   else
6982     x = gen_push (gen_rtx_REG (SImode, rn));
6983
6984   x = frame_insn (x);
6985   add_reg_note (x, REG_INC, gen_rtx_REG (SImode, STACK_POINTER_REGNUM));
6986   return x;
6987 }
6988
6989 /* Output RTL to pop register RN from the stack.  */
6990 static void
6991 pop (int rn)
6992 {
6993   rtx x, sp_reg, reg;
6994   if (rn == FPUL_REG)
6995     x = gen_pop_fpul ();
6996   else if (rn == FPSCR_REG)
6997     x = gen_pop_fpscr ();
6998   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD
6999            && ! TARGET_FPU_SINGLE && FP_OR_XD_REGISTER_P (rn))
7000     {
7001       if (FP_REGISTER_P (rn) && (rn - FIRST_FP_REG) & 1)
7002         return;
7003       x = gen_pop_4 (gen_rtx_REG (DFmode, rn));
7004     }
7005   else if (TARGET_SH2E && FP_REGISTER_P (rn))
7006     x = gen_pop_e (gen_rtx_REG (SFmode, rn));
7007   else
7008     x = gen_pop (gen_rtx_REG (SImode, rn));
7009
7010   x = emit_insn (x);
7011
7012   sp_reg = gen_rtx_REG (SImode, STACK_POINTER_REGNUM);
7013   reg = copy_rtx (GET_CODE (PATTERN (x)) == PARALLEL
7014                   ? SET_DEST (XVECEXP (PATTERN (x), 0, 0))
7015                   : SET_DEST (PATTERN (x)));
7016   add_reg_note (x, REG_CFA_RESTORE, reg);
7017   add_reg_note (x, REG_CFA_ADJUST_CFA,
7018                 gen_rtx_SET (SImode, sp_reg,
7019                              plus_constant (SImode, sp_reg,
7020                                             GET_MODE_SIZE (GET_MODE (reg)))));
7021   add_reg_note (x, REG_INC, gen_rtx_REG (SImode, STACK_POINTER_REGNUM));
7022   RTX_FRAME_RELATED_P (x) = 1;
7023 }
7024
7025 /* Generate code to push the regs specified in the mask.  */
7026 static void
7027 push_regs (HARD_REG_SET *mask, int interrupt_handler)
7028 {
7029   int i = interrupt_handler ? LAST_BANKED_REG + 1 : 0;
7030   int skip_fpscr = 0;
7031
7032   /* Push PR last; this gives better latencies after the prologue, and
7033      candidates for the return delay slot when there are no general
7034      registers pushed.  */
7035   for (; i < FIRST_PSEUDO_REGISTER; i++)
7036     {
7037       /* If this is an interrupt handler, and the SZ bit varies,
7038          and we have to push any floating point register, we need
7039          to switch to the correct precision first.  */
7040       if (i == FIRST_FP_REG && interrupt_handler && TARGET_FMOVD
7041           && hard_reg_set_intersect_p (*mask, reg_class_contents[DF_REGS]))
7042         {
7043           HARD_REG_SET unsaved;
7044
7045           push (FPSCR_REG);
7046           COMPL_HARD_REG_SET (unsaved, *mask);
7047           fpscr_set_from_mem (NORMAL_MODE (FP_MODE), unsaved);
7048           skip_fpscr = 1;
7049         }
7050       if (i != PR_REG
7051           && (i != FPSCR_REG || ! skip_fpscr)
7052           && TEST_HARD_REG_BIT (*mask, i))
7053         {
7054         /* If the ISR has RESBANK attribute assigned, don't push any of
7055            the following registers - R0-R14, MACH, MACL and GBR.  */
7056       if (! (sh_cfun_resbank_handler_p ()
7057              && ((i >= FIRST_GENERAL_REG && i < LAST_GENERAL_REG)
7058                  || i == MACH_REG
7059                  || i == MACL_REG
7060                  || i == GBR_REG)))
7061           push (i);
7062         }
7063     }
7064
7065   /* Push banked registers last to improve delay slot opportunities.  */
7066   if (interrupt_handler)
7067     {
7068       bool use_movml = false;
7069
7070       if (TARGET_SH2A)
7071         {
7072           unsigned int count = 0;
7073
7074           for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
7075             if (TEST_HARD_REG_BIT (*mask, i))
7076               count++;
7077             else
7078               break;
7079
7080           /* Use movml when all banked registers are pushed.  */
7081           if (count == LAST_BANKED_REG - FIRST_BANKED_REG + 1)
7082             use_movml = true;
7083         }
7084
7085       if (sh_cfun_resbank_handler_p ())
7086         ; /* Do nothing.  */
7087       else if (use_movml)
7088         {
7089           rtx x, mem, reg, set;
7090           rtx sp_reg = gen_rtx_REG (SImode, STACK_POINTER_REGNUM);
7091
7092           /* We must avoid scheduling multiple store insn with another
7093              insns.  */
7094           emit_insn (gen_blockage ());
7095           x = gen_movml_push_banked (sp_reg);
7096           x = frame_insn (x);
7097           for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
7098             {
7099               mem = gen_rtx_MEM (SImode, plus_constant (Pmode, sp_reg, i * 4));
7100               reg = gen_rtx_REG (SImode, i);
7101               add_reg_note (x, REG_CFA_OFFSET, gen_rtx_SET (SImode, mem, reg));
7102             }
7103
7104           set = gen_rtx_SET (SImode, sp_reg,
7105                              plus_constant (Pmode, sp_reg, - 32));
7106           add_reg_note (x, REG_CFA_ADJUST_CFA, set);
7107           emit_insn (gen_blockage ());
7108         }
7109       else
7110         for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
7111           if (TEST_HARD_REG_BIT (*mask, i))
7112             push (i);
7113     }
7114
7115   /* Don't push PR register for an ISR with RESBANK attribute assigned.  */
7116   if (TEST_HARD_REG_BIT (*mask, PR_REG) && !sh_cfun_resbank_handler_p ())
7117     push (PR_REG);
7118 }
7119
7120 /* Calculate how much extra space is needed to save all callee-saved
7121    target registers.
7122    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
7123 static int
7124 shmedia_target_regs_stack_space (HARD_REG_SET *live_regs_mask)
7125 {
7126   int reg;
7127   int stack_space = 0;
7128   int interrupt_handler = sh_cfun_interrupt_handler_p ();
7129
7130   for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
7131     if ((! call_really_used_regs[reg] || interrupt_handler)
7132         && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
7133       /* Leave space to save this target register on the stack,
7134          in case target register allocation wants to use it.  */
7135       stack_space += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
7136   return stack_space;
7137 }
7138
7139 /* Decide whether we should reserve space for callee-save target registers,
7140    in case target register allocation wants to use them.  REGS_SAVED is
7141    the space, in bytes, that is already required for register saves.
7142    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
7143 static int
7144 shmedia_reserve_space_for_target_registers_p (int regs_saved,
7145                                               HARD_REG_SET *live_regs_mask)
7146 {
7147   if (optimize_size)
7148     return 0;
7149   return shmedia_target_regs_stack_space (live_regs_mask) <= regs_saved;
7150 }
7151
7152 /* Decide how much space to reserve for callee-save target registers
7153    in case target register allocation wants to use them.
7154    LIVE_REGS_MASK is the register mask calculated by calc_live_regs.  */
7155 static int
7156 shmedia_target_regs_stack_adjust (HARD_REG_SET *live_regs_mask)
7157 {
7158   if (shmedia_space_reserved_for_target_registers)
7159     return shmedia_target_regs_stack_space (live_regs_mask);
7160   else
7161     return 0;
7162 }
7163
7164 /* Work out the registers which need to be saved, both as a mask and a
7165    count of saved words.  Return the count.
7166
7167    If doing a pragma interrupt function, then push all regs used by the
7168    function, and if we call another function (we can tell by looking at PR),
7169    make sure that all the regs it clobbers are safe too.  */
7170 static int
7171 calc_live_regs (HARD_REG_SET *live_regs_mask)
7172 {
7173   unsigned int reg;
7174   int count;
7175   tree attrs;
7176   bool interrupt_or_trapa_handler, trapa_handler, interrupt_handler;
7177   bool nosave_low_regs;
7178   int pr_live, has_call;
7179
7180   attrs = DECL_ATTRIBUTES (current_function_decl);
7181   interrupt_or_trapa_handler = sh_cfun_interrupt_handler_p ();
7182   trapa_handler = lookup_attribute ("trapa_handler", attrs) != NULL_TREE;
7183   interrupt_handler = interrupt_or_trapa_handler && ! trapa_handler;
7184   nosave_low_regs = lookup_attribute ("nosave_low_regs", attrs) != NULL_TREE;
7185
7186   CLEAR_HARD_REG_SET (*live_regs_mask);
7187   if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD && interrupt_handler
7188       && df_regs_ever_live_p (FPSCR_REG))
7189     target_flags &= ~MASK_FPU_SINGLE;
7190   /* If we can save a lot of saves by switching to double mode, do that.  */
7191   else if ((TARGET_SH4 || TARGET_SH2A_DOUBLE) && TARGET_FMOVD
7192            && TARGET_FPU_SINGLE)
7193     for (count = 0, reg = FIRST_FP_REG; reg <= LAST_FP_REG; reg += 2)
7194       if (df_regs_ever_live_p (reg) && df_regs_ever_live_p (reg+1)
7195           && (! call_really_used_regs[reg]
7196               || interrupt_handler)
7197           && ++count > 2)
7198         {
7199           target_flags &= ~MASK_FPU_SINGLE;
7200           break;
7201         }
7202   /* PR_MEDIA_REG is a general purpose register, thus global_alloc already
7203      knows how to use it.  That means the pseudo originally allocated for
7204      the initial value can become the PR_MEDIA_REG hard register, as seen for
7205      execute/20010122-1.c:test9.  */
7206   if (TARGET_SHMEDIA)
7207     /* ??? this function is called from initial_elimination_offset, hence we
7208        can't use the result of sh_media_register_for_return here.  */
7209     pr_live = sh_pr_n_sets ();
7210   else
7211     {
7212       rtx pr_initial = has_hard_reg_initial_val (Pmode, PR_REG);
7213       pr_live = (pr_initial
7214                  ? (!REG_P (pr_initial)
7215                     || REGNO (pr_initial) != (PR_REG))
7216                  : df_regs_ever_live_p (PR_REG));
7217       /* For Shcompact, if not optimizing, we end up with a memory reference
7218          using the return address pointer for __builtin_return_address even
7219          though there is no actual need to put the PR register on the stack.  */
7220       pr_live |= df_regs_ever_live_p (RETURN_ADDRESS_POINTER_REGNUM);
7221     }
7222   /* Force PR to be live if the prologue has to call the SHmedia
7223      argument decoder or register saver.  */
7224   if (TARGET_SHCOMPACT
7225       && ((crtl->args.info.call_cookie
7226            & ~ CALL_COOKIE_RET_TRAMP (1))
7227           || crtl->saves_all_registers))
7228     pr_live = 1;
7229   has_call = TARGET_SHMEDIA ? ! leaf_function_p () : pr_live;
7230   for (count = 0, reg = FIRST_PSEUDO_REGISTER; reg-- != 0; )
7231     {
7232       if (reg == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG)
7233           ? pr_live
7234           : interrupt_handler
7235           ? (/* Need to save all the regs ever live.  */
7236              (df_regs_ever_live_p (reg)
7237               || (call_really_used_regs[reg]
7238                   && (! fixed_regs[reg] || reg == MACH_REG || reg == MACL_REG
7239                       || reg == PIC_OFFSET_TABLE_REGNUM)
7240                   && has_call)
7241               || (TARGET_SHMEDIA && has_call
7242                   && REGISTER_NATURAL_MODE (reg) == SImode
7243                   && (GENERAL_REGISTER_P (reg) || TARGET_REGISTER_P (reg))))
7244              && reg != STACK_POINTER_REGNUM && reg != ARG_POINTER_REGNUM
7245              && reg != RETURN_ADDRESS_POINTER_REGNUM
7246              && reg != T_REG && reg != GBR_REG
7247              /* Push fpscr only on targets which have FPU */
7248              && (reg != FPSCR_REG || TARGET_FPU_ANY))
7249           : (/* Only push those regs which are used and need to be saved.  */
7250              (TARGET_SHCOMPACT
7251               && flag_pic
7252               && crtl->args.info.call_cookie
7253               && reg == PIC_OFFSET_TABLE_REGNUM)
7254              || (df_regs_ever_live_p (reg)
7255                  && ((!call_really_used_regs[reg]
7256                       && !(reg != PIC_OFFSET_TABLE_REGNUM
7257                            && fixed_regs[reg] && call_used_regs[reg]))
7258                      || (trapa_handler && reg == FPSCR_REG && TARGET_FPU_ANY)))
7259              || (crtl->calls_eh_return
7260                  && (reg == EH_RETURN_DATA_REGNO (0)
7261                      || reg == EH_RETURN_DATA_REGNO (1)
7262                      || reg == EH_RETURN_DATA_REGNO (2)
7263                      || reg == EH_RETURN_DATA_REGNO (3)))
7264              || ((reg == MACL_REG || reg == MACH_REG)
7265                  && df_regs_ever_live_p (reg)
7266                  && sh_cfun_attr_renesas_p ())
7267              ))
7268         {
7269           SET_HARD_REG_BIT (*live_regs_mask, reg);
7270           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
7271
7272           if ((TARGET_SH4 || TARGET_SH2A_DOUBLE || TARGET_SH5) && TARGET_FMOVD
7273               && GET_MODE_CLASS (REGISTER_NATURAL_MODE (reg)) == MODE_FLOAT)
7274             {
7275               if (FP_REGISTER_P (reg))
7276                 {
7277                   if (! TARGET_FPU_SINGLE && ! df_regs_ever_live_p (reg ^ 1))
7278                     {
7279                       SET_HARD_REG_BIT (*live_regs_mask, (reg ^ 1));
7280                       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg ^ 1));
7281                     }
7282                 }
7283               else if (XD_REGISTER_P (reg))
7284                 {
7285                   /* Must switch to double mode to access these registers.  */
7286                   target_flags &= ~MASK_FPU_SINGLE;
7287                 }
7288             }
7289         }
7290       if (nosave_low_regs && reg == R8_REG)
7291         break;
7292     }
7293   /* If we have a target register optimization pass after prologue / epilogue
7294      threading, we need to assume all target registers will be live even if
7295      they aren't now.  */
7296   if (flag_branch_target_load_optimize2
7297       && TARGET_SAVE_ALL_TARGET_REGS
7298       && shmedia_space_reserved_for_target_registers)
7299     for (reg = LAST_TARGET_REG; reg >= FIRST_TARGET_REG; reg--)
7300       if ((! call_really_used_regs[reg] || interrupt_handler)
7301           && ! TEST_HARD_REG_BIT (*live_regs_mask, reg))
7302         {
7303           SET_HARD_REG_BIT (*live_regs_mask, reg);
7304           count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (reg));
7305         }
7306   /* If this is an interrupt handler, we don't have any call-clobbered
7307      registers we can conveniently use for target register save/restore.
7308      Make sure we save at least one general purpose register when we need
7309      to save target registers.  */
7310   if (interrupt_handler
7311       && hard_reg_set_intersect_p (*live_regs_mask,
7312                                    reg_class_contents[TARGET_REGS])
7313       && ! hard_reg_set_intersect_p (*live_regs_mask,
7314                                      reg_class_contents[GENERAL_REGS]))
7315     {
7316       SET_HARD_REG_BIT (*live_regs_mask, R0_REG);
7317       count += GET_MODE_SIZE (REGISTER_NATURAL_MODE (R0_REG));
7318     }
7319
7320   return count;
7321 }
7322
7323 /* Code to generate prologue and epilogue sequences */
7324
7325 /* PUSHED is the number of bytes that are being pushed on the
7326    stack for register saves.  Return the frame size, padded
7327    appropriately so that the stack stays properly aligned.  */
7328 static HOST_WIDE_INT
7329 rounded_frame_size (int pushed)
7330 {
7331   HOST_WIDE_INT size = get_frame_size ();
7332   HOST_WIDE_INT align = STACK_BOUNDARY / BITS_PER_UNIT;
7333
7334   if (ACCUMULATE_OUTGOING_ARGS)
7335     size += crtl->outgoing_args_size;
7336
7337   return ((size + pushed + align - 1) & -align) - pushed;
7338 }
7339
7340 /* Choose a call-clobbered target-branch register that remains
7341    unchanged along the whole function.  We set it up as the return
7342    value in the prologue.  */
7343 int
7344 sh_media_register_for_return (void)
7345 {
7346   int regno;
7347   int tr0_used;
7348
7349   if (! crtl->is_leaf)
7350     return -1;
7351   if (lookup_attribute ("interrupt_handler",
7352                         DECL_ATTRIBUTES (current_function_decl)))
7353     return -1;
7354   if (sh_cfun_interrupt_handler_p ())
7355     return -1;
7356
7357   tr0_used = flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM);
7358
7359   for (regno = FIRST_TARGET_REG + tr0_used; regno <= LAST_TARGET_REG; regno++)
7360     if (call_really_used_regs[regno] && ! df_regs_ever_live_p (regno))
7361       return regno;
7362
7363   return -1;
7364 }
7365
7366 /* The maximum registers we need to save are:
7367    - 62 general purpose registers (r15 is stack pointer, r63 is zero)
7368    - 32 floating point registers (for each pair, we save none,
7369          one single precision value, or a double precision value).
7370    -  8 target registers
7371    -  add 1 entry for a delimiter.  */
7372 #define MAX_SAVED_REGS (62+32+8)
7373
7374 typedef struct save_entry_s
7375 {
7376   unsigned char reg;
7377   unsigned char mode;
7378   short offset;
7379 } save_entry;
7380
7381 #define MAX_TEMPS 4
7382
7383 /* There will be a delimiter entry with VOIDmode both at the start and the
7384    end of a filled in schedule.  The end delimiter has the offset of the
7385    save with the smallest (i.e. most negative) offset.  */
7386 typedef struct save_schedule_s
7387 {
7388   save_entry entries[MAX_SAVED_REGS + 2];
7389   int temps[MAX_TEMPS+1];
7390 } save_schedule;
7391
7392 /* Fill in SCHEDULE according to LIVE_REGS_MASK.  If RESTORE is nonzero,
7393    use reverse order.  Returns the last entry written to (not counting
7394    the delimiter).  OFFSET_BASE is a number to be added to all offset
7395    entries.  */
7396 static save_entry *
7397 sh5_schedule_saves (HARD_REG_SET *live_regs_mask, save_schedule *schedule,
7398                     int offset_base)
7399 {
7400   int align, i;
7401   save_entry *entry = schedule->entries;
7402   int tmpx = 0;
7403   int offset;
7404
7405   if (! current_function_interrupt)
7406     for (i = FIRST_GENERAL_REG; tmpx < MAX_TEMPS && i <= LAST_GENERAL_REG; i++)
7407       if (call_really_used_regs[i] && ! fixed_regs[i] && i != PR_MEDIA_REG
7408           && ! FUNCTION_ARG_REGNO_P (i)
7409           && i != FIRST_RET_REG
7410           && ! (cfun->static_chain_decl != NULL && i == STATIC_CHAIN_REGNUM)
7411           && ! (crtl->calls_eh_return
7412                 && (i == EH_RETURN_STACKADJ_REGNO
7413                     || ((unsigned) i >= EH_RETURN_DATA_REGNO (0)
7414                         && (unsigned) i <= EH_RETURN_DATA_REGNO (3)))))
7415         schedule->temps[tmpx++] = i;
7416   entry->reg = -1;
7417   entry->mode = VOIDmode;
7418   entry->offset = offset_base;
7419   entry++;
7420   /* We loop twice: first, we save 8-byte aligned registers in the
7421      higher addresses, that are known to be aligned.  Then, we
7422      proceed to saving 32-bit registers that don't need 8-byte
7423      alignment.
7424      If this is an interrupt function, all registers that need saving
7425      need to be saved in full.  moreover, we need to postpone saving
7426      target registers till we have saved some general purpose registers
7427      we can then use as scratch registers.  */
7428   offset = offset_base;
7429   for (align = 1; align >= 0; align--)
7430     {
7431       for (i = FIRST_PSEUDO_REGISTER - 1; i >= 0; i--)
7432         if (TEST_HARD_REG_BIT (*live_regs_mask, i))
7433           {
7434             enum machine_mode mode = REGISTER_NATURAL_MODE (i);
7435             int reg = i;
7436
7437             if (current_function_interrupt)
7438               {
7439                 if (TARGET_REGISTER_P (i))
7440                   continue;
7441                 if (GENERAL_REGISTER_P (i))
7442                   mode = DImode;
7443               }
7444             if (mode == SFmode && (i % 2) == 1
7445                 && ! TARGET_FPU_SINGLE && FP_REGISTER_P (i)
7446                 && (TEST_HARD_REG_BIT (*live_regs_mask, (i ^ 1))))
7447               {
7448                 mode = DFmode;
7449                 i--;
7450                 reg--;
7451               }
7452
7453             /* If we're doing the aligned pass and this is not aligned,
7454                or we're doing the unaligned pass and this is aligned,
7455                skip it.  */
7456             if ((GET_MODE_SIZE (mode) % (STACK_BOUNDARY / BITS_PER_UNIT) == 0)
7457                 != align)
7458               continue;
7459
7460             if (current_function_interrupt
7461                 && GENERAL_REGISTER_P (i)
7462                 && tmpx < MAX_TEMPS)
7463               schedule->temps[tmpx++] = i;
7464
7465             offset -= GET_MODE_SIZE (mode);
7466             entry->reg = i;
7467             entry->mode = mode;
7468             entry->offset = offset;
7469             entry++;
7470           }
7471       if (align && current_function_interrupt)
7472         for (i = LAST_TARGET_REG; i >= FIRST_TARGET_REG; i--)
7473           if (TEST_HARD_REG_BIT (*live_regs_mask, i))
7474             {
7475               offset -= GET_MODE_SIZE (DImode);
7476               entry->reg = i;
7477               entry->mode = DImode;
7478               entry->offset = offset;
7479               entry++;
7480             }
7481     }
7482   entry->reg = -1;
7483   entry->mode = VOIDmode;
7484   entry->offset = offset;
7485   schedule->temps[tmpx] = -1;
7486   return entry - 1;
7487 }
7488
7489 /* Expand code for the function prologue.  */
7490 void
7491 sh_expand_prologue (void)
7492 {
7493   HARD_REG_SET live_regs_mask;
7494   int d, i;
7495   int d_rounding = 0;
7496   int save_flags = target_flags;
7497   int pretend_args;
7498   int stack_usage;
7499   tree sp_switch_attr
7500     = lookup_attribute ("sp_switch", DECL_ATTRIBUTES (current_function_decl));
7501
7502   current_function_interrupt = sh_cfun_interrupt_handler_p ();
7503
7504   /* We have pretend args if we had an object sent partially in registers
7505      and partially on the stack, e.g. a large structure.  */
7506   pretend_args = crtl->args.pretend_args_size;
7507   if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl)
7508       && (NPARM_REGS(SImode)
7509           > crtl->args.info.arg_count[(int) SH_ARG_INT]))
7510     pretend_args = 0;
7511
7512   output_stack_adjust (-pretend_args
7513                        - crtl->args.info.stack_regs * 8,
7514                        stack_pointer_rtx, 0, NULL, true);
7515   stack_usage = pretend_args + crtl->args.info.stack_regs * 8;
7516
7517   if (TARGET_SHCOMPACT && flag_pic && crtl->args.info.call_cookie)
7518     /* We're going to use the PIC register to load the address of the
7519        incoming-argument decoder and/or of the return trampoline from
7520        the GOT, so make sure the PIC register is preserved and
7521        initialized.  */
7522     df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
7523
7524   if (TARGET_SHCOMPACT
7525       && (crtl->args.info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
7526     {
7527       int reg;
7528
7529       /* First, make all registers with incoming arguments that will
7530          be pushed onto the stack live, so that register renaming
7531          doesn't overwrite them.  */
7532       for (reg = 0; reg < NPARM_REGS (SImode); reg++)
7533         if (CALL_COOKIE_STACKSEQ_GET (crtl->args.info.call_cookie)
7534             >= NPARM_REGS (SImode) - reg)
7535           for (; reg < NPARM_REGS (SImode); reg++)
7536             emit_insn (gen_shcompact_preserve_incoming_args
7537                        (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
7538         else if (CALL_COOKIE_INT_REG_GET
7539                  (crtl->args.info.call_cookie, reg) == 1)
7540           emit_insn (gen_shcompact_preserve_incoming_args
7541                      (gen_rtx_REG (SImode, FIRST_PARM_REG + reg)));
7542
7543       emit_move_insn (gen_rtx_REG (Pmode, MACL_REG),
7544                       stack_pointer_rtx);
7545       emit_move_insn (gen_rtx_REG (SImode, R0_REG),
7546                       GEN_INT (crtl->args.info.call_cookie));
7547       emit_move_insn (gen_rtx_REG (SImode, MACH_REG),
7548                       gen_rtx_REG (SImode, R0_REG));
7549     }
7550   else if (TARGET_SHMEDIA)
7551     {
7552       int tr = sh_media_register_for_return ();
7553
7554       if (tr >= 0)
7555         emit_move_insn (gen_rtx_REG (DImode, tr),
7556                         gen_rtx_REG (DImode, PR_MEDIA_REG));
7557     }
7558
7559   /* Emit the code for SETUP_VARARGS.  */
7560   if (cfun->stdarg)
7561     {
7562       if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl))
7563         {
7564           /* Push arg regs as if they'd been provided by caller in stack.  */
7565           for (i = 0; i < NPARM_REGS(SImode); i++)
7566             {
7567               int rn = NPARM_REGS(SImode) + FIRST_PARM_REG - i - 1;
7568
7569               if (i >= (NPARM_REGS(SImode)
7570                         - crtl->args.info.arg_count[(int) SH_ARG_INT]
7571                         ))
7572                 break;
7573               push (rn);
7574               stack_usage += GET_MODE_SIZE (SImode);
7575             }
7576         }
7577     }
7578
7579   /* If we're supposed to switch stacks at function entry, do so now.  */
7580   if (sp_switch_attr)
7581     {
7582       rtx lab, newsrc;
7583       /* The argument specifies a variable holding the address of the
7584          stack the interrupt function should switch to/from at entry/exit.  */
7585       tree arg = TREE_VALUE ( TREE_VALUE (sp_switch_attr));
7586       const char *s
7587         = ggc_strdup (TREE_STRING_POINTER (arg));
7588       rtx sp_switch = gen_rtx_SYMBOL_REF (Pmode, s);
7589
7590       lab = add_constant (sp_switch, SImode, 0);
7591       newsrc = gen_rtx_LABEL_REF (VOIDmode, lab);
7592
7593       emit_insn (gen_sp_switch_1 (newsrc));
7594     }
7595
7596   d = calc_live_regs (&live_regs_mask);
7597   /* ??? Maybe we could save some switching if we can move a mode switch
7598      that already happens to be at the function start into the prologue.  */
7599   if (target_flags != save_flags && ! current_function_interrupt)
7600     emit_insn (gen_toggle_sz ());
7601
7602   if (TARGET_SH5)
7603     {
7604       int offset_base, offset;
7605       rtx r0 = NULL_RTX;
7606       int offset_in_r0 = -1;
7607       int sp_in_r0 = 0;
7608       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
7609       int total_size, save_size;
7610       save_schedule schedule;
7611       save_entry *entry;
7612       int *tmp_pnt;
7613
7614       if (call_really_used_regs[R0_REG] && ! fixed_regs[R0_REG]
7615           && ! current_function_interrupt)
7616         r0 = gen_rtx_REG (Pmode, R0_REG);
7617
7618       /* D is the actual number of bytes that we need for saving registers,
7619          however, in initial_elimination_offset we have committed to using
7620          an additional TREGS_SPACE amount of bytes - in order to keep both
7621          addresses to arguments supplied by the caller and local variables
7622          valid, we must keep this gap.  Place it between the incoming
7623          arguments and the actually saved registers in a bid to optimize
7624          locality of reference.  */
7625       total_size = d + tregs_space;
7626       total_size += rounded_frame_size (total_size);
7627       save_size = total_size - rounded_frame_size (d);
7628       if (save_size % (STACK_BOUNDARY / BITS_PER_UNIT))
7629         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
7630                         - save_size % (STACK_BOUNDARY / BITS_PER_UNIT));
7631
7632       /* If adjusting the stack in a single step costs nothing extra, do so.
7633          I.e. either if a single addi is enough, or we need a movi anyway,
7634          and we don't exceed the maximum offset range (the test for the
7635          latter is conservative for simplicity).  */
7636       if (TARGET_SHMEDIA
7637           && (CONST_OK_FOR_I10 (-total_size)
7638               || (! CONST_OK_FOR_I10 (-(save_size + d_rounding))
7639                   && total_size <= 2044)))
7640         d_rounding = total_size - save_size;
7641
7642       offset_base = d + d_rounding;
7643
7644       output_stack_adjust (-(save_size + d_rounding), stack_pointer_rtx,
7645                            0, NULL, true);
7646       stack_usage += save_size + d_rounding;
7647
7648       sh5_schedule_saves (&live_regs_mask, &schedule, offset_base);
7649       tmp_pnt = schedule.temps;
7650       for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
7651         {
7652           enum machine_mode mode = (enum machine_mode) entry->mode;
7653           unsigned int reg = entry->reg;
7654           rtx reg_rtx, mem_rtx, pre_dec = NULL_RTX;
7655           rtx orig_reg_rtx;
7656
7657           offset = entry->offset;
7658
7659           reg_rtx = gen_rtx_REG (mode, reg);
7660
7661           mem_rtx = gen_frame_mem (mode,
7662                                    gen_rtx_PLUS (Pmode,
7663                                                  stack_pointer_rtx,
7664                                                  GEN_INT (offset)));
7665
7666           if (!memory_address_p (mode, XEXP (mem_rtx, 0)))
7667             {
7668               gcc_assert (r0);
7669               mem_rtx = NULL_RTX;
7670             }
7671
7672           if (HAVE_PRE_DECREMENT
7673               && (offset_in_r0 - offset == GET_MODE_SIZE (mode)
7674                   || mem_rtx == NULL_RTX
7675                   || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
7676             {
7677               pre_dec = gen_frame_mem (mode, gen_rtx_PRE_DEC (Pmode, r0));
7678
7679               if (!memory_address_p (mode, XEXP (pre_dec, 0)))
7680                 pre_dec = NULL_RTX;
7681               else
7682                 {
7683                   mem_rtx = NULL_RTX;
7684                   offset += GET_MODE_SIZE (mode);
7685                 }
7686             }
7687
7688           if (mem_rtx != NULL_RTX)
7689             goto addr_ok;
7690
7691           if (offset_in_r0 == -1)
7692             {
7693               emit_move_insn (r0, GEN_INT (offset));
7694               offset_in_r0 = offset;
7695             }
7696           else if (offset != offset_in_r0)
7697             {
7698               emit_move_insn (r0,
7699                               gen_rtx_PLUS
7700                               (Pmode, r0,
7701                                GEN_INT (offset - offset_in_r0)));
7702               offset_in_r0 += offset - offset_in_r0;
7703             }
7704
7705           if (pre_dec != NULL_RTX)
7706             {
7707               if (! sp_in_r0)
7708                 {
7709                   emit_move_insn (r0,
7710                                   gen_rtx_PLUS
7711                                   (Pmode, r0, stack_pointer_rtx));
7712                   sp_in_r0 = 1;
7713                 }
7714
7715               offset -= GET_MODE_SIZE (mode);
7716               offset_in_r0 -= GET_MODE_SIZE (mode);
7717
7718               mem_rtx = pre_dec;
7719             }
7720           else if (sp_in_r0)
7721             mem_rtx = gen_frame_mem (mode, r0);
7722           else
7723             mem_rtx = gen_frame_mem (mode,
7724                                      gen_rtx_PLUS (Pmode,
7725                                                    stack_pointer_rtx,
7726                                                    r0));
7727
7728           /* We must not use an r0-based address for target-branch
7729              registers or for special registers without pre-dec
7730              memory addresses, since we store their values in r0
7731              first.  */
7732           gcc_assert (!TARGET_REGISTER_P (reg)
7733                       && ((reg != PR_REG && !SPECIAL_REGISTER_P (reg))
7734                           || mem_rtx == pre_dec));
7735           
7736         addr_ok:
7737           orig_reg_rtx = reg_rtx;
7738           if (TARGET_REGISTER_P (reg)
7739               || ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
7740                   && mem_rtx != pre_dec))
7741             {
7742               rtx tmp_reg = gen_rtx_REG (GET_MODE (reg_rtx), *tmp_pnt);
7743
7744               emit_move_insn (tmp_reg, reg_rtx);
7745
7746               if (REGNO (tmp_reg) == R0_REG)
7747                 {
7748                   offset_in_r0 = -1;
7749                   sp_in_r0 = 0;
7750                   gcc_assert (!refers_to_regno_p
7751                               (R0_REG, R0_REG+1, mem_rtx, (rtx *) 0));
7752                 }
7753
7754               if (*++tmp_pnt <= 0)
7755                 tmp_pnt = schedule.temps;
7756
7757               reg_rtx = tmp_reg;
7758             }
7759           {
7760             rtx insn;
7761
7762             /* Mark as interesting for dwarf cfi generator */
7763             insn = emit_move_insn (mem_rtx, reg_rtx);
7764             RTX_FRAME_RELATED_P (insn) = 1;
7765             /* If we use an intermediate register for the save, we can't
7766                describe this exactly in cfi as a copy of the to-be-saved
7767                register into the temporary register and then the temporary
7768                register on the stack, because the temporary register can
7769                have a different natural size than the to-be-saved register.
7770                Thus, we gloss over the intermediate copy and pretend we do
7771                a direct save from the to-be-saved register.  */
7772             if (REGNO (reg_rtx) != reg)
7773               {
7774                 rtx set;
7775
7776                 set = gen_rtx_SET (VOIDmode, mem_rtx, orig_reg_rtx);
7777                 add_reg_note (insn, REG_FRAME_RELATED_EXPR, set);
7778               }
7779
7780             if (TARGET_SHCOMPACT && (offset_in_r0 != -1))
7781               {
7782                 rtx reg_rtx = gen_rtx_REG (mode, reg);
7783                 rtx set;
7784                 rtx mem_rtx = gen_frame_mem (mode,
7785                                              gen_rtx_PLUS (Pmode,
7786                                                            stack_pointer_rtx,
7787                                                            GEN_INT (offset)));
7788
7789                 set = gen_rtx_SET (VOIDmode, mem_rtx, reg_rtx);
7790                 add_reg_note (insn, REG_FRAME_RELATED_EXPR, set);
7791               }
7792           }
7793         }
7794
7795       gcc_assert (entry->offset == d_rounding);
7796     }
7797   else
7798     {
7799       push_regs (&live_regs_mask, current_function_interrupt);
7800       stack_usage += d;
7801     }
7802
7803   if (flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
7804     emit_insn (gen_GOTaddr2picreg ());
7805
7806   if (SHMEDIA_REGS_STACK_ADJUST ())
7807     {
7808       /* This must NOT go through the PLT, otherwise mach and macl
7809          may be clobbered.  */
7810       function_symbol (gen_rtx_REG (Pmode, R0_REG),
7811                        (TARGET_FPU_ANY
7812                         ? "__GCC_push_shmedia_regs"
7813                         : "__GCC_push_shmedia_regs_nofpu"), SFUNC_GOT);
7814       emit_insn (gen_shmedia_save_restore_regs_compact
7815                  (GEN_INT (-SHMEDIA_REGS_STACK_ADJUST ())));
7816     }
7817
7818   if (target_flags != save_flags && ! current_function_interrupt)
7819     emit_insn (gen_toggle_sz ());
7820
7821   target_flags = save_flags;
7822
7823   output_stack_adjust (-rounded_frame_size (d) + d_rounding,
7824                        stack_pointer_rtx, 0, NULL, true);
7825   stack_usage += rounded_frame_size (d) - d_rounding;
7826
7827   if (frame_pointer_needed)
7828     frame_insn (GEN_MOV (hard_frame_pointer_rtx, stack_pointer_rtx));
7829
7830   if (TARGET_SHCOMPACT
7831       && (crtl->args.info.call_cookie & ~ CALL_COOKIE_RET_TRAMP(1)))
7832     {
7833       /* This must NOT go through the PLT, otherwise mach and macl
7834          may be clobbered.  */
7835       function_symbol (gen_rtx_REG (Pmode, R0_REG),
7836                       "__GCC_shcompact_incoming_args", SFUNC_GOT);
7837       emit_insn (gen_shcompact_incoming_args ());
7838     }
7839
7840   /* If we are profiling, make sure no instructions are scheduled before
7841      the call to mcount.  Similarly if some call instructions are swapped
7842      before frame related insns, it'll confuse the unwinder because
7843      currently SH has no unwind info for function epilogues.  */
7844   if (crtl->profile || flag_exceptions || flag_unwind_tables)
7845     emit_insn (gen_blockage ());
7846
7847   if (flag_stack_usage_info)
7848     current_function_static_stack_size = stack_usage;
7849 }
7850
7851 /* Expand code for the function epilogue.  */
7852 void
7853 sh_expand_epilogue (bool sibcall_p)
7854 {
7855   HARD_REG_SET live_regs_mask;
7856   int d, i;
7857   int d_rounding = 0;
7858
7859   int save_flags = target_flags;
7860   int frame_size, save_size;
7861   int fpscr_deferred = 0;
7862   int e = sibcall_p ? -1 : 1;
7863
7864   d = calc_live_regs (&live_regs_mask);
7865
7866   save_size = d;
7867   frame_size = rounded_frame_size (d);
7868
7869   if (TARGET_SH5)
7870     {
7871       int tregs_space = shmedia_target_regs_stack_adjust (&live_regs_mask);
7872       int total_size;
7873       if (d % (STACK_BOUNDARY / BITS_PER_UNIT))
7874         d_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
7875                       - d % (STACK_BOUNDARY / BITS_PER_UNIT));
7876
7877       total_size = d + tregs_space;
7878       total_size += rounded_frame_size (total_size);
7879       save_size = total_size - frame_size;
7880
7881       /* If adjusting the stack in a single step costs nothing extra, do so.
7882          I.e. either if a single addi is enough, or we need a movi anyway,
7883          and we don't exceed the maximum offset range (the test for the
7884          latter is conservative for simplicity).  */
7885       if (TARGET_SHMEDIA
7886           && ! frame_pointer_needed
7887           && (CONST_OK_FOR_I10 (total_size)
7888               || (! CONST_OK_FOR_I10 (save_size + d_rounding)
7889                   && total_size <= 2044)))
7890         d_rounding = frame_size;
7891
7892       frame_size -= d_rounding;
7893     }
7894
7895   if (frame_pointer_needed)
7896     {
7897       /* We must avoid scheduling the epilogue with previous basic blocks.
7898          See PR/18032 and PR/40313.  */
7899       emit_insn (gen_blockage ());
7900       output_stack_adjust (frame_size, hard_frame_pointer_rtx, e,
7901                            &live_regs_mask, true);
7902
7903       /* We must avoid moving the stack pointer adjustment past code
7904          which reads from the local frame, else an interrupt could
7905          occur after the SP adjustment and clobber data in the local
7906          frame.  */
7907       emit_insn (gen_blockage ());
7908       frame_insn (GEN_MOV (stack_pointer_rtx, hard_frame_pointer_rtx));
7909     }
7910   else if (frame_size)
7911     {
7912       /* We must avoid moving the stack pointer adjustment past code
7913          which reads from the local frame, else an interrupt could
7914          occur after the SP adjustment and clobber data in the local
7915          frame.  */
7916       emit_insn (gen_blockage ());
7917       output_stack_adjust (frame_size, stack_pointer_rtx, e,
7918                            &live_regs_mask, true);
7919     }
7920
7921   if (SHMEDIA_REGS_STACK_ADJUST ())
7922     {
7923       function_symbol (gen_rtx_REG (Pmode, R0_REG),
7924                        (TARGET_FPU_ANY
7925                         ? "__GCC_pop_shmedia_regs"
7926                         : "__GCC_pop_shmedia_regs_nofpu"), SFUNC_GOT);
7927       /* This must NOT go through the PLT, otherwise mach and macl
7928          may be clobbered.  */
7929       emit_insn (gen_shmedia_save_restore_regs_compact
7930                  (GEN_INT (SHMEDIA_REGS_STACK_ADJUST ())));
7931     }
7932
7933   /* Pop all the registers.  */
7934
7935   if (target_flags != save_flags && ! current_function_interrupt)
7936     emit_insn (gen_toggle_sz ());
7937   if (TARGET_SH5)
7938     {
7939       int offset_base, offset;
7940       int offset_in_r0 = -1;
7941       int sp_in_r0 = 0;
7942       rtx r0 = gen_rtx_REG (Pmode, R0_REG);
7943       save_schedule schedule;
7944       save_entry *entry;
7945       int *tmp_pnt;
7946
7947       entry = sh5_schedule_saves (&live_regs_mask, &schedule, d_rounding);
7948       offset_base = -entry[1].offset + d_rounding;
7949       tmp_pnt = schedule.temps;
7950       for (; entry->mode != VOIDmode; entry--)
7951         {
7952           enum machine_mode mode = (enum machine_mode) entry->mode;
7953           int reg = entry->reg;
7954           rtx reg_rtx, mem_rtx, post_inc = NULL_RTX;
7955
7956           offset = offset_base + entry->offset;
7957           reg_rtx = gen_rtx_REG (mode, reg);
7958
7959           mem_rtx = gen_frame_mem (mode,
7960                                    gen_rtx_PLUS (Pmode,
7961                                                  stack_pointer_rtx,
7962                                                  GEN_INT (offset)));
7963
7964           if (!memory_address_p (mode, XEXP (mem_rtx, 0)))
7965             mem_rtx = NULL_RTX;
7966
7967           if (HAVE_POST_INCREMENT
7968               && (offset == offset_in_r0
7969                   || (offset + GET_MODE_SIZE (mode) != d + d_rounding
7970                       && mem_rtx == NULL_RTX)
7971                   || reg == PR_REG || SPECIAL_REGISTER_P (reg)))
7972             {
7973               post_inc = gen_frame_mem (mode, gen_rtx_POST_INC (Pmode, r0));
7974
7975               if (!memory_address_p (mode, XEXP (post_inc, 0)))
7976                 post_inc = NULL_RTX;
7977               else
7978                 mem_rtx = NULL_RTX;
7979             }
7980
7981           if (mem_rtx != NULL_RTX)
7982             goto addr_ok;
7983
7984           if (offset_in_r0 == -1)
7985             {
7986               emit_move_insn (r0, GEN_INT (offset));
7987               offset_in_r0 = offset;
7988             }
7989           else if (offset != offset_in_r0)
7990             {
7991               emit_move_insn (r0,
7992                               gen_rtx_PLUS
7993                               (Pmode, r0,
7994                                GEN_INT (offset - offset_in_r0)));
7995               offset_in_r0 += offset - offset_in_r0;
7996             }
7997
7998           if (post_inc != NULL_RTX)
7999             {
8000               if (! sp_in_r0)
8001                 {
8002                   emit_move_insn (r0,
8003                                   gen_rtx_PLUS
8004                                   (Pmode, r0, stack_pointer_rtx));
8005                   sp_in_r0 = 1;
8006                 }
8007
8008               mem_rtx = post_inc;
8009
8010               offset_in_r0 += GET_MODE_SIZE (mode);
8011             }
8012           else if (sp_in_r0)
8013             mem_rtx = gen_frame_mem (mode, r0);
8014           else
8015             mem_rtx = gen_frame_mem (mode,
8016                                      gen_rtx_PLUS (Pmode,
8017                                                    stack_pointer_rtx,
8018                                                    r0));
8019
8020           gcc_assert ((reg != PR_REG && !SPECIAL_REGISTER_P (reg))
8021                       || mem_rtx == post_inc);
8022
8023         addr_ok:
8024           if ((reg == PR_REG || SPECIAL_REGISTER_P (reg))
8025               && mem_rtx != post_inc)
8026             {
8027               emit_move_insn (r0, mem_rtx);
8028               mem_rtx = r0;
8029             }
8030           else if (TARGET_REGISTER_P (reg))
8031             {
8032               rtx tmp_reg = gen_rtx_REG (mode, *tmp_pnt);
8033
8034               /* Give the scheduler a bit of freedom by using up to
8035                  MAX_TEMPS registers in a round-robin fashion.  */
8036               emit_move_insn (tmp_reg, mem_rtx);
8037               mem_rtx = tmp_reg;
8038               if (*++tmp_pnt < 0)
8039                 tmp_pnt = schedule.temps;
8040             }
8041
8042           emit_move_insn (reg_rtx, mem_rtx);
8043         }
8044
8045       gcc_assert (entry->offset + offset_base == d + d_rounding);
8046     }
8047   else /* ! TARGET_SH5 */
8048     {
8049       int last_reg;
8050
8051       save_size = 0;
8052         /* For an ISR with RESBANK attribute assigned, don't pop PR
8053            register.  */
8054       if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG)
8055           && !sh_cfun_resbank_handler_p ())     
8056         {
8057           if (!frame_pointer_needed)
8058             emit_insn (gen_blockage ());
8059           pop (PR_REG);
8060         }
8061
8062       /* Banked registers are popped first to avoid being scheduled in the
8063          delay slot. RTE switches banks before the ds instruction.  */
8064       if (current_function_interrupt)
8065         {
8066           bool use_movml = false;
8067
8068           if (TARGET_SH2A)
8069             {
8070               unsigned int count = 0;
8071
8072               for (i = FIRST_BANKED_REG; i <= LAST_BANKED_REG; i++)
8073                 if (TEST_HARD_REG_BIT (live_regs_mask, i))
8074                   count++;
8075                 else
8076                   break;
8077
8078               /* Use movml when all banked register are poped.  */
8079               if (count == LAST_BANKED_REG - FIRST_BANKED_REG + 1)
8080                 use_movml = true;
8081             }
8082
8083           if (sh_cfun_resbank_handler_p ())
8084             ; /* Do nothing.  */
8085           else if (use_movml)
8086             {
8087               rtx sp_reg = gen_rtx_REG (SImode, STACK_POINTER_REGNUM);
8088
8089               /* We must avoid scheduling multiple load insn with another
8090                  insns.  */
8091               emit_insn (gen_blockage ());
8092               emit_insn (gen_movml_pop_banked (sp_reg));
8093               emit_insn (gen_blockage ());
8094             }
8095           else
8096             for (i = LAST_BANKED_REG; i >= FIRST_BANKED_REG; i--)
8097               if (TEST_HARD_REG_BIT (live_regs_mask, i))
8098                 pop (i);
8099
8100           last_reg = FIRST_PSEUDO_REGISTER - LAST_BANKED_REG - 1;
8101         }
8102       else
8103         last_reg = FIRST_PSEUDO_REGISTER;
8104
8105       for (i = 0; i < last_reg; i++)
8106         {
8107           int j = (FIRST_PSEUDO_REGISTER - 1) - i;
8108
8109           if (j == FPSCR_REG && current_function_interrupt && TARGET_FMOVD
8110               && hard_reg_set_intersect_p (live_regs_mask,
8111                                           reg_class_contents[DF_REGS]))
8112             fpscr_deferred = 1;
8113           /* For an ISR with RESBANK attribute assigned, don't pop
8114              following registers, R0-R14, MACH, MACL and GBR.  */
8115           else if (j != PR_REG && TEST_HARD_REG_BIT (live_regs_mask, j) 
8116                    && ! (sh_cfun_resbank_handler_p ()
8117                          && ((j >= FIRST_GENERAL_REG
8118                               && j < LAST_GENERAL_REG)
8119                               || j == MACH_REG
8120                               || j == MACL_REG
8121                               || j == GBR_REG)))
8122             pop (j);
8123
8124           if (j == FIRST_FP_REG && fpscr_deferred)
8125             pop (FPSCR_REG);
8126         }
8127     }
8128   if (target_flags != save_flags && ! current_function_interrupt)
8129     emit_insn (gen_toggle_sz ());
8130   target_flags = save_flags;
8131
8132   output_stack_adjust (crtl->args.pretend_args_size
8133                        + save_size + d_rounding
8134                        + crtl->args.info.stack_regs * 8,
8135                        stack_pointer_rtx, e, NULL, true);
8136
8137   if (crtl->calls_eh_return)
8138     emit_insn (GEN_ADD3 (stack_pointer_rtx, stack_pointer_rtx,
8139                          EH_RETURN_STACKADJ_RTX));
8140
8141   /* Switch back to the normal stack if necessary.  */
8142   if (lookup_attribute ("sp_switch", DECL_ATTRIBUTES (current_function_decl)))
8143     emit_insn (gen_sp_switch_2 ());
8144
8145   /* Tell flow the insn that pops PR isn't dead.  */
8146   /* PR_REG will never be live in SHmedia mode, and we don't need to
8147      USE PR_MEDIA_REG, since it will be explicitly copied to TR0_REG
8148      by the return pattern.  */
8149   if (TEST_HARD_REG_BIT (live_regs_mask, PR_REG))
8150     emit_use (gen_rtx_REG (SImode, PR_REG));
8151 }
8152
8153 /* Emit code to change the current function's return address to RA.
8154    TEMP is available as a scratch register, if needed.  */
8155 void
8156 sh_set_return_address (rtx ra, rtx tmp)
8157 {
8158   HARD_REG_SET live_regs_mask;
8159   int d;
8160   int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
8161   int pr_offset;
8162
8163   d = calc_live_regs (&live_regs_mask);
8164
8165   /* If pr_reg isn't life, we can set it (or the register given in
8166      sh_media_register_for_return) directly.  */
8167   if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
8168     {
8169       rtx rr;
8170
8171       if (TARGET_SHMEDIA)
8172         {
8173           int rr_regno = sh_media_register_for_return ();
8174
8175           if (rr_regno < 0)
8176             rr_regno = pr_reg;
8177
8178           rr = gen_rtx_REG (DImode, rr_regno);
8179         }
8180       else
8181         rr = gen_rtx_REG (SImode, pr_reg);
8182
8183       emit_insn (GEN_MOV (rr, ra));
8184       /* Tell flow the register for return isn't dead.  */
8185       emit_use (rr);
8186       return;
8187     }
8188
8189   if (TARGET_SH5)
8190     {
8191       int offset;
8192       save_schedule schedule;
8193       save_entry *entry;
8194
8195       entry = sh5_schedule_saves (&live_regs_mask, &schedule, 0);
8196       offset = entry[1].offset;
8197       for (; entry->mode != VOIDmode; entry--)
8198         if (entry->reg == pr_reg)
8199           goto found;
8200
8201       /* We can't find pr register.  */
8202       gcc_unreachable ();
8203
8204     found:
8205       offset = entry->offset - offset;
8206       pr_offset = (rounded_frame_size (d) + offset
8207                    + SHMEDIA_REGS_STACK_ADJUST ());
8208     }
8209   else
8210     pr_offset = rounded_frame_size (d);
8211
8212   emit_insn (GEN_MOV (tmp, GEN_INT (pr_offset)));
8213
8214   if (frame_pointer_needed)
8215     emit_insn (GEN_ADD3 (tmp, tmp, hard_frame_pointer_rtx));
8216   else
8217     emit_insn (GEN_ADD3 (tmp, tmp, stack_pointer_rtx));
8218
8219   tmp = gen_frame_mem (Pmode, tmp);
8220   emit_insn (GEN_MOV (tmp, ra));
8221   /* Tell this store isn't dead.  */
8222   emit_use (tmp);
8223 }
8224
8225 /* Clear variables at function end.  */
8226 static void
8227 sh_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
8228                              HOST_WIDE_INT size ATTRIBUTE_UNUSED)
8229 {
8230 }
8231
8232 static rtx
8233 sh_builtin_saveregs (void)
8234 {
8235   /* First unnamed integer register.  */
8236   int first_intreg = crtl->args.info.arg_count[(int) SH_ARG_INT];
8237   /* Number of integer registers we need to save.  */
8238   int n_intregs = MAX (0, NPARM_REGS (SImode) - first_intreg);
8239   /* First unnamed SFmode float reg */
8240   int first_floatreg = crtl->args.info.arg_count[(int) SH_ARG_FLOAT];
8241   /* Number of SFmode float regs to save.  */
8242   int n_floatregs = MAX (0, NPARM_REGS (SFmode) - first_floatreg);
8243   rtx regbuf, fpregs;
8244   int bufsize, regno;
8245   alias_set_type alias_set;
8246
8247   if (TARGET_SH5)
8248     {
8249       if (n_intregs)
8250         {
8251           int pushregs = n_intregs;
8252
8253           while (pushregs < NPARM_REGS (SImode) - 1
8254                  && (CALL_COOKIE_INT_REG_GET
8255                         (crtl->args.info.call_cookie,
8256                          NPARM_REGS (SImode) - pushregs)
8257                      == 1))
8258             {
8259               crtl->args.info.call_cookie
8260                 &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
8261                                           - pushregs, 1);
8262               pushregs++;
8263             }
8264
8265           if (pushregs == NPARM_REGS (SImode))
8266             crtl->args.info.call_cookie
8267               |= (CALL_COOKIE_INT_REG (0, 1)
8268                   | CALL_COOKIE_STACKSEQ (pushregs - 1));
8269           else
8270             crtl->args.info.call_cookie
8271               |= CALL_COOKIE_STACKSEQ (pushregs);
8272
8273           crtl->args.pretend_args_size += 8 * n_intregs;
8274         }
8275       if (TARGET_SHCOMPACT)
8276         return const0_rtx;
8277     }
8278
8279   if (! TARGET_SH2E && ! TARGET_SH4 && ! TARGET_SH5)
8280     {
8281       error ("__builtin_saveregs not supported by this subtarget");
8282       return const0_rtx;
8283     }
8284
8285   if (TARGET_SHMEDIA)
8286     n_floatregs = 0;
8287
8288   /* Allocate block of memory for the regs.  */
8289   /* ??? If n_intregs + n_floatregs == 0, should we allocate at least 1 byte?
8290      Or can assign_stack_local accept a 0 SIZE argument?  */
8291   bufsize = (n_intregs * UNITS_PER_WORD) + (n_floatregs * UNITS_PER_WORD);
8292
8293   if (TARGET_SHMEDIA)
8294     regbuf = gen_frame_mem (BLKmode, gen_rtx_REG (Pmode, ARG_POINTER_REGNUM));
8295   else if (n_floatregs & 1)
8296     {
8297       rtx addr;
8298
8299       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
8300       addr = copy_to_mode_reg (Pmode, XEXP (regbuf, 0));
8301       emit_insn (gen_iorsi3 (addr, addr, GEN_INT (UNITS_PER_WORD)));
8302       regbuf = change_address (regbuf, BLKmode, addr);
8303     }
8304   else if (STACK_BOUNDARY < 64 && TARGET_FPU_DOUBLE && n_floatregs)
8305     {
8306       rtx addr, mask;
8307
8308       regbuf = assign_stack_local (BLKmode, bufsize + UNITS_PER_WORD, 0);
8309       addr = copy_to_mode_reg (Pmode, plus_constant (Pmode,
8310                                                      XEXP (regbuf, 0), 4));
8311       mask = copy_to_mode_reg (Pmode, GEN_INT (-8));
8312       emit_insn (gen_andsi3 (addr, addr, mask));
8313       regbuf = change_address (regbuf, BLKmode, addr);
8314     }
8315   else
8316     regbuf = assign_stack_local (BLKmode, bufsize, TARGET_FPU_DOUBLE ? 64 : 0);
8317   alias_set = get_varargs_alias_set ();
8318   set_mem_alias_set (regbuf, alias_set);
8319
8320   /* Save int args.
8321      This is optimized to only save the regs that are necessary.  Explicitly
8322      named args need not be saved.  */
8323   if (n_intregs > 0)
8324     move_block_from_reg (BASE_ARG_REG (SImode) + first_intreg,
8325                          adjust_address (regbuf, BLKmode,
8326                                          n_floatregs * UNITS_PER_WORD),
8327                          n_intregs);
8328
8329   if (TARGET_SHMEDIA)
8330     /* Return the address of the regbuf.  */
8331     return XEXP (regbuf, 0);
8332
8333   /* Save float args.
8334      This is optimized to only save the regs that are necessary.  Explicitly
8335      named args need not be saved.
8336      We explicitly build a pointer to the buffer because it halves the insn
8337      count when not optimizing (otherwise the pointer is built for each reg
8338      saved).
8339      We emit the moves in reverse order so that we can use predecrement.  */
8340
8341   fpregs = copy_to_mode_reg (Pmode,
8342                              plus_constant (Pmode, XEXP (regbuf, 0),
8343                                             n_floatregs * UNITS_PER_WORD));
8344   if (TARGET_SH4 || TARGET_SH2A_DOUBLE)
8345     {
8346       rtx mem;
8347       for (regno = NPARM_REGS (DFmode) - 2; regno >= first_floatreg; regno -= 2)
8348         {
8349           emit_insn (gen_addsi3 (fpregs, fpregs,
8350                                  GEN_INT (-2 * UNITS_PER_WORD)));
8351           mem = change_address (regbuf, DFmode, fpregs);
8352           emit_move_insn (mem,
8353                           gen_rtx_REG (DFmode, BASE_ARG_REG (DFmode) + regno));
8354         }
8355       regno = first_floatreg;
8356       if (regno & 1)
8357         {
8358           emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (-UNITS_PER_WORD)));
8359           mem = change_address (regbuf, SFmode, fpregs);
8360           emit_move_insn (mem,
8361                           gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno
8362                                                 - (TARGET_LITTLE_ENDIAN != 0)));
8363         }
8364     }
8365   else
8366     for (regno = NPARM_REGS (SFmode) - 1; regno >= first_floatreg; regno--)
8367       {
8368         rtx mem;
8369
8370         emit_insn (gen_addsi3 (fpregs, fpregs, GEN_INT (-UNITS_PER_WORD)));
8371         mem = change_address (regbuf, SFmode, fpregs);
8372         emit_move_insn (mem,
8373                         gen_rtx_REG (SFmode, BASE_ARG_REG (SFmode) + regno));
8374       }
8375
8376   /* Return the address of the regbuf.  */
8377   return XEXP (regbuf, 0);
8378 }
8379
8380 /* Define the `__builtin_va_list' type for the ABI.  */
8381 static tree
8382 sh_build_builtin_va_list (void)
8383 {
8384   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
8385   tree record, type_decl;
8386
8387   if (TARGET_SH5 || (! TARGET_SH2E && ! TARGET_SH4)
8388       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
8389     return ptr_type_node;
8390
8391   record = (*lang_hooks.types.make_type) (RECORD_TYPE);
8392   type_decl = build_decl (BUILTINS_LOCATION,
8393                           TYPE_DECL, get_identifier ("__va_list_tag"), record);
8394
8395   f_next_o = build_decl (BUILTINS_LOCATION,
8396                          FIELD_DECL, get_identifier ("__va_next_o"),
8397                          ptr_type_node);
8398   f_next_o_limit = build_decl (BUILTINS_LOCATION,
8399                                FIELD_DECL,
8400                                get_identifier ("__va_next_o_limit"),
8401                                ptr_type_node);
8402   f_next_fp = build_decl (BUILTINS_LOCATION,
8403                           FIELD_DECL, get_identifier ("__va_next_fp"),
8404                           ptr_type_node);
8405   f_next_fp_limit = build_decl (BUILTINS_LOCATION,
8406                                 FIELD_DECL,
8407                                 get_identifier ("__va_next_fp_limit"),
8408                                 ptr_type_node);
8409   f_next_stack = build_decl (BUILTINS_LOCATION,
8410                              FIELD_DECL, get_identifier ("__va_next_stack"),
8411                              ptr_type_node);
8412
8413   DECL_FIELD_CONTEXT (f_next_o) = record;
8414   DECL_FIELD_CONTEXT (f_next_o_limit) = record;
8415   DECL_FIELD_CONTEXT (f_next_fp) = record;
8416   DECL_FIELD_CONTEXT (f_next_fp_limit) = record;
8417   DECL_FIELD_CONTEXT (f_next_stack) = record;
8418
8419   TYPE_STUB_DECL (record) = type_decl;
8420   TYPE_NAME (record) = type_decl;
8421   TYPE_FIELDS (record) = f_next_o;
8422   DECL_CHAIN (f_next_o) = f_next_o_limit;
8423   DECL_CHAIN (f_next_o_limit) = f_next_fp;
8424   DECL_CHAIN (f_next_fp) = f_next_fp_limit;
8425   DECL_CHAIN (f_next_fp_limit) = f_next_stack;
8426
8427   layout_type (record);
8428
8429   return record;
8430 }
8431
8432 /* Implement `va_start' for varargs and stdarg.  */
8433 static void
8434 sh_va_start (tree valist, rtx nextarg)
8435 {
8436   tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
8437   tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
8438   tree t, u;
8439   int nfp, nint;
8440
8441   if (TARGET_SH5)
8442     {
8443       expand_builtin_saveregs ();
8444       std_expand_builtin_va_start (valist, nextarg);
8445       return;
8446     }
8447
8448   if ((! TARGET_SH2E && ! TARGET_SH4)
8449       || TARGET_HITACHI || sh_cfun_attr_renesas_p ())
8450     {
8451       std_expand_builtin_va_start (valist, nextarg);
8452       return;
8453     }
8454
8455   f_next_o = TYPE_FIELDS (va_list_type_node);
8456   f_next_o_limit = DECL_CHAIN (f_next_o);
8457   f_next_fp = DECL_CHAIN (f_next_o_limit);
8458   f_next_fp_limit = DECL_CHAIN (f_next_fp);
8459   f_next_stack = DECL_CHAIN (f_next_fp_limit);
8460
8461   next_o = build3 (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o,
8462                    NULL_TREE);
8463   next_o_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
8464                          valist, f_next_o_limit, NULL_TREE);
8465   next_fp = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp), valist, f_next_fp,
8466                     NULL_TREE);
8467   next_fp_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
8468                           valist, f_next_fp_limit, NULL_TREE);
8469   next_stack = build3 (COMPONENT_REF, TREE_TYPE (f_next_stack),
8470                        valist, f_next_stack, NULL_TREE);
8471
8472   /* Call __builtin_saveregs.  */
8473   u = make_tree (sizetype, expand_builtin_saveregs ());
8474   u = fold_convert (ptr_type_node, u);
8475   t = build2 (MODIFY_EXPR, ptr_type_node, next_fp, u);
8476   TREE_SIDE_EFFECTS (t) = 1;
8477   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
8478
8479   nfp = crtl->args.info.arg_count[SH_ARG_FLOAT];
8480   if (nfp < 8)
8481     nfp = 8 - nfp;
8482   else
8483     nfp = 0;
8484   u = fold_build_pointer_plus_hwi (u, UNITS_PER_WORD * nfp);
8485   t = build2 (MODIFY_EXPR, ptr_type_node, next_fp_limit, u);
8486   TREE_SIDE_EFFECTS (t) = 1;
8487   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
8488
8489   t = build2 (MODIFY_EXPR, ptr_type_node, next_o, u);
8490   TREE_SIDE_EFFECTS (t) = 1;
8491   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
8492
8493   nint = crtl->args.info.arg_count[SH_ARG_INT];
8494   if (nint < 4)
8495     nint = 4 - nint;
8496   else
8497     nint = 0;
8498   u = fold_build_pointer_plus_hwi (u, UNITS_PER_WORD * nint);
8499   t = build2 (MODIFY_EXPR, ptr_type_node, next_o_limit, u);
8500   TREE_SIDE_EFFECTS (t) = 1;
8501   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
8502
8503   u = make_tree (ptr_type_node, nextarg);
8504   t = build2 (MODIFY_EXPR, ptr_type_node, next_stack, u);
8505   TREE_SIDE_EFFECTS (t) = 1;
8506   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
8507 }
8508
8509 /* TYPE is a RECORD_TYPE.  If there is only a single nonzero-sized
8510    member, return it.  */
8511 static tree
8512 find_sole_member (tree type)
8513 {
8514   tree field, member = NULL_TREE;
8515
8516   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8517     {
8518       if (TREE_CODE (field) != FIELD_DECL)
8519         continue;
8520       if (!DECL_SIZE (field))
8521         return NULL_TREE;
8522       if (integer_zerop (DECL_SIZE (field)))
8523         continue;
8524       if (member)
8525         return NULL_TREE;
8526       member = field;
8527     }
8528   return member;
8529 }
8530
8531 /* Implement `va_arg'.  */
8532 static tree
8533 sh_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
8534                          gimple_seq *post_p ATTRIBUTE_UNUSED)
8535 {
8536   HOST_WIDE_INT size, rsize;
8537   tree tmp, pptr_type_node;
8538   tree addr, lab_over = NULL, result = NULL;
8539   bool pass_by_ref;
8540   tree eff_type;
8541
8542   if (!VOID_TYPE_P (type))
8543     pass_by_ref = targetm.calls.must_pass_in_stack (TYPE_MODE (type), type);
8544   else
8545     pass_by_ref = false;
8546
8547   if (pass_by_ref)
8548     type = build_pointer_type (type);
8549
8550   size = int_size_in_bytes (type);
8551   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
8552   pptr_type_node = build_pointer_type (ptr_type_node);
8553
8554   if (! TARGET_SH5 && (TARGET_SH2E || TARGET_SH4)
8555       && ! (TARGET_HITACHI || sh_cfun_attr_renesas_p ()))
8556     {
8557       tree f_next_o, f_next_o_limit, f_next_fp, f_next_fp_limit, f_next_stack;
8558       tree next_o, next_o_limit, next_fp, next_fp_limit, next_stack;
8559       int pass_as_float;
8560       tree lab_false;
8561       tree member;
8562
8563       f_next_o = TYPE_FIELDS (va_list_type_node);
8564       f_next_o_limit = DECL_CHAIN (f_next_o);
8565       f_next_fp = DECL_CHAIN (f_next_o_limit);
8566       f_next_fp_limit = DECL_CHAIN (f_next_fp);
8567       f_next_stack = DECL_CHAIN (f_next_fp_limit);
8568
8569       next_o = build3 (COMPONENT_REF, TREE_TYPE (f_next_o), valist, f_next_o,
8570                        NULL_TREE);
8571       next_o_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_o_limit),
8572                              valist, f_next_o_limit, NULL_TREE);
8573       next_fp = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp),
8574                         valist, f_next_fp, NULL_TREE);
8575       next_fp_limit = build3 (COMPONENT_REF, TREE_TYPE (f_next_fp_limit),
8576                               valist, f_next_fp_limit, NULL_TREE);
8577       next_stack = build3 (COMPONENT_REF, TREE_TYPE (f_next_stack),
8578                            valist, f_next_stack, NULL_TREE);
8579
8580       /* Structures with a single member with a distinct mode are passed
8581          like their member.  This is relevant if the latter has a REAL_TYPE
8582          or COMPLEX_TYPE type.  */
8583       eff_type = type;
8584       while (TREE_CODE (eff_type) == RECORD_TYPE
8585              && (member = find_sole_member (eff_type))
8586              && (TREE_CODE (TREE_TYPE (member)) == REAL_TYPE
8587                  || TREE_CODE (TREE_TYPE (member)) == COMPLEX_TYPE
8588                  || TREE_CODE (TREE_TYPE (member)) == RECORD_TYPE))
8589         {
8590           tree field_type = TREE_TYPE (member);
8591
8592           if (TYPE_MODE (eff_type) == TYPE_MODE (field_type))
8593             eff_type = field_type;
8594           else
8595             {
8596               gcc_assert ((TYPE_ALIGN (eff_type)
8597                            < GET_MODE_ALIGNMENT (TYPE_MODE (field_type)))
8598                           || (TYPE_ALIGN (eff_type)
8599                               > GET_MODE_BITSIZE (TYPE_MODE (field_type))));
8600               break;
8601             }
8602         }
8603
8604       if (TARGET_SH4 || TARGET_SH2A_DOUBLE)
8605         {
8606           pass_as_float = ((TREE_CODE (eff_type) == REAL_TYPE && size <= 8)
8607                            || (TREE_CODE (eff_type) == COMPLEX_TYPE
8608                                && TREE_CODE (TREE_TYPE (eff_type)) == REAL_TYPE
8609                                && size <= 16));
8610         }
8611       else
8612         {
8613           pass_as_float = (TREE_CODE (eff_type) == REAL_TYPE && size == 4);
8614         }
8615
8616       addr = create_tmp_var (pptr_type_node, NULL);
8617       lab_false = create_artificial_label (UNKNOWN_LOCATION);
8618       lab_over = create_artificial_label (UNKNOWN_LOCATION);
8619
8620       valist = build_simple_mem_ref (addr);
8621
8622       if (pass_as_float)
8623         {
8624           tree next_fp_tmp = create_tmp_var (TREE_TYPE (f_next_fp), NULL);
8625           tree cmp;
8626           bool is_double = size == 8 && TREE_CODE (eff_type) == REAL_TYPE;
8627
8628           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_fp));
8629           gimplify_assign (unshare_expr (addr), tmp, pre_p);
8630
8631           gimplify_assign (unshare_expr (next_fp_tmp), valist, pre_p);
8632           tmp = next_fp_limit;
8633           if (size > 4 && !is_double)
8634             tmp = fold_build_pointer_plus_hwi (unshare_expr (tmp), 4 - size);
8635           tmp = build2 (GE_EXPR, boolean_type_node,
8636                         unshare_expr (next_fp_tmp), unshare_expr (tmp));
8637           cmp = build3 (COND_EXPR, void_type_node, tmp,
8638                         build1 (GOTO_EXPR, void_type_node,
8639                                 unshare_expr (lab_false)), NULL_TREE);
8640           if (!is_double)
8641             gimplify_and_add (cmp, pre_p);
8642
8643           if (TYPE_ALIGN (eff_type) > BITS_PER_WORD
8644               || (is_double || size == 16))
8645             {
8646               tmp = fold_convert (sizetype, next_fp_tmp);
8647               tmp = build2 (BIT_AND_EXPR, sizetype, tmp,
8648                             size_int (UNITS_PER_WORD));
8649               tmp = fold_build_pointer_plus (unshare_expr (next_fp_tmp), tmp);
8650               gimplify_assign (unshare_expr (next_fp_tmp), tmp, pre_p);
8651             }
8652           if (is_double)
8653             gimplify_and_add (cmp, pre_p);
8654
8655 #ifdef FUNCTION_ARG_SCmode_WART
8656           if (TYPE_MODE (eff_type) == SCmode
8657               && TARGET_SH4 && TARGET_LITTLE_ENDIAN)
8658             {
8659               tree subtype = TREE_TYPE (eff_type);
8660               tree real, imag;
8661
8662               imag
8663                 = std_gimplify_va_arg_expr (next_fp_tmp, subtype, pre_p, NULL);
8664               imag = get_initialized_tmp_var (imag, pre_p, NULL);
8665
8666               real
8667                 = std_gimplify_va_arg_expr (next_fp_tmp, subtype, pre_p, NULL);
8668               real = get_initialized_tmp_var (real, pre_p, NULL);
8669
8670               result = build2 (COMPLEX_EXPR, eff_type, real, imag);
8671               if (type != eff_type)
8672                 result = build1 (VIEW_CONVERT_EXPR, type, result);
8673               result = get_initialized_tmp_var (result, pre_p, NULL);
8674             }
8675 #endif /* FUNCTION_ARG_SCmode_WART */
8676
8677           tmp = build1 (GOTO_EXPR, void_type_node, unshare_expr (lab_over));
8678           gimplify_and_add (tmp, pre_p);
8679
8680           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_false));
8681           gimplify_and_add (tmp, pre_p);
8682
8683           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_stack));
8684           gimplify_assign (unshare_expr (addr), tmp, pre_p);
8685           gimplify_assign (unshare_expr (next_fp_tmp),
8686                            unshare_expr (valist), pre_p);
8687
8688           gimplify_assign (unshare_expr (valist),
8689                            unshare_expr (next_fp_tmp), post_p);
8690           valist = next_fp_tmp;
8691         }
8692       else
8693         {
8694           tmp = fold_build_pointer_plus_hwi (unshare_expr (next_o), rsize);
8695           tmp = build2 (GT_EXPR, boolean_type_node, tmp,
8696                         unshare_expr (next_o_limit));
8697           tmp = build3 (COND_EXPR, void_type_node, tmp,
8698                         build1 (GOTO_EXPR, void_type_node,
8699                                 unshare_expr (lab_false)),
8700                         NULL_TREE);
8701           gimplify_and_add (tmp, pre_p);
8702
8703           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_o));
8704           gimplify_assign (unshare_expr (addr), tmp, pre_p);
8705
8706           tmp = build1 (GOTO_EXPR, void_type_node, unshare_expr (lab_over));
8707           gimplify_and_add (tmp, pre_p);
8708
8709           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_false));
8710           gimplify_and_add (tmp, pre_p);
8711
8712           if (size > 4 && ! (TARGET_SH4 || TARGET_SH2A))
8713             gimplify_assign (unshare_expr (next_o),
8714                              unshare_expr (next_o_limit), pre_p);
8715
8716           tmp = build1 (ADDR_EXPR, pptr_type_node, unshare_expr (next_stack));
8717           gimplify_assign (unshare_expr (addr), tmp, pre_p);
8718         }
8719
8720       if (!result)
8721         {
8722           tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_over));
8723           gimplify_and_add (tmp, pre_p);
8724         }
8725     }
8726
8727   /* ??? In va-sh.h, there had been code to make values larger than
8728      size 8 indirect.  This does not match the FUNCTION_ARG macros.  */
8729
8730   tmp = std_gimplify_va_arg_expr (valist, type, pre_p, NULL);
8731   if (result)
8732     {
8733       gimplify_assign (result, tmp, pre_p);
8734       result = build1 (NOP_EXPR, TREE_TYPE (result), result);
8735       tmp = build1 (LABEL_EXPR, void_type_node, unshare_expr (lab_over));
8736       gimplify_and_add (tmp, pre_p);
8737     }
8738   else
8739     result = tmp;
8740
8741   if (pass_by_ref)
8742     result = build_va_arg_indirect_ref (result);
8743
8744   return result;
8745 }
8746
8747 /* 64 bit floating points memory transfers are paired single precision loads
8748    or store.  So DWARF information needs fixing in little endian (unless
8749    PR=SZ=1 in FPSCR).  */
8750 rtx
8751 sh_dwarf_register_span (rtx reg)
8752 {
8753   unsigned regno = REGNO (reg);
8754
8755   if (WORDS_BIG_ENDIAN || GET_MODE (reg) != DFmode)
8756     return NULL_RTX;
8757
8758   return
8759     gen_rtx_PARALLEL (VOIDmode,
8760                       gen_rtvec (2,
8761                                  gen_rtx_REG (SFmode, regno + 1),
8762                                  gen_rtx_REG (SFmode, regno)));
8763 }
8764
8765 static enum machine_mode
8766 sh_promote_function_mode (const_tree type, enum machine_mode mode,
8767                           int *punsignedp, const_tree funtype,
8768                           int for_return)
8769 {
8770   if (sh_promote_prototypes (funtype))
8771     return promote_mode (type, mode, punsignedp);
8772   else
8773     return default_promote_function_mode (type, mode, punsignedp, funtype,
8774                                           for_return);
8775 }
8776
8777 static bool
8778 sh_promote_prototypes (const_tree type)
8779 {
8780   if (TARGET_HITACHI)
8781     return false;
8782   if (! type)
8783     return true;
8784   return ! sh_attr_renesas_p (type);
8785 }
8786
8787 /* Whether an argument must be passed by reference.  On SHcompact, we
8788    pretend arguments wider than 32-bits that would have been passed in
8789    registers are passed by reference, so that an SHmedia trampoline
8790    loads them into the full 64-bits registers.  */
8791 static int
8792 shcompact_byref (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
8793                  const_tree type, bool named)
8794 {
8795   unsigned HOST_WIDE_INT size;
8796
8797   if (type)
8798     size = int_size_in_bytes (type);
8799   else
8800     size = GET_MODE_SIZE (mode);
8801
8802   if (cum->arg_count[SH_ARG_INT] < NPARM_REGS (SImode)
8803       && (!named
8804           || GET_SH_ARG_CLASS (mode) == SH_ARG_INT
8805           || (GET_SH_ARG_CLASS (mode) == SH_ARG_FLOAT
8806               && cum->arg_count[SH_ARG_FLOAT] >= NPARM_REGS (SFmode)))
8807       && size > 4
8808       && !SHCOMPACT_FORCE_ON_STACK (mode, type)
8809       && !SH5_WOULD_BE_PARTIAL_NREGS (*cum, mode, type, named))
8810     return size;
8811   else
8812     return 0;
8813 }
8814
8815 static bool
8816 sh_pass_by_reference (cumulative_args_t cum_v, enum machine_mode mode,
8817                       const_tree type, bool named)
8818 {
8819   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
8820
8821   if (targetm.calls.must_pass_in_stack (mode, type))
8822     return true;
8823
8824   /* ??? std_gimplify_va_arg_expr passes NULL for cum.  That function
8825      wants to know about pass-by-reference semantics for incoming
8826      arguments.  */
8827   if (! cum)
8828     return false;
8829
8830   if (TARGET_SHCOMPACT)
8831     {
8832       cum->byref = shcompact_byref (cum, mode, type, named);
8833       return cum->byref != 0;
8834     }
8835
8836   return false;
8837 }
8838
8839 static bool
8840 sh_callee_copies (cumulative_args_t cum, enum machine_mode mode,
8841                   const_tree type, bool named ATTRIBUTE_UNUSED)
8842 {
8843   /* ??? How can it possibly be correct to return true only on the
8844      caller side of the equation?  Is there someplace else in the
8845      sh backend that's magically producing the copies?  */
8846   return (get_cumulative_args (cum)->outgoing
8847           && ((mode == BLKmode ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode))
8848               % SH_MIN_ALIGN_FOR_CALLEE_COPY == 0));
8849 }
8850
8851 static int
8852 sh_arg_partial_bytes (cumulative_args_t cum_v, enum machine_mode mode,
8853                       tree type, bool named ATTRIBUTE_UNUSED)
8854 {
8855   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
8856   int words = 0;
8857
8858   if (!TARGET_SH5
8859       && PASS_IN_REG_P (*cum, mode, type)
8860       && !(TARGET_SH4 || TARGET_SH2A_DOUBLE)
8861       && (ROUND_REG (*cum, mode)
8862           + (mode != BLKmode
8863              ? ROUND_ADVANCE (GET_MODE_SIZE (mode))
8864              : ROUND_ADVANCE (int_size_in_bytes (type)))
8865           > NPARM_REGS (mode)))
8866     words = NPARM_REGS (mode) - ROUND_REG (*cum, mode);
8867
8868   else if (!TARGET_SHCOMPACT
8869            && SH5_WOULD_BE_PARTIAL_NREGS (*cum, mode, type, named))
8870     words = NPARM_REGS (SImode) - cum->arg_count[SH_ARG_INT];
8871
8872   return words * UNITS_PER_WORD;
8873 }
8874
8875
8876 /* Define where to put the arguments to a function.
8877    Value is zero to push the argument on the stack,
8878    or a hard register in which to store the argument.
8879
8880    MODE is the argument's machine mode.
8881    TYPE is the data type of the argument (as a tree).
8882     This is null for libcalls where that information may
8883     not be available.
8884    CUM is a variable of type CUMULATIVE_ARGS which gives info about
8885     the preceding args and about the function being called.
8886    NAMED is nonzero if this argument is a named parameter
8887     (otherwise it is an extra parameter matching an ellipsis).
8888
8889    On SH the first args are normally in registers
8890    and the rest are pushed.  Any arg that starts within the first
8891    NPARM_REGS words is at least partially passed in a register unless
8892    its data type forbids.  */
8893 static rtx
8894 sh_function_arg (cumulative_args_t ca_v, enum machine_mode mode,
8895                  const_tree type, bool named)
8896 {
8897   CUMULATIVE_ARGS *ca = get_cumulative_args (ca_v);
8898
8899   if (! TARGET_SH5 && mode == VOIDmode)
8900     return GEN_INT (ca->renesas_abi ? 1 : 0);
8901
8902   if (! TARGET_SH5
8903       && PASS_IN_REG_P (*ca, mode, type)
8904       && (named || ! (TARGET_HITACHI || ca->renesas_abi)))
8905     {
8906       int regno;
8907
8908       if (mode == SCmode && TARGET_SH4 && TARGET_LITTLE_ENDIAN
8909           && (! FUNCTION_ARG_SCmode_WART || (ROUND_REG (*ca, mode) & 1)))
8910         {
8911           rtx r1 = gen_rtx_EXPR_LIST (VOIDmode,
8912                                       gen_rtx_REG (SFmode,
8913                                                    BASE_ARG_REG (mode)
8914                                                    + (ROUND_REG (*ca, mode) ^ 1)),
8915                                       const0_rtx);
8916           rtx r2 = gen_rtx_EXPR_LIST (VOIDmode,
8917                                       gen_rtx_REG (SFmode,
8918                                                    BASE_ARG_REG (mode)
8919                                                    + ((ROUND_REG (*ca, mode) + 1) ^ 1)),
8920                                       GEN_INT (4));
8921           return gen_rtx_PARALLEL(SCmode, gen_rtvec(2, r1, r2));
8922         }
8923
8924      /* If the alignment of a DF value causes an SF register to be
8925         skipped, we will use that skipped register for the next SF
8926         value.  */
8927       if ((TARGET_HITACHI || ca->renesas_abi)
8928           && ca->free_single_fp_reg
8929           && mode == SFmode)
8930         return gen_rtx_REG (mode, ca->free_single_fp_reg);
8931
8932       regno = (BASE_ARG_REG (mode) + ROUND_REG (*ca, mode))
8933                ^ (mode == SFmode && TARGET_SH4
8934                   && TARGET_LITTLE_ENDIAN
8935                   && ! TARGET_HITACHI && ! ca->renesas_abi);
8936       return gen_rtx_REG (mode, regno);
8937
8938     }
8939
8940   if (TARGET_SH5)
8941     {
8942       if (mode == VOIDmode && TARGET_SHCOMPACT)
8943         return GEN_INT (ca->call_cookie);
8944
8945       /* The following test assumes unnamed arguments are promoted to
8946          DFmode.  */
8947       if (mode == SFmode && ca->free_single_fp_reg)
8948         return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode, ca->free_single_fp_reg);
8949
8950       if ((GET_SH_ARG_CLASS (mode) == SH_ARG_FLOAT)
8951           && (named || ! ca->prototype_p)
8952           && ca->arg_count[(int) SH_ARG_FLOAT] < NPARM_REGS (SFmode))
8953         {
8954           if (! ca->prototype_p && TARGET_SHMEDIA)
8955             return SH5_PROTOTYPELESS_FLOAT_ARG (*ca, mode);
8956
8957           return SH5_PROTOTYPED_FLOAT_ARG (*ca, mode,
8958                                            FIRST_FP_PARM_REG
8959                                            + ca->arg_count[(int) SH_ARG_FLOAT]);
8960         }
8961
8962       if (ca->arg_count[(int) SH_ARG_INT] < NPARM_REGS (SImode)
8963           && (! TARGET_SHCOMPACT
8964               || (! SHCOMPACT_FORCE_ON_STACK (mode, type)
8965                   && ! SH5_WOULD_BE_PARTIAL_NREGS (*ca, mode,
8966                                                    type, named))))
8967         {
8968           return gen_rtx_REG (mode, (FIRST_PARM_REG
8969                                        + ca->arg_count[(int) SH_ARG_INT]));
8970         }
8971
8972       return NULL_RTX;
8973     }
8974
8975   return NULL_RTX;
8976 }
8977
8978 /* Update the data in CUM to advance over an argument
8979    of mode MODE and data type TYPE.
8980    (TYPE is null for libcalls where that information may not be
8981    available.)  */
8982 static void
8983 sh_function_arg_advance (cumulative_args_t ca_v, enum machine_mode mode,
8984                          const_tree type, bool named)
8985 {
8986   CUMULATIVE_ARGS *ca = get_cumulative_args (ca_v);
8987
8988   if (ca->force_mem)
8989     ca->force_mem = 0;
8990   else if (TARGET_SH5)
8991     {
8992       const_tree type2 = (ca->byref && type
8993                           ? TREE_TYPE (type)
8994                           : type);
8995       enum machine_mode mode2 = (ca->byref && type
8996                                  ? TYPE_MODE (type2)
8997                                  : mode);
8998       int dwords = ((ca->byref
8999                      ? ca->byref
9000                      : mode2 == BLKmode
9001                      ? int_size_in_bytes (type2)
9002                      : GET_MODE_SIZE (mode2)) + 7) / 8;
9003       int numregs = MIN (dwords, NPARM_REGS (SImode)
9004                          - ca->arg_count[(int) SH_ARG_INT]);
9005
9006       if (numregs)
9007         {
9008           ca->arg_count[(int) SH_ARG_INT] += numregs;
9009           if (TARGET_SHCOMPACT
9010               && SHCOMPACT_FORCE_ON_STACK (mode2, type2))
9011             {
9012               ca->call_cookie
9013                 |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
9014                                         - numregs, 1);
9015               /* N.B. We want this also for outgoing.  */
9016               ca->stack_regs += numregs;
9017             }
9018           else if (ca->byref)
9019             {
9020               if (! ca->outgoing)
9021                 ca->stack_regs += numregs;
9022               ca->byref_regs += numregs;
9023               ca->byref = 0;
9024               do
9025                 ca->call_cookie
9026                   |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
9027                                           - numregs, 2);
9028               while (--numregs);
9029               ca->call_cookie
9030                 |= CALL_COOKIE_INT_REG (ca->arg_count[(int) SH_ARG_INT]
9031                                         - 1, 1);
9032             }
9033           else if (dwords > numregs)
9034             {
9035               int pushregs = numregs;
9036
9037               if (TARGET_SHCOMPACT)
9038                 ca->stack_regs += numregs;
9039               while (pushregs < NPARM_REGS (SImode) - 1
9040                      && (CALL_COOKIE_INT_REG_GET
9041                          (ca->call_cookie,
9042                           NPARM_REGS (SImode) - pushregs)
9043                          == 1))
9044                 {
9045                   ca->call_cookie
9046                     &= ~ CALL_COOKIE_INT_REG (NPARM_REGS (SImode)
9047                                               - pushregs, 1);
9048                   pushregs++;
9049                 }
9050               if (numregs == NPARM_REGS (SImode))
9051                 ca->call_cookie
9052                   |= CALL_COOKIE_INT_REG (0, 1)
9053                   | CALL_COOKIE_STACKSEQ (numregs - 1);
9054               else
9055                 ca->call_cookie
9056                   |= CALL_COOKIE_STACKSEQ (numregs);
9057             }
9058         }
9059       if (GET_SH_ARG_CLASS (mode2) == SH_ARG_FLOAT
9060           && (named || ! ca->prototype_p))
9061         {
9062           if (mode2 == SFmode && ca->free_single_fp_reg)
9063             ca->free_single_fp_reg = 0;
9064           else if (ca->arg_count[(int) SH_ARG_FLOAT]
9065                    < NPARM_REGS (SFmode))
9066             {
9067               int numfpregs
9068                 = MIN ((GET_MODE_SIZE (mode2) + 7) / 8 * 2,
9069                        NPARM_REGS (SFmode)
9070                        - ca->arg_count[(int) SH_ARG_FLOAT]);
9071
9072               ca->arg_count[(int) SH_ARG_FLOAT] += numfpregs;
9073
9074               if (TARGET_SHCOMPACT && ! ca->prototype_p)
9075                 {
9076                   if (ca->outgoing && numregs > 0)
9077                     do
9078                       {
9079                         ca->call_cookie
9080                           |= (CALL_COOKIE_INT_REG
9081                               (ca->arg_count[(int) SH_ARG_INT]
9082                                - numregs + ((numfpregs - 2) / 2),
9083                                4 + (ca->arg_count[(int) SH_ARG_FLOAT]
9084                                     - numfpregs) / 2));
9085                       }
9086                     while (numfpregs -= 2);
9087                 }
9088               else if (mode2 == SFmode && (named)
9089                        && (ca->arg_count[(int) SH_ARG_FLOAT]
9090                            < NPARM_REGS (SFmode)))
9091                 ca->free_single_fp_reg
9092                   = FIRST_FP_PARM_REG - numfpregs
9093                   + ca->arg_count[(int) SH_ARG_FLOAT] + 1;
9094             }
9095         }
9096       return;
9097     }
9098
9099   if ((TARGET_HITACHI || ca->renesas_abi) && TARGET_FPU_DOUBLE)
9100     {
9101       /* Note that we've used the skipped register.  */
9102       if (mode == SFmode && ca->free_single_fp_reg)
9103         {
9104           ca->free_single_fp_reg = 0;
9105           return;
9106         }
9107       /* When we have a DF after an SF, there's an SF register that get
9108          skipped in order to align the DF value.  We note this skipped
9109          register, because the next SF value will use it, and not the
9110          SF that follows the DF.  */
9111       if (mode == DFmode
9112           && ROUND_REG (*ca, DFmode) != ROUND_REG (*ca, SFmode))
9113         {
9114           ca->free_single_fp_reg = (ROUND_REG (*ca, SFmode)
9115                                     + BASE_ARG_REG (mode));
9116         }
9117     }
9118
9119   if (! ((TARGET_SH4 || TARGET_SH2A) || ca->renesas_abi)
9120       || PASS_IN_REG_P (*ca, mode, type))
9121     (ca->arg_count[(int) GET_SH_ARG_CLASS (mode)]
9122      = (ROUND_REG (*ca, mode)
9123         + (mode == BLKmode
9124            ? ROUND_ADVANCE (int_size_in_bytes (type))
9125            : ROUND_ADVANCE (GET_MODE_SIZE (mode)))));
9126 }
9127
9128 /* The Renesas calling convention doesn't quite fit into this scheme since
9129    the address is passed like an invisible argument, but one that is always
9130    passed in memory.  */
9131 static rtx
9132 sh_struct_value_rtx (tree fndecl, int incoming ATTRIBUTE_UNUSED)
9133 {
9134   if (TARGET_HITACHI || sh_attr_renesas_p (fndecl))
9135     return NULL_RTX;
9136   return gen_rtx_REG (Pmode, 2);
9137 }
9138
9139 /* Worker function for TARGET_FUNCTION_VALUE.
9140
9141    For the SH, this is like LIBCALL_VALUE, except that we must change the
9142    mode like PROMOTE_MODE does.
9143    ??? PROMOTE_MODE is ignored for non-scalar types.  The set of types
9144    tested here has to be kept in sync with the one in
9145    explow.c:promote_mode.  */
9146 static rtx
9147 sh_function_value (const_tree valtype,
9148                    const_tree fn_decl_or_type,
9149                    bool outgoing ATTRIBUTE_UNUSED)
9150 {
9151   if (fn_decl_or_type
9152       && !DECL_P (fn_decl_or_type))
9153     fn_decl_or_type = NULL;
9154
9155   return gen_rtx_REG (
9156            ((GET_MODE_CLASS (TYPE_MODE (valtype)) == MODE_INT
9157              && GET_MODE_SIZE (TYPE_MODE (valtype)) < 4
9158              && (TREE_CODE (valtype) == INTEGER_TYPE
9159                  || TREE_CODE (valtype) == ENUMERAL_TYPE
9160                  || TREE_CODE (valtype) == BOOLEAN_TYPE
9161                  || TREE_CODE (valtype) == REAL_TYPE
9162                  || TREE_CODE (valtype) == OFFSET_TYPE))
9163             && sh_promote_prototypes (fn_decl_or_type)
9164             ? (TARGET_SHMEDIA64 ? DImode : SImode) : TYPE_MODE (valtype)),
9165            BASE_RETURN_VALUE_REG (TYPE_MODE (valtype)));
9166 }
9167
9168 /* Worker function for TARGET_LIBCALL_VALUE.  */
9169 static rtx
9170 sh_libcall_value (enum machine_mode mode, const_rtx fun ATTRIBUTE_UNUSED)
9171 {
9172   return gen_rtx_REG (mode, BASE_RETURN_VALUE_REG (mode));
9173 }
9174
9175 /* Return true if N is a possible register number of function value.  */
9176 static bool
9177 sh_function_value_regno_p (const unsigned int regno)
9178 {
9179   return ((regno) == FIRST_RET_REG 
9180           || (TARGET_SH2E && (regno) == FIRST_FP_RET_REG)
9181           || (TARGET_SHMEDIA_FPU && (regno) == FIRST_FP_RET_REG));
9182 }
9183
9184 /* Worker function for TARGET_RETURN_IN_MEMORY.  */
9185 static bool
9186 sh_return_in_memory (const_tree type, const_tree fndecl)
9187 {
9188   if (TARGET_SH5)
9189     {
9190       if (TYPE_MODE (type) == BLKmode)
9191         return ((unsigned HOST_WIDE_INT) int_size_in_bytes (type)) > 8;
9192       else
9193         return GET_MODE_SIZE (TYPE_MODE (type)) > 8;
9194     }
9195   else
9196     {
9197       return (TYPE_MODE (type) == BLKmode
9198               || ((TARGET_HITACHI || sh_attr_renesas_p (fndecl))
9199                   && TREE_CODE (type) == RECORD_TYPE));
9200     }
9201 }
9202
9203 /* We actually emit the code in sh_expand_prologue.  We used to use
9204    a static variable to flag that we need to emit this code, but that
9205    doesn't when inlining, when functions are deferred and then emitted
9206    later.  Fortunately, we already have two flags that are part of struct
9207    function that tell if a function uses varargs or stdarg.  */
9208 static void
9209 sh_setup_incoming_varargs (cumulative_args_t ca,
9210                            enum machine_mode mode,
9211                            tree type,
9212                            int *pretend_arg_size,
9213                            int second_time ATTRIBUTE_UNUSED)
9214 {
9215   gcc_assert (cfun->stdarg);
9216   if (TARGET_VARARGS_PRETEND_ARGS (current_function_decl))
9217     {
9218       int named_parm_regs, anon_parm_regs;
9219
9220       named_parm_regs = (ROUND_REG (*get_cumulative_args (ca), mode)
9221                          + (mode == BLKmode
9222                             ? ROUND_ADVANCE (int_size_in_bytes (type))
9223                             : ROUND_ADVANCE (GET_MODE_SIZE (mode))));
9224       anon_parm_regs = NPARM_REGS (SImode) - named_parm_regs;
9225       if (anon_parm_regs > 0)
9226         *pretend_arg_size = anon_parm_regs * 4;
9227     }
9228 }
9229
9230 static bool
9231 sh_strict_argument_naming (cumulative_args_t ca ATTRIBUTE_UNUSED)
9232 {
9233   return TARGET_SH5;
9234 }
9235
9236 static bool
9237 sh_pretend_outgoing_varargs_named (cumulative_args_t ca_v)
9238 {
9239   CUMULATIVE_ARGS *ca = get_cumulative_args (ca_v);
9240
9241   return ! (TARGET_HITACHI || ca->renesas_abi) && ! TARGET_SH5;
9242 }
9243
9244
9245 /* Define the offset between two registers, one to be eliminated, and
9246    the other its replacement, at the start of a routine.  */
9247 int
9248 initial_elimination_offset (int from, int to)
9249 {
9250   int regs_saved;
9251   int regs_saved_rounding = 0;
9252   int total_saved_regs_space;
9253   int total_auto_space;
9254   int save_flags = target_flags;
9255   int copy_flags;
9256   HARD_REG_SET live_regs_mask;
9257
9258   shmedia_space_reserved_for_target_registers = false;
9259   regs_saved = calc_live_regs (&live_regs_mask);
9260   regs_saved += SHMEDIA_REGS_STACK_ADJUST ();
9261
9262   if (shmedia_reserve_space_for_target_registers_p (regs_saved, &live_regs_mask))
9263     {
9264       shmedia_space_reserved_for_target_registers = true;
9265       regs_saved += shmedia_target_regs_stack_adjust (&live_regs_mask);
9266     }
9267
9268   if (TARGET_SH5 && regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT))
9269     regs_saved_rounding = ((STACK_BOUNDARY / BITS_PER_UNIT)
9270                            - regs_saved % (STACK_BOUNDARY / BITS_PER_UNIT));
9271
9272   total_auto_space = rounded_frame_size (regs_saved) - regs_saved_rounding;
9273   copy_flags = target_flags;
9274   target_flags = save_flags;
9275
9276   total_saved_regs_space = regs_saved + regs_saved_rounding;
9277
9278   if (from == ARG_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
9279     return total_saved_regs_space + total_auto_space
9280            + crtl->args.info.byref_regs * 8;
9281
9282   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
9283     return total_saved_regs_space + total_auto_space
9284            + crtl->args.info.byref_regs * 8;
9285
9286   /* Initial gap between fp and sp is 0.  */
9287   if (from == HARD_FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
9288     return 0;
9289
9290   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
9291     return rounded_frame_size (0);
9292
9293   if (from == FRAME_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
9294     return rounded_frame_size (0);
9295
9296   gcc_assert (from == RETURN_ADDRESS_POINTER_REGNUM
9297               && (to == HARD_FRAME_POINTER_REGNUM
9298                   || to == STACK_POINTER_REGNUM));
9299   if (TARGET_SH5)
9300     {
9301       int n = total_saved_regs_space;
9302       int pr_reg = TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG;
9303       save_schedule schedule;
9304       save_entry *entry;
9305
9306       n += total_auto_space;
9307
9308       /* If it wasn't saved, there's not much we can do.  */
9309       if (! TEST_HARD_REG_BIT (live_regs_mask, pr_reg))
9310         return n;
9311
9312       target_flags = copy_flags;
9313
9314       sh5_schedule_saves (&live_regs_mask, &schedule, n);
9315       for (entry = &schedule.entries[1]; entry->mode != VOIDmode; entry++)
9316         if (entry->reg == pr_reg)
9317           {
9318             target_flags = save_flags;
9319             return entry->offset;
9320           }
9321       gcc_unreachable ();
9322     }
9323   else
9324     return total_auto_space;
9325 }
9326
9327 /* Parse the -mfixed-range= option string.  */
9328 void
9329 sh_fix_range (const char *const_str)
9330 {
9331   int i, first, last;
9332   char *str, *dash, *comma;
9333
9334   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
9335      REG2 are either register names or register numbers.  The effect
9336      of this option is to mark the registers in the range from REG1 to
9337      REG2 as ``fixed'' so they won't be used by the compiler.  */
9338
9339   i = strlen (const_str);
9340   str = (char *) alloca (i + 1);
9341   memcpy (str, const_str, i + 1);
9342
9343   while (1)
9344     {
9345       dash = strchr (str, '-');
9346       if (!dash)
9347         {
9348           warning (0, "value of -mfixed-range must have form REG1-REG2");
9349           return;
9350         }
9351       *dash = '\0';
9352       comma = strchr (dash + 1, ',');
9353       if (comma)
9354         *comma = '\0';
9355
9356       first = decode_reg_name (str);
9357       if (first < 0)
9358         {
9359           warning (0, "unknown register name: %s", str);
9360           return;
9361         }
9362
9363       last = decode_reg_name (dash + 1);
9364       if (last < 0)
9365         {
9366           warning (0, "unknown register name: %s", dash + 1);
9367           return;
9368         }
9369
9370       *dash = '-';
9371
9372       if (first > last)
9373         {
9374           warning (0, "%s-%s is an empty range", str, dash + 1);
9375           return;
9376         }
9377
9378       for (i = first; i <= last; ++i)
9379         fixed_regs[i] = call_used_regs[i] = 1;
9380
9381       if (!comma)
9382         break;
9383
9384       *comma = ',';
9385       str = comma + 1;
9386     }
9387 }
9388 \f
9389 /* Insert any deferred function attributes from earlier pragmas.  */
9390 static void
9391 sh_insert_attributes (tree node, tree *attributes)
9392 {
9393   tree attrs;
9394
9395   if (TREE_CODE (node) != FUNCTION_DECL)
9396     return;
9397
9398   /* We are only interested in fields.  */
9399   if (!DECL_P (node))
9400     return;
9401
9402   /* Append the attributes to the deferred attributes.  */
9403   *sh_deferred_function_attributes_tail = *attributes;
9404   attrs = sh_deferred_function_attributes;
9405   if (!attrs)
9406     return;
9407
9408   /* Some attributes imply or require the interrupt attribute.  */
9409   if (!lookup_attribute ("interrupt_handler", attrs)
9410       && !lookup_attribute ("interrupt_handler", DECL_ATTRIBUTES (node)))
9411     {
9412       /* If we have a trapa_handler, but no interrupt_handler attribute,
9413          insert an interrupt_handler attribute.  */
9414       if (lookup_attribute ("trapa_handler", attrs) != NULL_TREE)
9415         /* We can't use sh_pr_interrupt here because that's not in the
9416            java frontend.  */
9417         attrs
9418           = tree_cons (get_identifier("interrupt_handler"), NULL_TREE, attrs);
9419       /* However, for sp_switch, trap_exit, nosave_low_regs and resbank,
9420          if the interrupt attribute is missing, we ignore the attribute
9421          and warn.  */
9422       else if (lookup_attribute ("sp_switch", attrs)
9423                || lookup_attribute ("trap_exit", attrs)
9424                || lookup_attribute ("nosave_low_regs", attrs)
9425                || lookup_attribute ("resbank", attrs))
9426         {
9427           tree *tail;
9428
9429           for (tail = attributes; attrs; attrs = TREE_CHAIN (attrs))
9430             {
9431               if (is_attribute_p ("sp_switch", TREE_PURPOSE (attrs))
9432                   || is_attribute_p ("trap_exit", TREE_PURPOSE (attrs))
9433                   || is_attribute_p ("nosave_low_regs", TREE_PURPOSE (attrs))
9434                   || is_attribute_p ("resbank", TREE_PURPOSE (attrs)))
9435                 warning (OPT_Wattributes,
9436                          "%qE attribute only applies to interrupt functions",
9437                          TREE_PURPOSE (attrs));
9438               else
9439                 {
9440                   *tail = tree_cons (TREE_PURPOSE (attrs), NULL_TREE,
9441                                      NULL_TREE);
9442                   tail = &TREE_CHAIN (*tail);
9443                 }
9444             }
9445           attrs = *attributes;
9446         }
9447     }
9448
9449   /* Install the processed list.  */
9450   *attributes = attrs;
9451
9452   /* Clear deferred attributes.  */
9453   sh_deferred_function_attributes = NULL_TREE;
9454   sh_deferred_function_attributes_tail = &sh_deferred_function_attributes;
9455
9456   return;
9457 }
9458
9459 /*------------------------------------------------------------------------------
9460   Target specific attributes
9461   Supported attributes are:
9462
9463    * interrupt_handler
9464         Specifies this function is an interrupt handler.
9465
9466    * trapa_handler
9467         Like interrupt_handler, but don't save all registers.
9468
9469    * sp_switch
9470         Specifies an alternate stack for an interrupt handler to run on.
9471
9472    * trap_exit
9473         Use a trapa to exit an interrupt function instead of rte.
9474
9475    * nosave_low_regs
9476         Don't save r0..r7 in an interrupt handler function.
9477         This is useful on SH3* and SH4*, which have a separate set of low
9478         regs for user and privileged modes.
9479         This is mainly to be used for non-reentrant interrupt handlers (i.e.
9480         those that run with interrupts disabled and thus can't be
9481         interrupted thenselves).
9482
9483    * renesas
9484         Use Renesas calling/layout conventions (functions and structures).
9485
9486    * resbank
9487         In case of an interrupt handler function, use a register bank to
9488         save registers R0-R14, MACH, MACL, GBR and PR.
9489         This is available only on SH2A targets.
9490
9491    * function_vector
9492         Declares a function to be called using the TBR relative addressing
9493         mode.  Takes an argument that specifies the slot number in the table
9494         where this function can be looked up by the JSR/N @@(disp8,TBR) insn.
9495 */
9496
9497 /* Handle a 'resbank' attribute.  */
9498 static tree
9499 sh_handle_resbank_handler_attribute (tree * node, tree name,
9500                                      tree args ATTRIBUTE_UNUSED,
9501                                      int flags ATTRIBUTE_UNUSED,
9502                                      bool * no_add_attrs)
9503 {
9504   if (!TARGET_SH2A)
9505     {
9506       warning (OPT_Wattributes, "%qE attribute is supported only for SH2A",
9507                name);
9508       *no_add_attrs = true;
9509     }
9510   if (TREE_CODE (*node) != FUNCTION_DECL)
9511     {
9512       warning (OPT_Wattributes, "%qE attribute only applies to functions",
9513                name);
9514       *no_add_attrs = true;
9515     }
9516
9517   return NULL_TREE;
9518 }
9519
9520 /* Handle an "interrupt_handler" attribute; arguments as in
9521    struct attribute_spec.handler.  */
9522 static tree
9523 sh_handle_interrupt_handler_attribute (tree *node, tree name,
9524                                        tree args ATTRIBUTE_UNUSED,
9525                                        int flags ATTRIBUTE_UNUSED,
9526                                        bool *no_add_attrs)
9527 {
9528   if (TREE_CODE (*node) != FUNCTION_DECL)
9529     {
9530       warning (OPT_Wattributes, "%qE attribute only applies to functions",
9531                name);
9532       *no_add_attrs = true;
9533     }
9534   else if (TARGET_SHCOMPACT)
9535     {
9536       error ("attribute interrupt_handler is not compatible with -m5-compact");
9537       *no_add_attrs = true;
9538     }
9539
9540   return NULL_TREE;
9541 }
9542
9543 /* Handle an 'function_vector' attribute; arguments as in
9544    struct attribute_spec.handler.  */
9545 static tree
9546 sh2a_handle_function_vector_handler_attribute (tree * node, tree name,
9547                                                tree args ATTRIBUTE_UNUSED,
9548                                                int flags ATTRIBUTE_UNUSED,
9549                                                bool * no_add_attrs)
9550 {
9551   if (!TARGET_SH2A)
9552     {
9553       warning (OPT_Wattributes, "%qE attribute only applies to SH2A",
9554                name);
9555       *no_add_attrs = true;
9556     }
9557   else if (TREE_CODE (*node) != FUNCTION_DECL)
9558     {
9559       warning (OPT_Wattributes, "%qE attribute only applies to functions",
9560                name);
9561       *no_add_attrs = true;
9562     }
9563   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
9564     {
9565       /* The argument must be a constant integer.  */
9566       warning (OPT_Wattributes,
9567                "%qE attribute argument not an integer constant",
9568                name);
9569       *no_add_attrs = true;
9570     }
9571   else if (TREE_INT_CST_LOW (TREE_VALUE (args)) > 255)
9572     {
9573       /* The argument value must be between 0 to 255.  */
9574       warning (OPT_Wattributes,
9575                "%qE attribute argument should be between 0 to 255",
9576                name);
9577       *no_add_attrs = true;
9578     }
9579   return NULL_TREE;
9580 }
9581
9582 /* Returns true if current function has been assigned the attribute
9583    'function_vector'.  */
9584 bool
9585 sh2a_is_function_vector_call (rtx x)
9586 {
9587   if (GET_CODE (x) == SYMBOL_REF
9588       && (SYMBOL_REF_FLAGS (x) & SYMBOL_FLAG_FUNCVEC_FUNCTION))
9589     {
9590       tree tr = SYMBOL_REF_DECL (x);
9591
9592       if (sh2a_function_vector_p (tr))
9593         return true;
9594     }
9595
9596   return false;
9597 }
9598
9599 /* Returns the function vector number, if the attribute
9600    'function_vector' is assigned, otherwise returns zero.  */
9601 int
9602 sh2a_get_function_vector_number (rtx x)
9603 {
9604   int num;
9605   tree list, t;
9606
9607   if ((GET_CODE (x) == SYMBOL_REF)
9608       && (SYMBOL_REF_FLAGS (x) & SYMBOL_FLAG_FUNCVEC_FUNCTION))
9609     {
9610       t = SYMBOL_REF_DECL (x);
9611
9612       if (TREE_CODE (t) != FUNCTION_DECL)
9613         return 0;
9614
9615       list = SH_ATTRIBUTES (t);
9616       while (list)
9617         {
9618           if (is_attribute_p ("function_vector", TREE_PURPOSE (list)))
9619             {
9620               num = TREE_INT_CST_LOW (TREE_VALUE (TREE_VALUE (list)));
9621               return num;
9622             }
9623
9624           list = TREE_CHAIN (list);
9625         }
9626
9627       return 0;
9628     }
9629   else
9630     return 0;
9631 }
9632
9633 /* Handle an "sp_switch" attribute; arguments as in
9634    struct attribute_spec.handler.  */
9635 static tree
9636 sh_handle_sp_switch_attribute (tree *node, tree name, tree args,
9637                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
9638 {
9639   if (TREE_CODE (*node) != FUNCTION_DECL)
9640     {
9641       warning (OPT_Wattributes, "%qE attribute only applies to functions",
9642                name);
9643       *no_add_attrs = true;
9644     }
9645   else if (TREE_CODE (TREE_VALUE (args)) != STRING_CST)
9646     {
9647       /* The argument must be a constant string.  */
9648       warning (OPT_Wattributes, "%qE attribute argument not a string constant",
9649                name);
9650       *no_add_attrs = true;
9651     }
9652
9653   return NULL_TREE;
9654 }
9655
9656 /* Handle an "trap_exit" attribute; arguments as in
9657    struct attribute_spec.handler.  */
9658 static tree
9659 sh_handle_trap_exit_attribute (tree *node, tree name, tree args,
9660                                int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
9661 {
9662   if (TREE_CODE (*node) != FUNCTION_DECL)
9663     {
9664       warning (OPT_Wattributes, "%qE attribute only applies to functions",
9665                name);
9666       *no_add_attrs = true;
9667     }
9668   /* The argument specifies a trap number to be used in a trapa instruction
9669      at function exit (instead of an rte instruction).  */
9670   else if (TREE_CODE (TREE_VALUE (args)) != INTEGER_CST)
9671     {
9672       /* The argument must be a constant integer.  */
9673       warning (OPT_Wattributes, "%qE attribute argument not an "
9674                "integer constant", name);
9675       *no_add_attrs = true;
9676     }
9677
9678   return NULL_TREE;
9679 }
9680
9681 static tree
9682 sh_handle_renesas_attribute (tree *node ATTRIBUTE_UNUSED,
9683                              tree name ATTRIBUTE_UNUSED,
9684                              tree args ATTRIBUTE_UNUSED,
9685                              int flags ATTRIBUTE_UNUSED,
9686                              bool *no_add_attrs ATTRIBUTE_UNUSED)
9687 {
9688   return NULL_TREE;
9689 }
9690
9691 /* True if __attribute__((renesas)) or -mrenesas.  */
9692 bool
9693 sh_attr_renesas_p (const_tree td)
9694 {
9695   if (TARGET_HITACHI)
9696     return true;
9697   if (td == NULL_TREE)
9698     return false;
9699   if (DECL_P (td))
9700     td = TREE_TYPE (td);
9701   if (td == error_mark_node)
9702     return false;
9703   return (lookup_attribute ("renesas", TYPE_ATTRIBUTES (td))
9704           != NULL_TREE);
9705 }
9706
9707 /* True if __attribute__((renesas)) or -mrenesas, for the current
9708    function.  */
9709 bool
9710 sh_cfun_attr_renesas_p (void)
9711 {
9712   return sh_attr_renesas_p (current_function_decl);
9713 }
9714
9715 /* Returns true if the current function has the "interrupt_handler"
9716    attribute set.  */
9717 bool
9718 sh_cfun_interrupt_handler_p (void)
9719 {
9720   return (lookup_attribute ("interrupt_handler",
9721                             DECL_ATTRIBUTES (current_function_decl))
9722           != NULL_TREE);
9723 }
9724
9725 /* Returns true if FUNC has been assigned the attribute
9726    "function_vector".  */
9727 bool
9728 sh2a_function_vector_p (tree func)
9729 {
9730   tree list;
9731   if (TREE_CODE (func) != FUNCTION_DECL)
9732     return false;
9733
9734   list = SH_ATTRIBUTES (func);
9735   while (list)
9736     {
9737       if (is_attribute_p ("function_vector", TREE_PURPOSE (list)))
9738         return true;
9739
9740       list = TREE_CHAIN (list);
9741     }
9742   return false;
9743 }
9744
9745 /* Returns true if given tree has the "resbank" attribute set.  */
9746 bool
9747 sh_cfun_resbank_handler_p (void)
9748 {
9749   return ((lookup_attribute ("resbank",
9750                              DECL_ATTRIBUTES (current_function_decl))
9751           != NULL_TREE)
9752           && (lookup_attribute ("interrupt_handler",
9753                                 DECL_ATTRIBUTES (current_function_decl))
9754               != NULL_TREE) && TARGET_SH2A);
9755 }
9756
9757 /* Returns true if the current function has a "trap_exit" attribute set.  */
9758 bool
9759 sh_cfun_trap_exit_p (void)
9760 {
9761   return lookup_attribute ("trap_exit", DECL_ATTRIBUTES (current_function_decl))
9762          != NULL_TREE;
9763 }
9764
9765 /* Implement TARGET_CHECK_PCH_TARGET_FLAGS.  */
9766 static const char *
9767 sh_check_pch_target_flags (int old_flags)
9768 {
9769   if ((old_flags ^ target_flags) & (MASK_SH1 | MASK_SH2 | MASK_SH3
9770                                     | MASK_SH_E | MASK_HARD_SH4
9771                                     | MASK_FPU_SINGLE | MASK_SH4))
9772     return _("created and used with different architectures / ABIs");
9773   if ((old_flags ^ target_flags) & MASK_HITACHI)
9774     return _("created and used with different ABIs");
9775   if ((old_flags ^ target_flags) & MASK_LITTLE_ENDIAN)
9776     return _("created and used with different endianness");
9777   return NULL;
9778 }
9779 \f
9780 /* Predicates used by the templates.  */
9781
9782 /* Returns true if OP is MACL, MACH or PR.  The input must be a REG rtx.
9783    Used only in general_movsrc_operand.  */
9784 bool
9785 system_reg_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
9786 {
9787   switch (REGNO (op))
9788     {
9789     case PR_REG:
9790     case MACL_REG:
9791     case MACH_REG:
9792       return true;
9793     }
9794   return false;
9795 }
9796
9797 /* Returns true if OP is a floating point value with value 0.0.  */
9798 bool
9799 fp_zero_operand (rtx op)
9800 {
9801   REAL_VALUE_TYPE r;
9802
9803   if (GET_MODE (op) != SFmode)
9804     return false;
9805
9806   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
9807   return REAL_VALUES_EQUAL (r, dconst0) && ! REAL_VALUE_MINUS_ZERO (r);
9808 }
9809
9810 /* Returns true if OP is a floating point value with value 1.0.  */
9811 bool
9812 fp_one_operand (rtx op)
9813 {
9814   REAL_VALUE_TYPE r;
9815
9816   if (GET_MODE (op) != SFmode)
9817     return false;
9818
9819   REAL_VALUE_FROM_CONST_DOUBLE (r, op);
9820   return REAL_VALUES_EQUAL (r, dconst1);
9821 }
9822
9823 /* In general mode switching is used.  If we are
9824    compiling without -mfmovd, movsf_ie isn't taken into account for
9825    mode switching.  We could check in machine_dependent_reorg for
9826    cases where we know we are in single precision mode, but there is
9827    interface to find that out during reload, so we must avoid
9828    choosing an fldi alternative during reload and thus failing to
9829    allocate a scratch register for the constant loading.  */
9830 bool
9831 fldi_ok (void)
9832 {
9833   return true;
9834 }
9835
9836 /* Return the TLS type for TLS symbols.  */
9837 enum tls_model
9838 tls_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
9839 {
9840   if (GET_CODE (op) != SYMBOL_REF)
9841     return TLS_MODEL_NONE;
9842   return SYMBOL_REF_TLS_MODEL (op);
9843 }
9844 \f
9845 /* Return the destination address of a branch.  */
9846 static int
9847 branch_dest (rtx branch)
9848 {
9849   rtx dest = SET_SRC (PATTERN (branch));
9850   int dest_uid;
9851
9852   if (GET_CODE (dest) == IF_THEN_ELSE)
9853     dest = XEXP (dest, 1);
9854   dest = XEXP (dest, 0);
9855   dest_uid = INSN_UID (dest);
9856   return INSN_ADDRESSES (dest_uid);
9857 }
9858 \f
9859 /* Return nonzero if REG is not used after INSN.
9860    We assume REG is a reload reg, and therefore does
9861    not live past labels.  It may live past calls or jumps though.  */
9862 bool
9863 reg_unused_after (rtx reg, rtx insn)
9864 {
9865   enum rtx_code code;
9866   rtx set;
9867
9868   /* If the reg is set by this instruction, then it is safe for our
9869      case.  Disregard the case where this is a store to memory, since
9870      we are checking a register used in the store address.  */
9871   set = single_set (insn);
9872   if (set && !MEM_P (SET_DEST (set))
9873       && reg_overlap_mentioned_p (reg, SET_DEST (set)))
9874     return true;
9875
9876   while ((insn = NEXT_INSN (insn)))
9877     {
9878       rtx set;
9879       if (!INSN_P (insn))
9880         continue;
9881
9882       code = GET_CODE (insn);
9883
9884 #if 0
9885       /* If this is a label that existed before reload, then the register
9886          is dead here.  However, if this is a label added by reorg, then
9887          the register may still be live here.  We can't tell the difference,
9888          so we just ignore labels completely.  */
9889       if (code == CODE_LABEL)
9890         return 1;
9891       /* else */
9892 #endif
9893
9894       if (code == JUMP_INSN)
9895         return false;
9896
9897       /* If this is a sequence, we must handle them all at once.
9898          We could have for instance a call that sets the target register,
9899          and an insn in a delay slot that uses the register.  In this case,
9900          we must return 0.  */
9901       else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
9902         {
9903           int i;
9904           int retval = 0;
9905
9906           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
9907             {
9908               rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
9909               rtx set = single_set (this_insn);
9910
9911               if (CALL_P (this_insn))
9912                 code = CALL_INSN;
9913               else if (JUMP_P (this_insn))
9914                 {
9915                   if (INSN_ANNULLED_BRANCH_P (this_insn))
9916                     return false;
9917                   code = JUMP_INSN;
9918                 }
9919
9920               if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
9921                 return false;
9922               if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
9923                 {
9924                   if (!MEM_P (SET_DEST (set)))
9925                     retval = true;
9926                   else
9927                     return false;
9928                 }
9929               if (set == NULL_RTX
9930                   && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
9931                 return false;
9932             }
9933           if (retval == 1)
9934             return true;
9935           else if (code == JUMP_INSN)
9936             return false;
9937         }
9938
9939       set = single_set (insn);
9940       if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
9941         return false;
9942       if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
9943         return !MEM_P (SET_DEST (set));
9944       if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
9945         return false;
9946
9947       if (code == CALL_INSN && call_really_used_regs[REGNO (reg)])
9948         return true;
9949     }
9950   return true;
9951 }
9952 \f
9953 #include "ggc.h"
9954
9955 static GTY(()) rtx t_reg_rtx;
9956 rtx
9957 get_t_reg_rtx (void)
9958 {
9959   if (! t_reg_rtx)
9960     t_reg_rtx = gen_rtx_REG (SImode, T_REG);
9961   return t_reg_rtx;
9962 }
9963
9964 static GTY(()) rtx fpscr_rtx;
9965 rtx
9966 get_fpscr_rtx (void)
9967 {
9968   if (! fpscr_rtx)
9969     {
9970       fpscr_rtx = gen_rtx_REG (PSImode, FPSCR_REG);
9971       REG_USERVAR_P (fpscr_rtx) = 1;
9972       mark_user_reg (fpscr_rtx);
9973     }
9974   if (! reload_completed || mdep_reorg_phase != SH_AFTER_MDEP_REORG)
9975     mark_user_reg (fpscr_rtx);
9976   return fpscr_rtx;
9977 }
9978
9979 static GTY(()) tree fpscr_values;
9980
9981 static void
9982 emit_fpu_switch (rtx scratch, int index)
9983 {
9984   rtx dst, src;
9985
9986   if (fpscr_values == NULL)
9987     {
9988       tree t;
9989
9990       t = build_index_type (integer_one_node);
9991       t = build_array_type (integer_type_node, t);
9992       t = build_decl (BUILTINS_LOCATION,
9993                       VAR_DECL, get_identifier ("__fpscr_values"), t);
9994       DECL_ARTIFICIAL (t) = 1;
9995       DECL_IGNORED_P (t) = 1;
9996       DECL_EXTERNAL (t) = 1;
9997       TREE_STATIC (t) = 1;
9998       TREE_PUBLIC (t) = 1;
9999       TREE_USED (t) = 1;
10000
10001       fpscr_values = t;
10002     }
10003
10004   src = DECL_RTL (fpscr_values);
10005   if (!can_create_pseudo_p ())
10006     {
10007       emit_move_insn (scratch, XEXP (src, 0));
10008       if (index != 0)
10009         emit_insn (gen_addsi3 (scratch, scratch, GEN_INT (index * 4)));
10010       src = adjust_automodify_address (src, PSImode, scratch, index * 4);
10011     }
10012   else
10013     src = adjust_address (src, PSImode, index * 4);
10014
10015   dst = get_fpscr_rtx ();
10016   emit_move_insn (dst, src);
10017 }
10018
10019 void
10020 emit_sf_insn (rtx pat)
10021 {
10022   emit_insn (pat);
10023 }
10024
10025 void
10026 emit_df_insn (rtx pat)
10027 {
10028   emit_insn (pat);
10029 }
10030
10031 void
10032 expand_sf_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
10033 {
10034   emit_sf_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
10035 }
10036
10037 void
10038 expand_sf_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
10039 {
10040   emit_sf_insn ((*fun) (operands[0], operands[1], operands[2],
10041                          get_fpscr_rtx ()));
10042 }
10043
10044 void
10045 expand_df_unop (rtx (*fun) (rtx, rtx, rtx), rtx *operands)
10046 {
10047   emit_df_insn ((*fun) (operands[0], operands[1], get_fpscr_rtx ()));
10048 }
10049
10050 void
10051 expand_df_binop (rtx (*fun) (rtx, rtx, rtx, rtx), rtx *operands)
10052 {
10053   emit_df_insn ((*fun) (operands[0], operands[1], operands[2],
10054                         get_fpscr_rtx ()));
10055 }
10056 \f
10057 static rtx get_free_reg (HARD_REG_SET);
10058
10059 /* This function returns a register to use to load the address to load
10060    the fpscr from.  Currently it always returns r1 or r7, but when we are
10061    able to use pseudo registers after combine, or have a better mechanism
10062    for choosing a register, it should be done here.  */
10063 /* REGS_LIVE is the liveness information for the point for which we
10064    need this allocation.  In some bare-bones exit blocks, r1 is live at the
10065    start.  We can even have all of r0..r3 being live:
10066 __complex__ long long f (double d) { if (d == 0) return 2; else return 3; }
10067    INSN before which new insns are placed with will clobber the register
10068    we return.  If a basic block consists only of setting the return value
10069    register to a pseudo and using that register, the return value is not
10070    live before or after this block, yet we we'll insert our insns right in
10071    the middle.  */
10072 static rtx
10073 get_free_reg (HARD_REG_SET regs_live)
10074 {
10075   if (! TEST_HARD_REG_BIT (regs_live, 1))
10076     return gen_rtx_REG (Pmode, 1);
10077
10078   /* Hard reg 1 is live; since this is a small register classes target,
10079      there shouldn't be anything but a jump before the function end.  */
10080   gcc_assert (!TEST_HARD_REG_BIT (regs_live, 7));
10081   return gen_rtx_REG (Pmode, 7);
10082 }
10083
10084 /* This function will set the fpscr from memory.
10085    MODE is the mode we are setting it to.  */
10086 void
10087 fpscr_set_from_mem (int mode, HARD_REG_SET regs_live)
10088 {
10089   enum attr_fp_mode fp_mode = (enum attr_fp_mode) mode;
10090   enum attr_fp_mode norm_mode = ACTUAL_NORMAL_MODE (FP_MODE);
10091   rtx addr_reg;
10092
10093   addr_reg = !can_create_pseudo_p () ? get_free_reg (regs_live) : NULL_RTX;
10094   emit_fpu_switch (addr_reg, fp_mode == norm_mode);
10095 }
10096
10097 /* Is the given character a logical line separator for the assembler?  */
10098 #ifndef IS_ASM_LOGICAL_LINE_SEPARATOR
10099 #define IS_ASM_LOGICAL_LINE_SEPARATOR(C, STR) ((C) == ';')
10100 #endif
10101
10102 static bool
10103 sequence_insn_p (rtx insn)
10104 {
10105   rtx prev, next;
10106
10107   prev = PREV_INSN (insn);
10108   if (prev == NULL)
10109     return false;
10110
10111   next = NEXT_INSN (prev);
10112   if (next == NULL)
10113     return false;
10114
10115   return INSN_P (next) && GET_CODE (PATTERN (next)) == SEQUENCE;
10116 }
10117
10118 int
10119 sh_insn_length_adjustment (rtx insn)
10120 {
10121   /* Instructions with unfilled delay slots take up an extra two bytes for
10122      the nop in the delay slot.  */
10123   if (((NONJUMP_INSN_P (insn)
10124         && GET_CODE (PATTERN (insn)) != USE
10125         && GET_CODE (PATTERN (insn)) != CLOBBER)
10126        || CALL_P (insn)
10127        || (JUMP_P (insn) && !JUMP_TABLE_DATA_P (insn)))
10128       && ! sequence_insn_p (insn)
10129       && get_attr_needs_delay_slot (insn) == NEEDS_DELAY_SLOT_YES)
10130     return 2;
10131
10132   /* SH2e has a bug that prevents the use of annulled branches, so if
10133      the delay slot is not filled, we'll have to put a NOP in it.  */
10134   if (sh_cpu_attr == CPU_SH2E
10135       && JUMP_P (insn) && !JUMP_TABLE_DATA_P (insn)
10136       && get_attr_type (insn) == TYPE_CBRANCH
10137       && ! sequence_insn_p (insn))
10138     return 2;
10139
10140   /* sh-dsp parallel processing insn take four bytes instead of two.  */
10141
10142   if (NONJUMP_INSN_P (insn))
10143     {
10144       int sum = 0;
10145       rtx body = PATTERN (insn);
10146       const char *templ;
10147       char c;
10148       bool maybe_label = true;
10149
10150       if (GET_CODE (body) == ASM_INPUT)
10151         templ = XSTR (body, 0);
10152       else if (asm_noperands (body) >= 0)
10153         templ
10154           = decode_asm_operands (body, NULL, NULL, NULL, NULL, NULL);
10155       else
10156         return 0;
10157       do
10158         {
10159           int ppi_adjust = 0;
10160
10161           do
10162             c = *templ++;
10163           while (c == ' ' || c == '\t');
10164           /* all sh-dsp parallel-processing insns start with p.
10165              The only non-ppi sh insn starting with p is pref.
10166              The only ppi starting with pr is prnd.  */
10167           if ((c == 'p' || c == 'P') && strncasecmp ("re", templ, 2))
10168             ppi_adjust = 2;
10169           /* The repeat pseudo-insn expands two three insns, a total of
10170              six bytes in size.  */
10171           else if ((c == 'r' || c == 'R')
10172                    && ! strncasecmp ("epeat", templ, 5))
10173             ppi_adjust = 4;
10174           while (c && c != '\n'
10175                  && ! IS_ASM_LOGICAL_LINE_SEPARATOR (c, templ))
10176             {
10177               /* If this is a label, it is obviously not a ppi insn.  */
10178               if (c == ':' && maybe_label)
10179                 {
10180                   ppi_adjust = 0;
10181                   break;
10182                 }
10183               else if (c == '\'' || c == '"')
10184                 maybe_label = false;
10185               c = *templ++;
10186             }
10187           sum += ppi_adjust;
10188           maybe_label = c != ':';
10189         }
10190       while (c);
10191       return sum;
10192     }
10193   return 0;
10194 }
10195 \f
10196 /* Return TRUE for a valid displacement for the REG+disp addressing
10197    with MODE.  */
10198 bool
10199 sh_legitimate_index_p (enum machine_mode mode, rtx op, bool consider_sh2a,
10200                        bool allow_zero)
10201 {
10202   if (! CONST_INT_P (op))
10203     return false;
10204
10205   if (TARGET_SHMEDIA)
10206     {
10207       int size;
10208
10209       /* Check if this is the address of an unaligned load / store.  */
10210       if (mode == VOIDmode)
10211         return satisfies_constraint_I06 (op);
10212
10213       size = GET_MODE_SIZE (mode);
10214       return (!(INTVAL (op) & (size - 1))
10215               && INTVAL (op) >= -512 * size
10216               && INTVAL (op) < 512 * size);
10217     }
10218   else
10219     {
10220       const HOST_WIDE_INT offset = INTVAL (op);
10221       const int max_disp = max_mov_insn_displacement (mode, consider_sh2a);
10222       const int align_mask = mov_insn_alignment_mask (mode, consider_sh2a);
10223
10224       /* If the mode does not support any displacement always return false.
10225          Even though an index of '0' is actually always valid, it will cause
10226          troubles when e.g. a DFmode move is split into two SFmode moves,
10227          where one SFmode move will have index '0' and the other move will
10228          have index '4'.  */
10229        if (!allow_zero && max_disp < 1)
10230         return false;
10231
10232       return offset >= 0 && offset <= max_disp && (offset & align_mask) == 0;
10233     }
10234 }
10235
10236 /* Recognize an RTL expression that is a valid memory address for
10237    an instruction.
10238    The MODE argument is the machine mode for the MEM expression
10239    that wants to use this address.
10240    Allow  REG
10241           REG+disp
10242           REG+r0
10243           REG++
10244           --REG
10245           GBR
10246           GBR+disp  */
10247 static bool
10248 sh_legitimate_address_p (enum machine_mode mode, rtx x, bool strict)
10249 {
10250   if (REG_P (x) && REGNO (x) == GBR_REG)
10251     return true;
10252
10253   if (MAYBE_BASE_REGISTER_RTX_P (x, strict))
10254     return true;
10255   else if ((GET_CODE (x) == POST_INC || GET_CODE (x) == PRE_DEC)
10256            && ! TARGET_SHMEDIA
10257            && MAYBE_BASE_REGISTER_RTX_P (XEXP (x, 0), strict))
10258     return true;
10259   else if (GET_CODE (x) == PLUS
10260            && (mode != PSImode || reload_completed))
10261     {
10262       rtx xop0 = XEXP (x, 0);
10263       rtx xop1 = XEXP (x, 1);
10264
10265       if (REG_P (xop0) && REGNO (xop0) == GBR_REG)
10266         return gbr_displacement (xop1, mode);
10267
10268       if (GET_MODE_SIZE (mode) <= 8
10269           && MAYBE_BASE_REGISTER_RTX_P (xop0, strict)
10270           && sh_legitimate_index_p (mode, xop1, TARGET_SH2A, false))
10271         return true;
10272
10273       if ((ALLOW_INDEXED_ADDRESS || GET_MODE (x) == DImode
10274            || ((xop0 == stack_pointer_rtx
10275                 || xop0 == hard_frame_pointer_rtx)
10276                && REG_P (xop1) && REGNO (xop1) == R0_REG)
10277            || ((xop1 == stack_pointer_rtx
10278                 || xop1 == hard_frame_pointer_rtx)
10279                && REG_P (xop0) && REGNO (xop0) == R0_REG))
10280           && ((!TARGET_SHMEDIA && GET_MODE_SIZE (mode) <= 4)
10281               || (TARGET_SHMEDIA && GET_MODE_SIZE (mode) <= 8)
10282               || ((TARGET_SH4 || TARGET_SH2A_DOUBLE)
10283                   && TARGET_FMOVD && mode == DFmode)))
10284         {
10285           if (MAYBE_BASE_REGISTER_RTX_P (xop1, strict)
10286               && MAYBE_INDEX_REGISTER_RTX_P (xop0, strict))
10287             return true;
10288           if (MAYBE_INDEX_REGISTER_RTX_P (xop1, strict)
10289               && MAYBE_BASE_REGISTER_RTX_P (xop0, strict))
10290             return true;
10291         }
10292     }
10293
10294   return false;
10295 }
10296 \f
10297 /* Return TRUE if X references a SYMBOL_REF or LABEL_REF whose symbol
10298    isn't protected by a PIC unspec.  */
10299 bool
10300 nonpic_symbol_mentioned_p (rtx x)
10301 {
10302   const char *fmt;
10303   int i;
10304
10305   if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF
10306       || GET_CODE (x) == PC)
10307     return true;
10308
10309   /* We don't want to look into the possible MEM location of a
10310      CONST_DOUBLE, since we're not going to use it, in general.  */
10311   if (GET_CODE (x) == CONST_DOUBLE)
10312     return false;
10313
10314   if (GET_CODE (x) == UNSPEC
10315       && (XINT (x, 1) == UNSPEC_PIC
10316           || XINT (x, 1) == UNSPEC_GOT
10317           || XINT (x, 1) == UNSPEC_GOTOFF
10318           || XINT (x, 1) == UNSPEC_GOTPLT
10319           || XINT (x, 1) == UNSPEC_GOTTPOFF
10320           || XINT (x, 1) == UNSPEC_DTPOFF
10321           || XINT (x, 1) == UNSPEC_TPOFF
10322           || XINT (x, 1) == UNSPEC_PLT
10323           || XINT (x, 1) == UNSPEC_SYMOFF
10324           || XINT (x, 1) == UNSPEC_PCREL_SYMOFF))
10325     return false;
10326
10327   fmt = GET_RTX_FORMAT (GET_CODE (x));
10328   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
10329     {
10330       if (fmt[i] == 'E')
10331         {
10332           int j;
10333           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
10334             if (nonpic_symbol_mentioned_p (XVECEXP (x, i, j)))
10335               return true;
10336         }
10337       else if (fmt[i] == 'e' && nonpic_symbol_mentioned_p (XEXP (x, i)))
10338         return true;
10339     }
10340
10341   return false;
10342 }
10343
10344 /* Convert a non-PIC address in `orig' to a PIC address using @GOT or
10345    @GOTOFF in `reg'.  */
10346 rtx
10347 legitimize_pic_address (rtx orig, enum machine_mode mode ATTRIBUTE_UNUSED,
10348                         rtx reg)
10349 {
10350   if (tls_symbolic_operand (orig, Pmode) != TLS_MODEL_NONE)
10351     return orig;
10352
10353   if (GET_CODE (orig) == LABEL_REF
10354       || (GET_CODE (orig) == SYMBOL_REF && SYMBOL_REF_LOCAL_P (orig)))
10355     {
10356       if (reg == NULL_RTX)
10357         reg = gen_reg_rtx (Pmode);
10358
10359       emit_insn (gen_symGOTOFF2reg (reg, orig));
10360       return reg;
10361     }
10362   else if (GET_CODE (orig) == SYMBOL_REF)
10363     {
10364       if (reg == NULL_RTX)
10365         reg = gen_reg_rtx (Pmode);
10366
10367       emit_insn (gen_symGOT2reg (reg, orig));
10368       return reg;
10369     }
10370   return orig;
10371 }
10372
10373 /* Given a (logical) mode size and an offset in bytes, try to find a the
10374    appropriate displacement value for a mov insn.  On SH the displacements
10375    are limited to max. 60 bytes for SImode, max. 30 bytes in HImode and max.
10376    15 bytes in QImode.  To compensate this we create a new base address by
10377    adding an adjustment value to it.
10378
10379    If the originally requested offset is greater than 127 we prefer using
10380    values 124..127 over 128..131 to increase opportunities to use the
10381    add #imm, Rn insn.
10382
10383    In some cases it is possible that a requested offset might seem unaligned
10384    or inappropriate for the mode size, like offset = 2 and mode size = 4.
10385    This is compensated by adjusting the base address so that the effective
10386    address of the displacement move insn will be aligned. 
10387
10388    This is not the best possible way of rebasing the base address, as it
10389    does not look at other present displacement addressings around it.
10390    In some cases this can create more base address adjustments than would
10391    actually be necessary.  */
10392 struct disp_adjust
10393 {
10394   rtx offset_adjust;
10395   rtx mov_disp;
10396 };
10397
10398 static struct disp_adjust
10399 sh_find_mov_disp_adjust (enum machine_mode mode, HOST_WIDE_INT offset)
10400 {
10401   struct disp_adjust res = { NULL_RTX, NULL_RTX };
10402
10403   /* Do not try to use SH2A's large displacements here, because this would
10404      effectively disable the small displacement insns.  */
10405   const int mode_sz = GET_MODE_SIZE (mode);
10406   const int mov_insn_sz = mov_insn_size (mode, false);
10407   const int max_disp = max_mov_insn_displacement (mode, false);
10408   const int max_disp_next = max_disp + mov_insn_sz;
10409   HOST_WIDE_INT align_modifier = offset > 127 ? mov_insn_sz : 0;
10410   HOST_WIDE_INT offset_adjust;
10411
10412   /* In some cases this actually does happen and we must check for it.  */
10413   if (mode_sz < 1 || mode_sz > 8 || max_disp < 1)
10414     return res;
10415
10416   /* Keeps the previous behavior for QImode displacement addressing.
10417      This just decides how the offset is re-based.  Removing this special
10418      case will result in slightly bigger code on average, but it's not that
10419      bad actually.  */
10420   if (mov_insn_sz == 1)
10421     align_modifier = 0;
10422
10423   offset_adjust = ((offset + align_modifier) & ~max_disp) - align_modifier;
10424
10425   if (mode_sz + offset - offset_adjust <= max_disp_next)
10426     {
10427       res.offset_adjust = GEN_INT (offset_adjust);
10428       res.mov_disp = GEN_INT (offset - offset_adjust);
10429     }
10430
10431   return res;
10432 }
10433
10434 /* Try to modify an illegitimate address and make it legitimate.
10435    If we find one, return the new, valid address.
10436    Otherwise, return the original address.  */
10437 static rtx
10438 sh_legitimize_address (rtx x, rtx oldx, enum machine_mode mode)
10439 {
10440   if (flag_pic)
10441     x = legitimize_pic_address (oldx, mode, NULL_RTX);
10442
10443   if (TARGET_SHMEDIA)
10444     return x;
10445
10446   if (((TARGET_SH4 || TARGET_SH2A_DOUBLE) && mode == DFmode)
10447       || (TARGET_SH2E && mode == SFmode))
10448     return x;
10449
10450   if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1))
10451       && BASE_REGISTER_RTX_P (XEXP (x, 0)))
10452     {
10453       struct disp_adjust adj = sh_find_mov_disp_adjust (mode,
10454                                                         INTVAL (XEXP (x, 1)));
10455
10456       if (adj.offset_adjust != NULL_RTX && adj.mov_disp != NULL_RTX)
10457         {
10458           rtx sum = expand_binop (Pmode, add_optab, XEXP (x, 0),
10459                                   adj.offset_adjust, NULL_RTX, 0,
10460                                   OPTAB_LIB_WIDEN);
10461           return gen_rtx_PLUS (Pmode, sum, adj.mov_disp);
10462         }
10463     }
10464
10465   return x;
10466 }
10467
10468 /* Attempt to replace *p, which is an address that needs reloading, with
10469    a valid memory address for an operand of mode MODE.
10470    Like for sh_legitimize_address, for the SH we try to get a normal form
10471    of the address.  That will allow inheritance of the address reloads.  */
10472 bool
10473 sh_legitimize_reload_address (rtx *p, enum machine_mode mode, int opnum,
10474                               int itype)
10475 {
10476   enum reload_type type = (enum reload_type) itype;
10477   const int mode_sz = GET_MODE_SIZE (mode);
10478
10479   if (TARGET_SHMEDIA)
10480     return false;
10481
10482   if (GET_CODE (*p) == PLUS && CONST_INT_P (XEXP (*p, 1))
10483       && MAYBE_BASE_REGISTER_RTX_P (XEXP (*p, 0), true)
10484       && ! (mode == PSImode && type == RELOAD_FOR_INPUT_ADDRESS)
10485       && (ALLOW_INDEXED_ADDRESS
10486           || XEXP (*p, 0) == stack_pointer_rtx
10487           || XEXP (*p, 0) == hard_frame_pointer_rtx))
10488     {
10489       const HOST_WIDE_INT offset = INTVAL (XEXP (*p, 1));
10490       struct disp_adjust adj = sh_find_mov_disp_adjust (mode, offset);
10491
10492       if (TARGET_SH2A && mode == DFmode && (offset & 0x7))
10493         {
10494           push_reload (*p, NULL_RTX, p, NULL,
10495                        BASE_REG_CLASS, Pmode, VOIDmode, 0, 0, opnum, type);
10496           return true;
10497         }
10498
10499       if (TARGET_SH2E && mode == SFmode)
10500         {
10501           *p = copy_rtx (*p);
10502           push_reload (*p, NULL_RTX, p, NULL,
10503                        BASE_REG_CLASS, Pmode, VOIDmode, 0, 0, opnum, type);
10504           return true;
10505         }
10506
10507       /* FIXME: Do not allow to legitimize QImode and HImode displacement
10508          moves because then reload has a problem figuring the constraint
10509          that the move insn target/source reg must be R0.
10510          Or maybe some handling is wrong in sh_secondary_reload for this
10511          to work properly? */
10512       if ((mode_sz == 4 || mode_sz == 8)
10513           && ! (TARGET_SH4 && mode == DFmode)
10514           && adj.offset_adjust != NULL_RTX && adj.mov_disp != NULL_RTX)
10515         {
10516           rtx sum = gen_rtx_PLUS (Pmode, XEXP (*p, 0), adj.offset_adjust);
10517           *p = gen_rtx_PLUS (Pmode, sum, adj.mov_disp);
10518           push_reload (sum, NULL_RTX, &XEXP (*p, 0), NULL,
10519                        BASE_REG_CLASS, Pmode, VOIDmode, 0, 0, opnum, type);
10520           return true;
10521         }
10522     }
10523
10524   /* We must re-recognize what we created before.  */
10525   if (GET_CODE (*p) == PLUS
10526       && (mode_sz == 4 || mode_sz == 8)
10527       && GET_CODE (XEXP (*p, 0)) == PLUS
10528       && CONST_INT_P (XEXP (XEXP (*p, 0), 1))
10529       && MAYBE_BASE_REGISTER_RTX_P (XEXP (XEXP (*p, 0), 0), true)
10530       && CONST_INT_P (XEXP (*p, 1))
10531       && ! (TARGET_SH2E && mode == SFmode))
10532     {
10533       /* Because this address is so complex, we know it must have
10534          been created by LEGITIMIZE_RELOAD_ADDRESS before; thus,
10535          it is already unshared, and needs no further unsharing.  */
10536       push_reload (XEXP (*p, 0), NULL_RTX, &XEXP (*p, 0), NULL,
10537                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0, opnum, type);
10538       return true;
10539     }
10540
10541   return false;
10542 }
10543
10544 /* In the name of slightly smaller debug output, and to cater to
10545    general assembler lossage, recognize various UNSPEC sequences
10546    and turn them back into a direct symbol reference.  */
10547 static rtx
10548 sh_delegitimize_address (rtx orig_x)
10549 {
10550   rtx x, y;
10551
10552   orig_x = delegitimize_mem_from_attrs (orig_x);
10553
10554   x = orig_x;
10555   if (MEM_P (x))
10556     x = XEXP (x, 0);
10557   if (GET_CODE (x) == CONST)
10558     {
10559       y = XEXP (x, 0);
10560       if (GET_CODE (y) == UNSPEC)
10561         {
10562           if (XINT (y, 1) == UNSPEC_GOT
10563               || XINT (y, 1) == UNSPEC_GOTOFF
10564               || XINT (y, 1) == UNSPEC_SYMOFF)
10565             return XVECEXP (y, 0, 0);
10566           else if (XINT (y, 1) == UNSPEC_PCREL_SYMOFF)
10567             {
10568               if (GET_CODE (XVECEXP (y, 0, 0)) == CONST)
10569                 {
10570                   rtx symplt = XEXP (XVECEXP (y, 0, 0), 0);
10571
10572                   if (GET_CODE (symplt) == UNSPEC
10573                       && XINT (symplt, 1) == UNSPEC_PLT)
10574                     return XVECEXP (symplt, 0, 0);
10575                 }
10576             }
10577           else if (TARGET_SHMEDIA
10578                    && (XINT (y, 1) == UNSPEC_EXTRACT_S16
10579                        || XINT (y, 1) == UNSPEC_EXTRACT_U16))
10580             {
10581               rtx offset = XVECEXP (y, 0, 1);
10582
10583               x = gen_rtx_PLUS (Pmode, XVECEXP (y, 0, 0), offset);
10584               if (MEM_P (orig_x))
10585                 x = replace_equiv_address_nv (orig_x, x);
10586               return x;
10587             }
10588         }
10589     }
10590
10591   return orig_x;
10592 }
10593
10594 /* Mark the use of a constant in the literal table. If the constant
10595    has multiple labels, make it unique.  */
10596 static rtx
10597 mark_constant_pool_use (rtx x)
10598 {
10599   rtx insn, lab, pattern;
10600
10601   if (x == NULL_RTX)
10602     return x;
10603
10604   switch (GET_CODE (x))
10605     {
10606     case LABEL_REF:
10607       x = XEXP (x, 0);
10608     case CODE_LABEL:
10609       break;
10610     default:
10611       return x;
10612     }
10613
10614   /* Get the first label in the list of labels for the same constant
10615      and delete another labels in the list.  */
10616   lab = x;
10617   for (insn = PREV_INSN (x); insn; insn = PREV_INSN (insn))
10618     {
10619       if (!LABEL_P (insn)
10620           || LABEL_REFS (insn) != NEXT_INSN (insn))
10621         break;
10622       lab = insn;
10623     }
10624
10625   for (insn = LABEL_REFS (lab); insn; insn = LABEL_REFS (insn))
10626     INSN_DELETED_P (insn) = 1;
10627
10628   /* Mark constants in a window.  */
10629   for (insn = NEXT_INSN (x); insn; insn = NEXT_INSN (insn))
10630     {
10631       if (!NONJUMP_INSN_P (insn))
10632         continue;
10633
10634       pattern = PATTERN (insn);
10635       if (GET_CODE (pattern) != UNSPEC_VOLATILE)
10636         continue;
10637
10638       switch (XINT (pattern, 1))
10639         {
10640         case UNSPECV_CONST2:
10641         case UNSPECV_CONST4:
10642         case UNSPECV_CONST8:
10643           XVECEXP (pattern, 0, 1) = const1_rtx;
10644           break;
10645         case UNSPECV_WINDOW_END:
10646           if (XVECEXP (pattern, 0, 0) == x)
10647             return lab;
10648           break;
10649         case UNSPECV_CONST_END:
10650           return lab;
10651         default:
10652           break;
10653         }
10654     }
10655
10656   return lab;
10657 }
10658 \f
10659 /* Return true if it's possible to redirect BRANCH1 to the destination
10660    of an unconditional jump BRANCH2.  We only want to do this if the
10661    resulting branch will have a short displacement.  */
10662 bool
10663 sh_can_redirect_branch (rtx branch1, rtx branch2)
10664 {
10665   if (flag_expensive_optimizations && simplejump_p (branch2))
10666     {
10667       rtx dest = XEXP (SET_SRC (single_set (branch2)), 0);
10668       rtx insn;
10669       int distance;
10670
10671       for (distance = 0, insn = NEXT_INSN (branch1);
10672            insn && distance < 256;
10673            insn = PREV_INSN (insn))
10674         {
10675           if (insn == dest)
10676             return true;
10677           else
10678             distance += get_attr_length (insn);
10679         }
10680       for (distance = 0, insn = NEXT_INSN (branch1);
10681            insn && distance < 256;
10682            insn = NEXT_INSN (insn))
10683         {
10684           if (insn == dest)
10685             return true;
10686           else
10687             distance += get_attr_length (insn);
10688         }
10689     }
10690   return false;
10691 }
10692
10693 /* Return nonzero if register old_reg can be renamed to register new_reg.  */
10694 bool
10695 sh_hard_regno_rename_ok (unsigned int old_reg ATTRIBUTE_UNUSED,
10696                          unsigned int new_reg)
10697 {
10698   /* Interrupt functions can only use registers that have already been
10699      saved by the prologue, even if they would normally be
10700      call-clobbered.  */
10701   if (sh_cfun_interrupt_handler_p () && !df_regs_ever_live_p (new_reg))
10702     return false;
10703
10704   return true;
10705 }
10706
10707 /* Function to update the integer COST
10708    based on the relationship between INSN that is dependent on
10709    DEP_INSN through the dependence LINK.  The default is to make no
10710    adjustment to COST.  This can be used for example to specify to
10711    the scheduler that an output- or anti-dependence does not incur
10712    the same cost as a data-dependence.  The return value should be
10713    the new value for COST.  */
10714 static int
10715 sh_adjust_cost (rtx insn, rtx link ATTRIBUTE_UNUSED, rtx dep_insn, int cost)
10716 {
10717   rtx reg, use_pat;
10718
10719   if (TARGET_SHMEDIA)
10720     {
10721       /* On SHmedia, if the dependence is an anti-dependence or
10722          output-dependence, there is no cost.  */
10723       if (REG_NOTE_KIND (link) != 0)
10724         {
10725           /* However, dependencies between target register loads and
10726              uses of the register in a subsequent block that are separated
10727              by a conditional branch are not modelled - we have to do with
10728              the anti-dependency between the target register load and the
10729              conditional branch that ends the current block.  */
10730           if (REG_NOTE_KIND (link) == REG_DEP_ANTI
10731               && GET_CODE (PATTERN (dep_insn)) == SET
10732               && (get_attr_type (dep_insn) == TYPE_PT_MEDIA
10733                   || get_attr_type (dep_insn) == TYPE_PTABS_MEDIA)
10734               && get_attr_type (insn) == TYPE_CBRANCH_MEDIA)
10735             {
10736               int orig_cost = cost;
10737               rtx note = find_reg_note (insn, REG_BR_PROB, 0);
10738               rtx target = ((! note
10739                              || INTVAL (XEXP (note, 0)) * 2 < REG_BR_PROB_BASE)
10740                             ? insn : JUMP_LABEL (insn));
10741               /* On the likely path, the branch costs 1, on the unlikely path,
10742                  it costs 3.  */
10743               cost--;
10744               do
10745                 target = next_active_insn (target);
10746               while (target && ! flow_dependent_p (target, dep_insn)
10747                      && --cost > 0);
10748               /* If two branches are executed in immediate succession, with the
10749                  first branch properly predicted, this causes a stall at the
10750                  second branch, hence we won't need the target for the
10751                  second branch for two cycles after the launch of the first
10752                  branch.  */
10753               if (cost > orig_cost - 2)
10754                 cost = orig_cost - 2;
10755             }
10756           else
10757             cost = 0;
10758         }
10759
10760       else if (get_attr_is_mac_media (insn)
10761                && get_attr_is_mac_media (dep_insn))
10762         cost = 1;
10763
10764       else if (! reload_completed
10765                && GET_CODE (PATTERN (insn)) == SET
10766                && GET_CODE (SET_SRC (PATTERN (insn))) == FLOAT
10767                && GET_CODE (PATTERN (dep_insn)) == SET
10768                && fp_arith_reg_operand (SET_SRC (PATTERN (dep_insn)), VOIDmode)
10769                && cost < 4)
10770         cost = 4;
10771       /* Schedule the ptabs for a casesi_jump_media in preference to stuff
10772          that is needed at the target.  */
10773       else if (get_attr_type (insn) == TYPE_JUMP_MEDIA
10774                && ! flow_dependent_p (insn, dep_insn))
10775         cost--;
10776     }
10777   else if (REG_NOTE_KIND (link) == 0)
10778     {
10779       enum attr_type type;
10780       rtx dep_set;
10781
10782       if (recog_memoized (insn) < 0
10783           || recog_memoized (dep_insn) < 0)
10784         return cost;
10785
10786       dep_set = single_set (dep_insn);
10787
10788       /* The latency that we specify in the scheduling description refers
10789          to the actual output, not to an auto-increment register; for that,
10790          the latency is one.  */
10791       if (dep_set && MEM_P (SET_SRC (dep_set)) && cost > 1)
10792         {
10793           rtx set = single_set (insn);
10794
10795           if (set
10796               && !reg_mentioned_p (SET_DEST (dep_set), SET_SRC (set))
10797               && (!MEM_P (SET_DEST (set))
10798                   || !reg_mentioned_p (SET_DEST (dep_set),
10799                                        XEXP (SET_DEST (set), 0))))
10800             cost = 1;
10801         }
10802       /* The only input for a call that is timing-critical is the
10803          function's address.  */
10804       if (CALL_P (insn))
10805         {
10806           rtx call = get_call_rtx_from (insn);
10807           if (call
10808                   /* sibcalli_thunk uses a symbol_ref in an unspec.  */
10809               && (GET_CODE (XEXP (XEXP (call, 0), 0)) == UNSPEC
10810                   || ! reg_set_p (XEXP (XEXP (call, 0), 0), dep_insn)))
10811             cost -= TARGET_SH4_300 ? 3 : 6;
10812         }
10813       /* Likewise, the most timing critical input for an sfuncs call
10814          is the function address.  However, sfuncs typically start
10815          using their arguments pretty quickly.
10816          Assume a four cycle delay for SH4 before they are needed.
10817          Cached ST40-300 calls are quicker, so assume only a one
10818          cycle delay there.
10819          ??? Maybe we should encode the delays till input registers
10820          are needed by sfuncs into the sfunc call insn.  */
10821       /* All sfunc calls are parallels with at least four components.
10822          Exploit this to avoid unnecessary calls to sfunc_uses_reg.  */
10823       else if (GET_CODE (PATTERN (insn)) == PARALLEL
10824                && XVECLEN (PATTERN (insn), 0) >= 4
10825                && (reg = sfunc_uses_reg (insn)))
10826         {
10827           if (! reg_set_p (reg, dep_insn))
10828             cost -= TARGET_SH4_300 ? 1 : 4;
10829         }
10830       if (TARGET_HARD_SH4 && !TARGET_SH4_300)
10831         {
10832           enum attr_type dep_type = get_attr_type (dep_insn);
10833
10834           if (dep_type == TYPE_FLOAD || dep_type == TYPE_PCFLOAD)
10835             cost--;
10836           else if ((dep_type == TYPE_LOAD_SI || dep_type == TYPE_PCLOAD_SI)
10837                    && (type = get_attr_type (insn)) != TYPE_CALL
10838                    && type != TYPE_SFUNC)
10839             cost--;
10840           /* When the preceding instruction loads the shift amount of
10841              the following SHAD/SHLD, the latency of the load is increased
10842              by 1 cycle.  */
10843           if (get_attr_type (insn) == TYPE_DYN_SHIFT
10844               && get_attr_any_int_load (dep_insn) == ANY_INT_LOAD_YES
10845               && reg_overlap_mentioned_p (SET_DEST (dep_set),
10846                                           XEXP (SET_SRC (single_set (insn)),
10847                                                 1)))
10848             cost++;
10849           /* When an LS group instruction with a latency of less than
10850              3 cycles is followed by a double-precision floating-point
10851              instruction, FIPR, or FTRV, the latency of the first
10852              instruction is increased to 3 cycles.  */
10853           else if (cost < 3
10854                    && get_attr_insn_class (dep_insn) == INSN_CLASS_LS_GROUP
10855                    && get_attr_dfp_comp (insn) == DFP_COMP_YES)
10856             cost = 3;
10857           /* The lsw register of a double-precision computation is ready one
10858              cycle earlier.  */
10859           else if (reload_completed
10860                    && get_attr_dfp_comp (dep_insn) == DFP_COMP_YES
10861                    && (use_pat = single_set (insn))
10862                    && ! regno_use_in (REGNO (SET_DEST (single_set (dep_insn))),
10863                                       SET_SRC (use_pat)))
10864             cost -= 1;
10865
10866           if (get_attr_any_fp_comp (dep_insn) == ANY_FP_COMP_YES
10867               && get_attr_late_fp_use (insn) == LATE_FP_USE_YES)
10868             cost -= 1;
10869         }
10870       else if (TARGET_SH4_300)
10871         {
10872           /* Stores need their input register two cycles later.  */
10873           if (dep_set && cost >= 1
10874               && ((type = get_attr_type (insn)) == TYPE_STORE
10875                   || type == TYPE_PSTORE
10876                   || type == TYPE_FSTORE || type == TYPE_MAC_MEM))
10877             {
10878               rtx set = single_set (insn);
10879
10880               if (!reg_mentioned_p (SET_SRC (set), XEXP (SET_DEST (set), 0))
10881                   && rtx_equal_p (SET_SRC (set), SET_DEST (dep_set)))
10882                 {
10883                   cost -= 2;
10884                   /* But don't reduce the cost below 1 if the address depends
10885                      on a side effect of dep_insn.  */
10886                   if (cost < 1
10887                       && modified_in_p (XEXP (SET_DEST (set), 0), dep_insn))
10888                     cost = 1;
10889                 }
10890             }
10891         }
10892     }
10893   /* An anti-dependence penalty of two applies if the first insn is a double
10894      precision fadd / fsub / fmul.  */
10895   else if (!TARGET_SH4_300
10896            && REG_NOTE_KIND (link) == REG_DEP_ANTI
10897            && recog_memoized (dep_insn) >= 0
10898            && (get_attr_type (dep_insn) == TYPE_DFP_ARITH
10899                || get_attr_type (dep_insn) == TYPE_DFP_MUL)
10900            /* A lot of alleged anti-flow dependences are fake,
10901               so check this one is real.  */
10902            && flow_dependent_p (dep_insn, insn))
10903     cost = 2;
10904
10905   return cost;
10906 }
10907
10908 /* Check if INSN is flow-dependent on DEP_INSN.  Can also be used to check
10909    if DEP_INSN is anti-flow dependent on INSN.  */
10910 static bool
10911 flow_dependent_p (rtx insn, rtx dep_insn)
10912 {
10913   rtx tmp = PATTERN (insn);
10914
10915   note_stores (PATTERN (dep_insn), flow_dependent_p_1, &tmp);
10916   return tmp == NULL_RTX;
10917 }
10918
10919 /* A helper function for flow_dependent_p called through note_stores.  */
10920 static void
10921 flow_dependent_p_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
10922 {
10923   rtx * pinsn = (rtx *) data;
10924
10925   if (*pinsn && reg_referenced_p (x, *pinsn))
10926     *pinsn = NULL_RTX;
10927 }
10928
10929 /* For use by sh_allocate_initial_value.  Note that sh.md contains some
10930    'special function' patterns (type sfunc) that clobber pr, but that
10931    do not look like function calls to leaf_function_p.  Hence we must
10932    do this extra check.  */
10933 static int
10934 sh_pr_n_sets (void)
10935 {
10936   return DF_REG_DEF_COUNT (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
10937 }
10938
10939 /* Return where to allocate pseudo for a given hard register initial
10940    value.  */
10941 static rtx
10942 sh_allocate_initial_value (rtx hard_reg)
10943 {
10944   rtx x;
10945
10946   if (REGNO (hard_reg) == (TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG))
10947     {
10948       if (crtl->is_leaf
10949           && ! sh_pr_n_sets ()
10950           && ! (TARGET_SHCOMPACT
10951                 && ((crtl->args.info.call_cookie
10952                      & ~ CALL_COOKIE_RET_TRAMP (1))
10953                     || crtl->saves_all_registers)))
10954         x = hard_reg;
10955       else
10956         x = gen_frame_mem (Pmode, return_address_pointer_rtx);
10957     }
10958   else
10959     x = NULL_RTX;
10960
10961   return x;
10962 }
10963
10964 /* This function returns "2" to indicate dual issue for the SH4
10965    processor.  To be used by the DFA pipeline description.  */
10966 static int
10967 sh_issue_rate (void)
10968 {
10969   if (TARGET_SUPERSCALAR)
10970     return 2;
10971   else
10972     return 1;
10973 }
10974
10975 /* Functions for ready queue reordering for sched1.  */
10976
10977 /* Get weight for mode for a set x.  */
10978 static short
10979 find_set_regmode_weight (rtx x, enum machine_mode mode)
10980 {
10981   if (GET_CODE (x) == CLOBBER && register_operand (SET_DEST (x), mode))
10982     return 1;
10983   if (GET_CODE (x) == SET && register_operand (SET_DEST (x), mode))
10984     {
10985       if (REG_P (SET_DEST (x)))
10986         {
10987           if (!reg_mentioned_p (SET_DEST (x), SET_SRC (x)))
10988             return 1;
10989           else
10990             return 0;
10991         }
10992       return 1;
10993     }
10994   return 0;
10995 }
10996
10997 /* Get regmode weight for insn.  */
10998 static short
10999 find_insn_regmode_weight (rtx insn, enum machine_mode mode)
11000 {
11001   short reg_weight = 0;
11002   rtx x;
11003
11004   /* Increment weight for each register born here.  */
11005   x = PATTERN (insn);
11006   reg_weight += find_set_regmode_weight (x, mode);
11007   if (GET_CODE (x) == PARALLEL)
11008     {
11009       int j;
11010       for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
11011         {
11012           x = XVECEXP (PATTERN (insn), 0, j);
11013           reg_weight += find_set_regmode_weight (x, mode);
11014         }
11015     }
11016   /* Decrement weight for each register that dies here.  */
11017   for (x = REG_NOTES (insn); x; x = XEXP (x, 1))
11018     {
11019       if (REG_NOTE_KIND (x) == REG_DEAD || REG_NOTE_KIND (x) == REG_UNUSED)
11020         {
11021           rtx note = XEXP (x, 0);
11022           if (REG_P (note) && GET_MODE (note) == mode)
11023             reg_weight--;
11024         }
11025     }
11026   return reg_weight;
11027 }
11028
11029 /* Calculate regmode weights for all insns of a basic block.  */
11030 static void
11031 find_regmode_weight (basic_block b, enum machine_mode mode)
11032 {
11033   rtx insn, next_tail, head, tail;
11034
11035   get_ebb_head_tail (b, b, &head, &tail);
11036   next_tail = NEXT_INSN (tail);
11037
11038   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
11039     {
11040       /* Handle register life information.  */
11041       if (!INSN_P (insn))
11042         continue;
11043
11044       if (mode == SFmode)
11045         INSN_REGMODE_WEIGHT (insn, mode) =
11046           find_insn_regmode_weight (insn, mode)
11047           + 2 * find_insn_regmode_weight (insn, DFmode);
11048       else if (mode == SImode)
11049         INSN_REGMODE_WEIGHT (insn, mode) =
11050           find_insn_regmode_weight (insn, mode)
11051           + 2 * find_insn_regmode_weight (insn, DImode);
11052     }
11053 }
11054
11055 /* Comparison function for ready queue sorting.  */
11056 static int
11057 rank_for_reorder (const void *x, const void *y)
11058 {
11059   rtx tmp = *(const rtx *) y;
11060   rtx tmp2 = *(const rtx *) x;
11061
11062   /* The insn in a schedule group should be issued the first.  */
11063   if (SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
11064     return SCHED_GROUP_P (tmp2) ? 1 : -1;
11065
11066   /* If insns are equally good, sort by INSN_LUID (original insn order), This
11067      minimizes instruction movement, thus minimizing sched's effect on
11068      register pressure.  */
11069   return INSN_LUID (tmp) - INSN_LUID (tmp2);
11070 }
11071
11072 /* Resort the array A in which only element at index N may be out of order.  */
11073 static void
11074 swap_reorder (rtx *a, int n)
11075 {
11076   rtx insn = a[n - 1];
11077   int i = n - 2;
11078
11079   while (i >= 0 && rank_for_reorder (a + i, &insn) >= 0)
11080     {
11081       a[i + 1] = a[i];
11082       i -= 1;
11083     }
11084   a[i + 1] = insn;
11085 }
11086
11087 /* Sort the ready list by ascending priority.  */
11088 static void
11089 ready_reorder (rtx *ready, int nready)
11090 {
11091   if (nready == 2)
11092     swap_reorder (ready, nready);
11093   else if (nready > 2)
11094      qsort (ready, nready, sizeof (rtx), rank_for_reorder);
11095 }
11096
11097 /* Count life regions of r0 for a block.  */
11098 static int
11099 find_r0_life_regions (basic_block b)
11100 {
11101   rtx end, insn;
11102   rtx pset;
11103   rtx r0_reg;
11104   int live;
11105   int set;
11106   int death = 0;
11107
11108   if (REGNO_REG_SET_P (df_get_live_in (b), R0_REG))
11109     {
11110       set = 1;
11111       live = 1;
11112     }
11113   else
11114     {
11115       set = 0;
11116       live = 0;
11117     }
11118
11119   insn = BB_HEAD (b);
11120   end = BB_END (b);
11121   r0_reg = gen_rtx_REG (SImode, R0_REG);
11122   while (1)
11123     {
11124       if (INSN_P (insn))
11125         {
11126           if (find_regno_note (insn, REG_DEAD, R0_REG))
11127             {
11128               death++;
11129               live = 0;
11130             }
11131           if (!live
11132               && (pset = single_set (insn))
11133               && reg_overlap_mentioned_p (r0_reg, SET_DEST (pset))
11134               && !find_regno_note (insn, REG_UNUSED, R0_REG))
11135             {
11136               set++;
11137               live = 1;
11138             }
11139         }
11140       if (insn == end)
11141         break;
11142       insn = NEXT_INSN (insn);
11143     }
11144   return set - death;
11145 }
11146
11147 /* Calculate regmode weights for all insns of all basic block.  */
11148 static void
11149 sh_md_init_global (FILE *dump ATTRIBUTE_UNUSED,
11150                    int verbose ATTRIBUTE_UNUSED,
11151                    int old_max_uid)
11152 {
11153   basic_block b;
11154
11155   regmode_weight[0] = (short *) xcalloc (old_max_uid, sizeof (short));
11156   regmode_weight[1] = (short *) xcalloc (old_max_uid, sizeof (short));
11157   r0_life_regions = 0;
11158
11159   FOR_EACH_BB_REVERSE (b)
11160   {
11161     find_regmode_weight (b, SImode);
11162     find_regmode_weight (b, SFmode);
11163     if (!reload_completed)
11164       r0_life_regions += find_r0_life_regions (b);
11165   }
11166
11167   CURR_REGMODE_PRESSURE (SImode) = 0;
11168   CURR_REGMODE_PRESSURE (SFmode) = 0;
11169 }
11170
11171 /* Cleanup.  */
11172 static void
11173 sh_md_finish_global (FILE *dump ATTRIBUTE_UNUSED,
11174                      int verbose ATTRIBUTE_UNUSED)
11175 {
11176   if (regmode_weight[0])
11177     {
11178       free (regmode_weight[0]);
11179       regmode_weight[0] = NULL;
11180     }
11181   if (regmode_weight[1])
11182     {
11183       free (regmode_weight[1]);
11184       regmode_weight[1] = NULL;
11185     }
11186 }
11187
11188 /* The scalar modes supported differs from the default version in TImode
11189    for 32-bit SHMEDIA.  */
11190 static bool
11191 sh_scalar_mode_supported_p (enum machine_mode mode)
11192 {
11193   if (TARGET_SHMEDIA32 && mode == TImode)
11194     return false;
11195
11196   return default_scalar_mode_supported_p (mode);
11197 }
11198
11199 /* Cache the can_issue_more so that we can return it from reorder2. Also,
11200    keep count of register pressures on SImode and SFmode. */
11201 static int
11202 sh_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
11203                    int sched_verbose ATTRIBUTE_UNUSED,
11204                    rtx insn,
11205                    int can_issue_more)
11206 {
11207   if (GET_CODE (PATTERN (insn)) != USE
11208       && GET_CODE (PATTERN (insn)) != CLOBBER)
11209     cached_can_issue_more = can_issue_more - 1;
11210   else
11211     cached_can_issue_more = can_issue_more;
11212
11213   if (reload_completed)
11214     return cached_can_issue_more;
11215
11216   CURR_REGMODE_PRESSURE (SImode) += INSN_REGMODE_WEIGHT (insn, SImode);
11217   CURR_REGMODE_PRESSURE (SFmode) += INSN_REGMODE_WEIGHT (insn, SFmode);
11218
11219   return cached_can_issue_more;
11220 }
11221
11222 static void
11223 sh_md_init (FILE *dump ATTRIBUTE_UNUSED,
11224             int verbose ATTRIBUTE_UNUSED,
11225             int veclen ATTRIBUTE_UNUSED)
11226 {
11227   CURR_REGMODE_PRESSURE (SImode) = 0;
11228   CURR_REGMODE_PRESSURE (SFmode) = 0;
11229 }
11230
11231 /* Some magic numbers.  */
11232 /* Pressure on register r0 can lead to spill failures. so avoid sched1 for
11233    functions that already have high pressure on r0. */
11234 #define R0_MAX_LIFE_REGIONS 2
11235 /* Register Pressure thresholds for SImode and SFmode registers.  */
11236 #define SIMODE_MAX_WEIGHT 5
11237 #define SFMODE_MAX_WEIGHT 10
11238
11239 /* Return true if the pressure is high for MODE.  */
11240 static bool
11241 high_pressure (enum machine_mode mode)
11242 {
11243   /* Pressure on register r0 can lead to spill failures. so avoid sched1 for
11244      functions that already have high pressure on r0. */
11245    if (r0_life_regions >= R0_MAX_LIFE_REGIONS)
11246      return true;
11247
11248   if (mode == SFmode)
11249     return (CURR_REGMODE_PRESSURE (SFmode) > SFMODE_MAX_WEIGHT);
11250   else
11251     return (CURR_REGMODE_PRESSURE (SImode) > SIMODE_MAX_WEIGHT);
11252 }
11253
11254 /* Reorder ready queue if register pressure is high.  */
11255 static int
11256 sh_reorder (FILE *dump ATTRIBUTE_UNUSED,
11257             int sched_verbose ATTRIBUTE_UNUSED,
11258             rtx *ready,
11259             int *n_readyp,
11260             int clock_var ATTRIBUTE_UNUSED)
11261 {
11262   if (reload_completed)
11263     return sh_issue_rate ();
11264
11265   if (high_pressure (SFmode) || high_pressure (SImode))
11266     {
11267       ready_reorder (ready, *n_readyp);
11268     }
11269
11270   return sh_issue_rate ();
11271 }
11272
11273 /* Skip cycles if the current register pressure is high.  */
11274 static int
11275 sh_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
11276              int sched_verbose ATTRIBUTE_UNUSED,
11277              rtx *ready ATTRIBUTE_UNUSED,
11278              int *n_readyp ATTRIBUTE_UNUSED,
11279              int clock_var ATTRIBUTE_UNUSED)
11280 {
11281   if (reload_completed)
11282     return cached_can_issue_more;
11283
11284   if (high_pressure(SFmode) || high_pressure (SImode))
11285     skip_cycles = 1;
11286
11287   return cached_can_issue_more;
11288 }
11289
11290 /* Skip cycles without sorting the ready queue. This will move insn from
11291    Q->R. If this is the last cycle we are skipping; allow sorting of ready
11292    queue by sh_reorder.  */
11293
11294 /* Generally, skipping these many cycles are sufficient for all insns to move
11295    from Q -> R.  */
11296 #define MAX_SKIPS 8
11297
11298 static int
11299 sh_dfa_new_cycle (FILE *sched_dump ATTRIBUTE_UNUSED,
11300                   int sched_verbose ATTRIBUTE_UNUSED,
11301                   rtx insn ATTRIBUTE_UNUSED,
11302                   int last_clock_var,
11303                   int clock_var,
11304                   int *sort_p)
11305 {
11306   if (reload_completed)
11307     return 0;
11308
11309   if (skip_cycles)
11310     {
11311       if ((clock_var - last_clock_var) < MAX_SKIPS)
11312         {
11313           *sort_p = 0;
11314           return 1;
11315         }
11316       /* If this is the last cycle we are skipping, allow reordering of R.  */
11317       if ((clock_var - last_clock_var) == MAX_SKIPS)
11318         {
11319           *sort_p = 1;
11320           return 1;
11321         }
11322     }
11323
11324   skip_cycles = 0;
11325
11326   return 0;
11327 }
11328
11329 /* SHmedia requires registers for branches, so we can't generate new
11330    branches past reload.  */
11331 static bool
11332 sh_cannot_modify_jumps_p (void)
11333 {
11334   return (TARGET_SHMEDIA && (reload_in_progress || reload_completed));
11335 }
11336
11337 static reg_class_t
11338 sh_target_reg_class (void)
11339 {
11340   return TARGET_SHMEDIA ? TARGET_REGS : NO_REGS;
11341 }
11342
11343 static bool
11344 sh_optimize_target_register_callee_saved (bool after_prologue_epilogue_gen)
11345 {
11346   if (! shmedia_space_reserved_for_target_registers)
11347     return 0;
11348   if (after_prologue_epilogue_gen && ! TARGET_SAVE_ALL_TARGET_REGS)
11349     return 0;
11350
11351   HARD_REG_SET dummy;
11352   if (calc_live_regs (&dummy) >= 6 * 8)
11353     return 1;
11354   return 0;
11355 }
11356
11357 static bool
11358 sh_ms_bitfield_layout_p (const_tree record_type ATTRIBUTE_UNUSED)
11359 {
11360   return (TARGET_SH5 || TARGET_HITACHI || sh_attr_renesas_p (record_type));
11361 }
11362 \f
11363 /*
11364    On the SH1..SH4, the trampoline looks like
11365    2 0002 D202                  mov.l   l2,r2
11366    1 0000 D301                  mov.l   l1,r3
11367    3 0004 422B                  jmp     @r2
11368    4 0006 0009                  nop
11369    5 0008 00000000      l1:     .long   area
11370    6 000c 00000000      l2:     .long   function
11371
11372    SH5 (compact) uses r1 instead of r3 for the static chain.  */
11373
11374
11375 /* Emit RTL insns to initialize the variable parts of a trampoline.
11376    FNADDR is an RTX for the address of the function's pure code.
11377    CXT is an RTX for the static chain value for the function.  */
11378 static void
11379 sh_trampoline_init (rtx tramp_mem, tree fndecl, rtx cxt)
11380 {
11381   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
11382   rtx tramp = force_reg (Pmode, XEXP (tramp_mem, 0));
11383
11384   if (TARGET_SHMEDIA64)
11385     {
11386       rtx tramp_templ;
11387       int fixed_len;
11388
11389       rtx movi1 = GEN_INT (0xcc000010);
11390       rtx shori1 = GEN_INT (0xc8000010);
11391       rtx src, dst;
11392
11393       /* The following trampoline works within a +- 128 KB range for cxt:
11394          ptb/u cxt,tr1; movi fnaddr >> 48,r0; shori fnaddr >> 32,r0;
11395          shori fnaddr >> 16,r0; shori fnaddr,r0; ptabs/l r0,tr0
11396          gettr tr1,r1; blink tr0,r63  */
11397       /* Address rounding makes it hard to compute the exact bounds of the
11398          offset for this trampoline, but we have a rather generous offset
11399          range, so frame_offset should do fine as an upper bound.  */
11400       if (cxt == virtual_stack_vars_rtx && frame_offset < 0x20000)
11401         {
11402           /* ??? could optimize this trampoline initialization
11403              by writing DImode words with two insns each.  */
11404           rtx mask = force_reg (DImode, GEN_INT (0x3fffc00));
11405           rtx insn = gen_rtx_MINUS (DImode, cxt, tramp);
11406           insn = gen_rtx_ASHIFT (DImode, insn, GEN_INT (10-2));
11407           insn = gen_rtx_AND (DImode, insn, mask);
11408           /* Or in ptb/u .,tr1 pattern */
11409           insn = gen_rtx_IOR (DImode, insn, gen_int_mode (0xec000010, SImode));
11410           insn = force_operand (insn, NULL_RTX);
11411           insn = gen_lowpart (SImode, insn);
11412           emit_move_insn (change_address (tramp_mem, SImode, NULL_RTX), insn);
11413           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (38));
11414           insn = gen_rtx_AND (DImode, insn, mask);
11415           insn = force_operand (gen_rtx_IOR (DImode, movi1, insn), NULL_RTX);
11416           insn = gen_lowpart (SImode, insn);
11417           emit_move_insn (adjust_address (tramp_mem, SImode, 4), insn);
11418           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (22));
11419           insn = gen_rtx_AND (DImode, insn, mask);
11420           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
11421           insn = gen_lowpart (SImode, insn);
11422           emit_move_insn (adjust_address (tramp_mem, SImode, 8), insn);
11423           insn = gen_rtx_LSHIFTRT (DImode, fnaddr, GEN_INT (6));
11424           insn = gen_rtx_AND (DImode, insn, mask);
11425           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
11426           insn = gen_lowpart (SImode, insn);
11427           emit_move_insn (adjust_address (tramp_mem, SImode, 12), insn);
11428           insn = gen_rtx_ASHIFT (DImode, fnaddr, GEN_INT (10));
11429           insn = gen_rtx_AND (DImode, insn, mask);
11430           insn = force_operand (gen_rtx_IOR (DImode, shori1, insn), NULL_RTX);
11431           insn = gen_lowpart (SImode, insn);
11432           emit_move_insn (adjust_address (tramp_mem, SImode, 16), insn);
11433           emit_move_insn (adjust_address (tramp_mem, SImode, 20),
11434                           GEN_INT (0x6bf10600));
11435           emit_move_insn (adjust_address (tramp_mem, SImode, 24),
11436                           GEN_INT (0x4415fc10));
11437           emit_move_insn (adjust_address (tramp_mem, SImode, 28),
11438                           GEN_INT (0x4401fff0));
11439           emit_insn (gen_ic_invalidate_line (tramp));
11440           return;
11441         }
11442       tramp_templ = gen_rtx_SYMBOL_REF (Pmode,"__GCC_nested_trampoline");
11443       fixed_len = TRAMPOLINE_SIZE - 2 * GET_MODE_SIZE (Pmode);
11444
11445       tramp_templ = gen_datalabel_ref (tramp_templ);
11446       dst = tramp_mem;
11447       src = gen_const_mem (BLKmode, tramp_templ);
11448       set_mem_align (dst, 256);
11449       set_mem_align (src, 64);
11450       emit_block_move (dst, src, GEN_INT (fixed_len), BLOCK_OP_NORMAL);
11451
11452       emit_move_insn (adjust_address (tramp_mem, Pmode, fixed_len), fnaddr);
11453       emit_move_insn (adjust_address (tramp_mem, Pmode,
11454                                       fixed_len + GET_MODE_SIZE (Pmode)),
11455                       cxt);
11456       emit_insn (gen_ic_invalidate_line (tramp));
11457       return;
11458     }
11459   else if (TARGET_SHMEDIA)
11460     {
11461       /* movi fnaddr >> 16,r1; shori fnaddr,r1; ptabs/l r1,tr0
11462          movi cxt >> 16,r1; shori cxt,r1; blink tr0,r63  */
11463       rtx quad0 = gen_reg_rtx (DImode), cxtload = gen_reg_rtx (DImode);
11464       rtx quad1 = gen_reg_rtx (DImode), quad2 = gen_reg_rtx (DImode);
11465       /* movi 0,r1: 0xcc000010 shori 0,r1: c8000010  concatenated,
11466          rotated 10 right, and higher 16 bit of every 32 selected.  */
11467       rtx movishori
11468         = force_reg (V2HImode, (simplify_gen_subreg
11469                                 (V2HImode, GEN_INT (0x4330432), SImode, 0)));
11470       rtx ptabs = force_reg (DImode, GEN_INT (0x6bf10600));
11471       rtx blink = force_reg (DImode, GEN_INT (0x4401fff0));
11472
11473       fnaddr = force_reg (SImode, fnaddr);
11474       cxt = force_reg (SImode, cxt);
11475       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, quad0, 0),
11476                                  gen_rtx_SUBREG (V2HImode, fnaddr, 0),
11477                                  movishori));
11478       emit_insn (gen_rotrdi3_mextr (quad0, quad0,
11479                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
11480       emit_insn (gen_ashldi3_media (quad0, quad0, const2_rtx));
11481       emit_move_insn (change_address (tramp_mem, DImode, NULL_RTX), quad0);
11482       emit_insn (gen_mshflo_w_x (gen_rtx_SUBREG (V4HImode, cxtload, 0),
11483                                  gen_rtx_SUBREG (V2HImode, cxt, 0),
11484                                  movishori));
11485       emit_insn (gen_rotrdi3_mextr (cxtload, cxtload,
11486                                     GEN_INT (TARGET_LITTLE_ENDIAN ? 24 : 56)));
11487       emit_insn (gen_ashldi3_media (cxtload, cxtload, const2_rtx));
11488       if (TARGET_LITTLE_ENDIAN)
11489         {
11490           emit_insn (gen_mshflo_l_di (quad1, ptabs, cxtload));
11491           emit_insn (gen_mextr4 (quad2, cxtload, blink));
11492         }
11493       else
11494         {
11495           emit_insn (gen_mextr4 (quad1, cxtload, ptabs));
11496           emit_insn (gen_mshflo_l_di (quad2, blink, cxtload));
11497         }
11498       emit_move_insn (adjust_address (tramp_mem, DImode, 8), quad1);
11499       emit_move_insn (adjust_address (tramp_mem, DImode, 16), quad2);
11500       emit_insn (gen_ic_invalidate_line (tramp));
11501       return;
11502     }
11503   else if (TARGET_SHCOMPACT)
11504     {
11505       emit_insn (gen_initialize_trampoline (tramp, cxt, fnaddr));
11506       return;
11507     }
11508   emit_move_insn (change_address (tramp_mem, SImode, NULL_RTX),
11509                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0xd301d202 : 0xd202d301,
11510                                 SImode));
11511   emit_move_insn (adjust_address (tramp_mem, SImode, 4),
11512                   gen_int_mode (TARGET_LITTLE_ENDIAN ? 0x0009422b : 0x422b0009,
11513                                 SImode));
11514   emit_move_insn (adjust_address (tramp_mem, SImode, 8), cxt);
11515   emit_move_insn (adjust_address (tramp_mem, SImode, 12), fnaddr);
11516   if (TARGET_HARD_SH4 || TARGET_SH5)
11517     {
11518       if (!TARGET_INLINE_IC_INVALIDATE
11519           || (!(TARGET_SH4A_ARCH || TARGET_SH4_300) && TARGET_USERMODE))
11520         emit_library_call (function_symbol (NULL, "__ic_invalidate",
11521                                             FUNCTION_ORDINARY),
11522                            LCT_NORMAL, VOIDmode, 1, tramp, SImode);
11523       else
11524         emit_insn (gen_ic_invalidate_line (tramp));
11525     }
11526 }
11527
11528 /* On SH5, trampolines are SHmedia code, so add 1 to the address.  */
11529 static rtx
11530 sh_trampoline_adjust_address (rtx tramp)
11531 {
11532   if (TARGET_SHMEDIA)
11533     tramp = expand_simple_binop (Pmode, PLUS, tramp, const1_rtx,
11534                                  gen_reg_rtx (Pmode), 0, OPTAB_LIB_WIDEN);
11535   return tramp;
11536 }
11537
11538 /* FIXME: This is overly conservative.  A SHcompact function that
11539    receives arguments ``by reference'' will have them stored in its
11540    own stack frame, so it must not pass pointers or references to
11541    these arguments to other functions by means of sibling calls.  */
11542 /* If PIC, we cannot make sibling calls to global functions
11543    because the PLT requires r12 to be live.  */
11544 static bool
11545 sh_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
11546 {
11547   return (1
11548           && (! TARGET_SHCOMPACT
11549               || crtl->args.info.stack_regs == 0)
11550           && ! sh_cfun_interrupt_handler_p ()
11551           && (! flag_pic
11552               || (decl && ! TREE_PUBLIC (decl))
11553               || (decl && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT)));
11554 }
11555 \f
11556 /* Machine specific built-in functions.  */
11557
11558 struct builtin_description
11559 {
11560   bool (* const is_enabled) (void);
11561   const enum insn_code icode;
11562   const char *const name;
11563   int signature;
11564   tree fndecl;
11565 };
11566
11567 static bool
11568 shmedia_builtin_p (void)
11569 {
11570   return TARGET_SHMEDIA;
11571 }
11572
11573 /* This function can be used if there are any built-ins that are not for
11574    SHmedia.  It's commented out to avoid the defined-but-unused warning.
11575 static bool
11576 sh1_builtin_p (void)
11577 {
11578   return TARGET_SH1;
11579 }
11580 */
11581
11582 /* describe number and signedness of arguments; arg[0] == result
11583    (1: unsigned, 2: signed, 4: don't care, 8: pointer 0: no argument */
11584 /* 9: 64-bit pointer, 10: 32-bit pointer */
11585 static const char signature_args[][4] =
11586 {
11587 #define SH_BLTIN_V2SI2 0
11588   { 4, 4 },
11589 #define SH_BLTIN_V4HI2 1
11590   { 4, 4 },
11591 #define SH_BLTIN_V2SI3 2
11592   { 4, 4, 4 },
11593 #define SH_BLTIN_V4HI3 3
11594   { 4, 4, 4 },
11595 #define SH_BLTIN_V8QI3 4
11596   { 4, 4, 4 },
11597 #define SH_BLTIN_MAC_HISI 5
11598   { 1, 4, 4, 1 },
11599 #define SH_BLTIN_SH_HI 6
11600   { 4, 4, 1 },
11601 #define SH_BLTIN_SH_SI 7
11602   { 4, 4, 1 },
11603 #define SH_BLTIN_V4HI2V2SI 8
11604   { 4, 4, 4 },
11605 #define SH_BLTIN_V4HI2V8QI 9
11606   { 4, 4, 4 },
11607 #define SH_BLTIN_SISF 10
11608   { 4, 2 },
11609 #define SH_BLTIN_LDUA_L 11
11610   { 2, 10 },
11611 #define SH_BLTIN_LDUA_Q 12
11612   { 1, 10 },
11613 #define SH_BLTIN_STUA_L 13
11614   { 0, 10, 2 },
11615 #define SH_BLTIN_STUA_Q 14
11616   { 0, 10, 1 },
11617 #define SH_BLTIN_LDUA_L64 15
11618   { 2, 9 },
11619 #define SH_BLTIN_LDUA_Q64 16
11620   { 1, 9 },
11621 #define SH_BLTIN_STUA_L64 17
11622   { 0, 9, 2 },
11623 #define SH_BLTIN_STUA_Q64 18
11624   { 0, 9, 1 },
11625 #define SH_BLTIN_NUM_SHARED_SIGNATURES 19
11626 #define SH_BLTIN_2 19
11627 #define SH_BLTIN_SU 19
11628   { 1, 2 },
11629 #define SH_BLTIN_3 20
11630 #define SH_BLTIN_SUS 20
11631   { 2, 2, 1 },
11632 #define SH_BLTIN_PSSV 21
11633   { 0, 8, 2, 2 },
11634 #define SH_BLTIN_XXUU 22
11635 #define SH_BLTIN_UUUU 22
11636   { 1, 1, 1, 1 },
11637 #define SH_BLTIN_PV 23
11638   { 0, 8 },
11639 #define SH_BLTIN_VP 24
11640   { 8, 0 },
11641 };
11642 /* mcmv: operands considered unsigned.  */
11643 /* mmulsum_wq, msad_ubq: result considered unsigned long long.  */
11644 /* mperm: control value considered unsigned int.  */
11645 /* mshalds, mshard, mshards, mshlld, mshlrd: shift count is unsigned int.  */
11646 /* mshards_q: returns signed short.  */
11647 /* nsb: takes long long arg, returns unsigned char.  */
11648 static struct builtin_description bdesc[] =
11649 {
11650   { shmedia_builtin_p,
11651     CODE_FOR_absv2si2,  "__builtin_absv2si2", SH_BLTIN_V2SI2, 0 },
11652   { shmedia_builtin_p,
11653     CODE_FOR_absv4hi2,  "__builtin_absv4hi2", SH_BLTIN_V4HI2, 0 },
11654   { shmedia_builtin_p,
11655     CODE_FOR_addv2si3,  "__builtin_addv2si3", SH_BLTIN_V2SI3, 0 },
11656   { shmedia_builtin_p,
11657     CODE_FOR_addv4hi3,  "__builtin_addv4hi3", SH_BLTIN_V4HI3, 0 },
11658   { shmedia_builtin_p,
11659     CODE_FOR_ssaddv2si3,"__builtin_ssaddv2si3", SH_BLTIN_V2SI3, 0 },
11660   { shmedia_builtin_p,
11661     CODE_FOR_usaddv8qi3,"__builtin_usaddv8qi3", SH_BLTIN_V8QI3, 0 },
11662   { shmedia_builtin_p,
11663     CODE_FOR_ssaddv4hi3,"__builtin_ssaddv4hi3", SH_BLTIN_V4HI3, 0 },
11664   { shmedia_builtin_p,
11665     CODE_FOR_alloco_i,  "__builtin_sh_media_ALLOCO", SH_BLTIN_PV, 0 },
11666   { shmedia_builtin_p,
11667     CODE_FOR_negcmpeqv8qi,"__builtin_sh_media_MCMPEQ_B", SH_BLTIN_V8QI3, 0 },
11668   { shmedia_builtin_p,
11669     CODE_FOR_negcmpeqv2si,"__builtin_sh_media_MCMPEQ_L", SH_BLTIN_V2SI3, 0 },
11670   { shmedia_builtin_p,
11671     CODE_FOR_negcmpeqv4hi,"__builtin_sh_media_MCMPEQ_W", SH_BLTIN_V4HI3, 0 },
11672   { shmedia_builtin_p,
11673     CODE_FOR_negcmpgtuv8qi,"__builtin_sh_media_MCMPGT_UB", SH_BLTIN_V8QI3, 0 },
11674   { shmedia_builtin_p,
11675     CODE_FOR_negcmpgtv2si,"__builtin_sh_media_MCMPGT_L", SH_BLTIN_V2SI3, 0 },
11676   { shmedia_builtin_p,
11677     CODE_FOR_negcmpgtv4hi,"__builtin_sh_media_MCMPGT_W", SH_BLTIN_V4HI3, 0 },
11678   { shmedia_builtin_p,
11679     CODE_FOR_mcmv,      "__builtin_sh_media_MCMV", SH_BLTIN_UUUU, 0 },
11680   { shmedia_builtin_p,
11681     CODE_FOR_mcnvs_lw,  "__builtin_sh_media_MCNVS_LW", SH_BLTIN_3, 0 },
11682   { shmedia_builtin_p,
11683     CODE_FOR_mcnvs_wb,  "__builtin_sh_media_MCNVS_WB", SH_BLTIN_V4HI2V8QI, 0 },
11684   { shmedia_builtin_p,
11685     CODE_FOR_mcnvs_wub, "__builtin_sh_media_MCNVS_WUB", SH_BLTIN_V4HI2V8QI, 0 },
11686   { shmedia_builtin_p,
11687     CODE_FOR_mextr1,    "__builtin_sh_media_MEXTR1", SH_BLTIN_V8QI3, 0 },
11688   { shmedia_builtin_p,
11689     CODE_FOR_mextr2,    "__builtin_sh_media_MEXTR2", SH_BLTIN_V8QI3, 0 },
11690   { shmedia_builtin_p,
11691     CODE_FOR_mextr3,    "__builtin_sh_media_MEXTR3", SH_BLTIN_V8QI3, 0 },
11692   { shmedia_builtin_p,
11693     CODE_FOR_mextr4,    "__builtin_sh_media_MEXTR4", SH_BLTIN_V8QI3, 0 },
11694   { shmedia_builtin_p,
11695     CODE_FOR_mextr5,    "__builtin_sh_media_MEXTR5", SH_BLTIN_V8QI3, 0 },
11696   { shmedia_builtin_p,
11697     CODE_FOR_mextr6,    "__builtin_sh_media_MEXTR6", SH_BLTIN_V8QI3, 0 },
11698   { shmedia_builtin_p,
11699     CODE_FOR_mextr7,    "__builtin_sh_media_MEXTR7", SH_BLTIN_V8QI3, 0 },
11700   { shmedia_builtin_p,
11701     CODE_FOR_mmacfx_wl, "__builtin_sh_media_MMACFX_WL", SH_BLTIN_MAC_HISI, 0 },
11702   { shmedia_builtin_p,
11703     CODE_FOR_mmacnfx_wl,"__builtin_sh_media_MMACNFX_WL", SH_BLTIN_MAC_HISI, 0 },
11704   { shmedia_builtin_p,
11705     CODE_FOR_mulv2si3,  "__builtin_mulv2si3", SH_BLTIN_V2SI3, 0 },
11706   { shmedia_builtin_p,
11707     CODE_FOR_mulv4hi3,  "__builtin_mulv4hi3", SH_BLTIN_V4HI3, 0 },
11708   { shmedia_builtin_p,
11709     CODE_FOR_mmulfx_l,  "__builtin_sh_media_MMULFX_L", SH_BLTIN_V2SI3, 0 },
11710   { shmedia_builtin_p,
11711     CODE_FOR_mmulfx_w,  "__builtin_sh_media_MMULFX_W", SH_BLTIN_V4HI3, 0 },
11712   { shmedia_builtin_p,
11713     CODE_FOR_mmulfxrp_w,"__builtin_sh_media_MMULFXRP_W", SH_BLTIN_V4HI3, 0 },
11714   { shmedia_builtin_p,
11715     CODE_FOR_mmulhi_wl, "__builtin_sh_media_MMULHI_WL", SH_BLTIN_V4HI2V2SI, 0 },
11716   { shmedia_builtin_p,
11717     CODE_FOR_mmullo_wl, "__builtin_sh_media_MMULLO_WL", SH_BLTIN_V4HI2V2SI, 0 },
11718   { shmedia_builtin_p,
11719     CODE_FOR_mmulsum_wq,"__builtin_sh_media_MMULSUM_WQ", SH_BLTIN_XXUU, 0 },
11720   { shmedia_builtin_p,
11721     CODE_FOR_mperm_w,   "__builtin_sh_media_MPERM_W", SH_BLTIN_SH_HI, 0 },
11722   { shmedia_builtin_p,
11723     CODE_FOR_msad_ubq,  "__builtin_sh_media_MSAD_UBQ", SH_BLTIN_XXUU, 0 },
11724   { shmedia_builtin_p,
11725     CODE_FOR_mshalds_l, "__builtin_sh_media_MSHALDS_L", SH_BLTIN_SH_SI, 0 },
11726   { shmedia_builtin_p,
11727     CODE_FOR_mshalds_w, "__builtin_sh_media_MSHALDS_W", SH_BLTIN_SH_HI, 0 },
11728   { shmedia_builtin_p,
11729     CODE_FOR_ashrv2si3, "__builtin_ashrv2si3", SH_BLTIN_SH_SI, 0 },
11730   { shmedia_builtin_p,
11731     CODE_FOR_ashrv4hi3, "__builtin_ashrv4hi3", SH_BLTIN_SH_HI, 0 },
11732   { shmedia_builtin_p,
11733     CODE_FOR_mshards_q, "__builtin_sh_media_MSHARDS_Q", SH_BLTIN_SUS, 0 },
11734   { shmedia_builtin_p,
11735     CODE_FOR_mshfhi_b,  "__builtin_sh_media_MSHFHI_B", SH_BLTIN_V8QI3, 0 },
11736   { shmedia_builtin_p,
11737     CODE_FOR_mshfhi_l,  "__builtin_sh_media_MSHFHI_L", SH_BLTIN_V2SI3, 0 },
11738   { shmedia_builtin_p,
11739     CODE_FOR_mshfhi_w,  "__builtin_sh_media_MSHFHI_W", SH_BLTIN_V4HI3, 0 },
11740   { shmedia_builtin_p,
11741     CODE_FOR_mshflo_b,  "__builtin_sh_media_MSHFLO_B", SH_BLTIN_V8QI3, 0 },
11742   { shmedia_builtin_p,
11743     CODE_FOR_mshflo_l,  "__builtin_sh_media_MSHFLO_L", SH_BLTIN_V2SI3, 0 },
11744   { shmedia_builtin_p,
11745     CODE_FOR_mshflo_w,  "__builtin_sh_media_MSHFLO_W", SH_BLTIN_V4HI3, 0 },
11746   { shmedia_builtin_p,
11747     CODE_FOR_ashlv2si3, "__builtin_ashlv2si3", SH_BLTIN_SH_SI, 0 },
11748   { shmedia_builtin_p,
11749     CODE_FOR_ashlv4hi3, "__builtin_ashlv4hi3", SH_BLTIN_SH_HI, 0 },
11750   { shmedia_builtin_p,
11751     CODE_FOR_lshrv2si3, "__builtin_lshrv2si3", SH_BLTIN_SH_SI, 0 },
11752   { shmedia_builtin_p,
11753     CODE_FOR_lshrv4hi3, "__builtin_lshrv4hi3", SH_BLTIN_SH_HI, 0 },
11754   { shmedia_builtin_p,
11755     CODE_FOR_subv2si3,  "__builtin_subv2si3", SH_BLTIN_V2SI3, 0 },
11756   { shmedia_builtin_p,
11757     CODE_FOR_subv4hi3,  "__builtin_subv4hi3", SH_BLTIN_V4HI3, 0 },
11758   { shmedia_builtin_p,
11759     CODE_FOR_sssubv2si3,"__builtin_sssubv2si3", SH_BLTIN_V2SI3, 0 },
11760   { shmedia_builtin_p,
11761     CODE_FOR_ussubv8qi3,"__builtin_ussubv8qi3", SH_BLTIN_V8QI3, 0 },
11762   { shmedia_builtin_p,
11763     CODE_FOR_sssubv4hi3,"__builtin_sssubv4hi3", SH_BLTIN_V4HI3, 0 },
11764   { shmedia_builtin_p,
11765     CODE_FOR_fcosa_s,   "__builtin_sh_media_FCOSA_S", SH_BLTIN_SISF, 0 },
11766   { shmedia_builtin_p,
11767     CODE_FOR_fsina_s,   "__builtin_sh_media_FSINA_S", SH_BLTIN_SISF, 0 },
11768   { shmedia_builtin_p,
11769     CODE_FOR_fipr,      "__builtin_sh_media_FIPR_S", SH_BLTIN_3, 0 },
11770   { shmedia_builtin_p,
11771     CODE_FOR_ftrv,      "__builtin_sh_media_FTRV_S", SH_BLTIN_3, 0 },
11772   { shmedia_builtin_p,
11773     CODE_FOR_sqrtdf2,   "__builtin_sh_media_FSQRT_D", SH_BLTIN_2, 0 },
11774   { shmedia_builtin_p,
11775     CODE_FOR_sqrtsf2,   "__builtin_sh_media_FSQRT_S", SH_BLTIN_2, 0 },
11776   { shmedia_builtin_p,
11777     CODE_FOR_fsrra_s,   "__builtin_sh_media_FSRRA_S", SH_BLTIN_2, 0 },
11778   { shmedia_builtin_p,
11779     CODE_FOR_ldhi_l,    "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L, 0 },
11780   { shmedia_builtin_p,
11781     CODE_FOR_ldhi_q,    "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q, 0 },
11782   { shmedia_builtin_p,
11783     CODE_FOR_ldlo_l,    "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L, 0 },
11784   { shmedia_builtin_p,
11785     CODE_FOR_ldlo_q,    "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q, 0 },
11786   { shmedia_builtin_p,
11787     CODE_FOR_sthi_l,    "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L, 0 },
11788   { shmedia_builtin_p,
11789     CODE_FOR_sthi_q,    "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q, 0 },
11790   { shmedia_builtin_p,
11791     CODE_FOR_stlo_l,    "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L, 0 },
11792   { shmedia_builtin_p,
11793     CODE_FOR_stlo_q,    "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q, 0 },
11794   { shmedia_builtin_p,
11795     CODE_FOR_ldhi_l64,  "__builtin_sh_media_LDHI_L", SH_BLTIN_LDUA_L64, 0 },
11796   { shmedia_builtin_p,
11797     CODE_FOR_ldhi_q64,  "__builtin_sh_media_LDHI_Q", SH_BLTIN_LDUA_Q64, 0 },
11798   { shmedia_builtin_p,
11799     CODE_FOR_ldlo_l64,  "__builtin_sh_media_LDLO_L", SH_BLTIN_LDUA_L64, 0 },
11800   { shmedia_builtin_p,
11801     CODE_FOR_ldlo_q64,  "__builtin_sh_media_LDLO_Q", SH_BLTIN_LDUA_Q64, 0 },
11802   { shmedia_builtin_p,
11803     CODE_FOR_sthi_l64,  "__builtin_sh_media_STHI_L", SH_BLTIN_STUA_L64, 0 },
11804   { shmedia_builtin_p,
11805     CODE_FOR_sthi_q64,  "__builtin_sh_media_STHI_Q", SH_BLTIN_STUA_Q64, 0 },
11806   { shmedia_builtin_p,
11807     CODE_FOR_stlo_l64,  "__builtin_sh_media_STLO_L", SH_BLTIN_STUA_L64, 0 },
11808   { shmedia_builtin_p,
11809     CODE_FOR_stlo_q64,  "__builtin_sh_media_STLO_Q", SH_BLTIN_STUA_Q64, 0 },
11810   { shmedia_builtin_p,
11811     CODE_FOR_nsb,       "__builtin_sh_media_NSB", SH_BLTIN_SU, 0 },
11812   { shmedia_builtin_p,
11813     CODE_FOR_byterev,   "__builtin_sh_media_BYTEREV", SH_BLTIN_2, 0 },
11814   { shmedia_builtin_p,
11815     CODE_FOR_prefetch,  "__builtin_sh_media_PREFO", SH_BLTIN_PSSV, 0 },
11816 };
11817
11818 static void
11819 sh_init_builtins (void)
11820 {
11821   tree shared[SH_BLTIN_NUM_SHARED_SIGNATURES];
11822   memset (shared, 0, sizeof shared);
11823
11824   for (unsigned int di = 0; di < ARRAY_SIZE (bdesc); ++di)
11825     {
11826       builtin_description* d = &bdesc[di];
11827
11828       if (!d->is_enabled ())
11829         continue;
11830
11831       tree type, arg_type = NULL_TREE;
11832       int signature = d->signature;
11833
11834       if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES && shared[signature])
11835         type = shared[signature];
11836       else
11837         {
11838           int has_result = signature_args[signature][0] != 0;
11839           tree args[3];
11840
11841           if ((signature_args[signature][1] & 8)
11842               && (((signature_args[signature][1] & 1) && TARGET_SHMEDIA32)
11843                   || ((signature_args[signature][1] & 2) && TARGET_SHMEDIA64)))
11844             continue;
11845           if (! TARGET_FPU_ANY
11846               && FLOAT_MODE_P (insn_data[d->icode].operand[0].mode))
11847             continue;
11848           for (unsigned int i = 0; i < ARRAY_SIZE (args); i++)
11849             args[i] = NULL_TREE;
11850           for (int i = 3; ; i--)
11851             {
11852               int arg = signature_args[signature][i];
11853               int opno = i - 1 + has_result;
11854
11855               if (arg & 8)
11856                 arg_type = ptr_type_node;
11857               else if (arg)
11858                 arg_type = (*lang_hooks.types.type_for_mode)
11859                   (insn_data[d->icode].operand[opno].mode, (arg & 1));
11860               else if (i)
11861                 continue;
11862               else
11863                 arg_type = void_type_node;
11864               if (i == 0)
11865                 break;
11866               args[i-1] = arg_type;
11867             }
11868           type = build_function_type_list (arg_type, args[0], args[1],
11869                                            args[2], NULL_TREE);
11870           if (signature < SH_BLTIN_NUM_SHARED_SIGNATURES)
11871             shared[signature] = type;
11872         }
11873       d->fndecl =
11874         add_builtin_function (d->name, type, d - bdesc, BUILT_IN_MD,
11875                               NULL, NULL_TREE);
11876     }
11877 }
11878
11879 /* Implements target hook vector_mode_supported_p.  */
11880 bool
11881 sh_vector_mode_supported_p (enum machine_mode mode)
11882 {
11883   if (TARGET_FPU_ANY
11884       && ((mode == V2SFmode)
11885           || (mode == V4SFmode)
11886           || (mode == V16SFmode)))
11887     return true;
11888
11889   else if (TARGET_SHMEDIA
11890            && ((mode == V8QImode)
11891                || (mode == V2HImode)
11892                || (mode == V4HImode)
11893                || (mode == V2SImode)))
11894     return true;
11895
11896   return false;
11897 }
11898
11899 bool
11900 sh_frame_pointer_required (void)
11901 {
11902 /* If needed override this in other tm.h files to cope with various OS 
11903    lossage requiring a frame pointer.  */
11904   if (SUBTARGET_FRAME_POINTER_REQUIRED)
11905     return true;
11906
11907   if (crtl->profile)
11908     return true;
11909
11910   return false;
11911 }
11912
11913 /* Implements target hook dwarf_calling_convention.  Return an enum
11914    of dwarf_calling_convention.  */
11915 int
11916 sh_dwarf_calling_convention (const_tree func)
11917 {
11918   if (sh_attr_renesas_p (func))
11919     return DW_CC_GNU_renesas_sh;
11920
11921   return DW_CC_normal;
11922 }
11923
11924 /* Returns the sh builtin decl for CODE.  */
11925 static tree
11926 sh_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
11927 {
11928   if (code >= ARRAY_SIZE (bdesc))
11929     return error_mark_node;
11930
11931   if (!bdesc[code].is_enabled ())
11932     return error_mark_node;
11933
11934   return bdesc[code].fndecl;
11935 }
11936
11937 /* Expand an expression EXP that calls a built-in function,
11938    with result going to TARGET if that's convenient
11939    (and in mode MODE if that's convenient).
11940    SUBTARGET may be used as the target for computing one of EXP's operands.
11941    IGNORE is nonzero if the value is to be ignored.  */
11942 static rtx
11943 sh_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
11944                    enum machine_mode mode ATTRIBUTE_UNUSED, int ignore)
11945 {
11946   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
11947   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
11948   const struct builtin_description *d = &bdesc[fcode];
11949   enum insn_code icode = d->icode;
11950   int signature = d->signature;
11951   int nop = 0;
11952   rtx op[4];
11953
11954   if (signature_args[signature][0])
11955     {
11956       if (ignore)
11957         return NULL_RTX;
11958
11959       enum machine_mode tmode = insn_data[icode].operand[0].mode;
11960       if (! target || GET_MODE (target) != tmode
11961           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
11962         target = gen_reg_rtx (tmode);
11963       op[nop++] = target;
11964     }
11965   else
11966     target = NULL_RTX;
11967
11968   for (int i = 1; i <= 3; i++, nop++)
11969     {
11970       tree arg;
11971       enum machine_mode opmode, argmode;
11972       tree optype;
11973
11974       if (! signature_args[signature][i])
11975         break;
11976       arg = CALL_EXPR_ARG (exp, i - 1);
11977       if (arg == error_mark_node)
11978         return const0_rtx;
11979       if (signature_args[signature][i] & 8)
11980         {
11981           opmode = ptr_mode;
11982           optype = ptr_type_node;
11983         }
11984       else
11985         {
11986           opmode = insn_data[icode].operand[nop].mode;
11987           optype = (*lang_hooks.types.type_for_mode) (opmode, 0);
11988         }
11989       argmode = TYPE_MODE (TREE_TYPE (arg));
11990       if (argmode != opmode)
11991         arg = build1 (NOP_EXPR, optype, arg);
11992       op[nop] = expand_expr (arg, NULL_RTX, opmode, EXPAND_NORMAL);
11993       if (! (*insn_data[icode].operand[nop].predicate) (op[nop], opmode))
11994         op[nop] = copy_to_mode_reg (opmode, op[nop]);
11995     }
11996
11997   rtx pat = NULL_RTX;
11998
11999   switch (nop)
12000     {
12001     case 1:
12002       pat = (*insn_data[d->icode].genfun) (op[0]);
12003       break;
12004     case 2:
12005       pat = (*insn_data[d->icode].genfun) (op[0], op[1]);
12006       break;
12007     case 3:
12008       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2]);
12009       break;
12010     case 4:
12011       pat = (*insn_data[d->icode].genfun) (op[0], op[1], op[2], op[3]);
12012       break;
12013     default:
12014       gcc_unreachable ();
12015     }
12016   if (! pat)
12017     return NULL_RTX;
12018   emit_insn (pat);
12019   return target;
12020 }
12021
12022 void
12023 sh_expand_unop_v2sf (enum rtx_code code, rtx op0, rtx op1)
12024 {
12025   rtx sel0 = const0_rtx;
12026   rtx sel1 = const1_rtx;
12027   rtx (*fn) (rtx, rtx, rtx, rtx, rtx) = gen_unary_sf_op;
12028   rtx op = gen_rtx_fmt_e (code, SFmode, op1);
12029
12030   emit_insn ((*fn) (op0, op1, op, sel0, sel0));
12031   emit_insn ((*fn) (op0, op1, op, sel1, sel1));
12032 }
12033
12034 void
12035 sh_expand_binop_v2sf (enum rtx_code code, rtx op0, rtx op1, rtx op2)
12036 {
12037   rtx op = gen_rtx_fmt_ee (code, SFmode, op1, op2);
12038
12039   emit_insn (gen_binary_sf_op0 (op0, op1, op2, op));
12040   emit_insn (gen_binary_sf_op1 (op0, op1, op2, op));
12041 }
12042
12043 /* Return true if hard register REGNO can hold a value of machine-mode MODE.
12044    We can allow any mode in any general register.  The special registers
12045    only allow SImode.  Don't allow any mode in the PR.
12046
12047    We cannot hold DCmode values in the XD registers because alter_reg
12048    handles subregs of them incorrectly.  We could work around this by
12049    spacing the XD registers like the DR registers, but this would require
12050    additional memory in every compilation to hold larger register vectors.
12051    We could hold SFmode / SCmode values in XD registers, but that
12052    would require a tertiary reload when reloading from / to memory,
12053    and a secondary reload to reload from / to general regs; that
12054    seems to be a losing proposition.
12055
12056    We want to allow TImode FP regs so that when V4SFmode is loaded as TImode,
12057    it won't be ferried through GP registers first.  */
12058 bool
12059 sh_hard_regno_mode_ok (unsigned int regno, enum machine_mode mode)
12060 {
12061   if (SPECIAL_REGISTER_P (regno))
12062     return mode == SImode;
12063
12064   if (regno == FPUL_REG)
12065     return (mode == SImode || mode == SFmode);
12066
12067   if (FP_REGISTER_P (regno) && mode == SFmode)
12068     return true;
12069
12070   if (mode == V2SFmode)
12071     {
12072       if (((FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 2 == 0)
12073            || GENERAL_REGISTER_P (regno)))
12074         return true;
12075       else
12076         return false;
12077     }
12078
12079   if (mode == V4SFmode)
12080     {
12081       if ((FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 4 == 0)
12082           || GENERAL_REGISTER_P (regno))
12083         return true;
12084       else
12085         return false;
12086     }
12087
12088   if (mode == V16SFmode)
12089     {
12090       if (TARGET_SHMEDIA)
12091         {
12092           if (FP_REGISTER_P (regno) && (regno - FIRST_FP_REG) % 16 == 0)
12093             return true;
12094           else
12095             return false;
12096         }
12097       else
12098         return regno == FIRST_XD_REG;
12099     }
12100
12101   if (FP_REGISTER_P (regno))
12102     {
12103       if (mode == SFmode
12104           || mode == SImode
12105           || ((TARGET_SH2E || TARGET_SHMEDIA) && mode == SCmode)
12106           || ((((TARGET_SH4 || TARGET_SH2A_DOUBLE) && mode == DFmode)
12107                || mode == DCmode
12108                || (TARGET_SHMEDIA
12109                    && (mode == DFmode || mode == DImode
12110                        || mode == V2SFmode || mode == TImode)))
12111               && ((regno - FIRST_FP_REG) & 1) == 0)
12112           || ((TARGET_SH4 || TARGET_SHMEDIA) && mode == TImode
12113               && ((regno - FIRST_FP_REG) & 3) == 0))
12114         return true;
12115       else
12116         return false;
12117     }
12118
12119   if (XD_REGISTER_P (regno))
12120     return mode == DFmode;
12121
12122   if (TARGET_REGISTER_P (regno))
12123     return (mode == DImode || mode == SImode || mode == PDImode);
12124
12125   if (regno == PR_REG)
12126     return mode == SImode;
12127
12128   if (regno == FPSCR_REG)
12129     return mode == PSImode;
12130
12131   /* FIXME.  This works around PR target/37633 for -O0.  */
12132   if (!optimize && TARGET_SHMEDIA32 && GET_MODE_SIZE (mode) > 4)
12133     {
12134       unsigned int n = GET_MODE_SIZE (mode) / 8;
12135
12136       if (regno >= FIRST_GENERAL_REG + 10 - n + 1
12137           && regno <= FIRST_GENERAL_REG + 14)
12138         return false;
12139     }
12140
12141   return true;
12142 }
12143
12144 /* Return the class of registers for which a mode change from FROM to TO
12145    is invalid.  */
12146 bool
12147 sh_cannot_change_mode_class (enum machine_mode from, enum machine_mode to,
12148                              enum reg_class rclass)
12149 {
12150   /* We want to enable the use of SUBREGs as a means to
12151      VEC_SELECT a single element of a vector.  */
12152
12153   /* This effectively disallows using GENERAL_REGS for SFmode vector subregs.
12154      This can be problematic when SFmode vector subregs need to be accessed
12155      on the stack with displacement addressing, as it happens with -O0.
12156      Thus we disallow the mode change for -O0.  */
12157   if (to == SFmode && VECTOR_MODE_P (from) && GET_MODE_INNER (from) == SFmode)
12158     return optimize ? (reg_classes_intersect_p (GENERAL_REGS, rclass)) : false;
12159
12160   if (GET_MODE_SIZE (from) != GET_MODE_SIZE (to))
12161     {
12162       if (TARGET_LITTLE_ENDIAN)
12163         {
12164           if (GET_MODE_SIZE (to) < 8 || GET_MODE_SIZE (from) < 8)
12165             return reg_classes_intersect_p (DF_REGS, rclass);
12166         }
12167       else
12168         {
12169           if (GET_MODE_SIZE (from) < 8)
12170             return reg_classes_intersect_p (DF_HI_REGS, rclass);
12171         }
12172     }
12173   return false;
12174 }
12175
12176 /* Return true if registers in machine mode MODE will likely be
12177    allocated to registers in small register classes.  */
12178 bool
12179 sh_small_register_classes_for_mode_p (enum machine_mode mode ATTRIBUTE_UNUSED)
12180 {
12181   return (! TARGET_SHMEDIA);
12182 }
12183
12184 /* If ADDRESS refers to a CODE_LABEL, add NUSES to the number of times
12185    that label is used.  */
12186 void
12187 sh_mark_label (rtx address, int nuses)
12188 {
12189   if (GOTOFF_P (address))
12190     {
12191       /* Extract the label or symbol.  */
12192       address = XEXP (address, 0);
12193       if (GET_CODE (address) == PLUS)
12194         address = XEXP (address, 0);
12195       address = XVECEXP (address, 0, 0);
12196     }
12197   if (GET_CODE (address) == LABEL_REF
12198       && LABEL_P (XEXP (address, 0)))
12199     LABEL_NUSES (XEXP (address, 0)) += nuses;
12200 }
12201
12202 /* Compute extra cost of moving data between one register class
12203    and another.
12204
12205    If SECONDARY*_RELOAD_CLASS says something about the src/dst pair, regclass
12206    uses this information.  Hence, the general register <-> floating point
12207    register information here is not used for SFmode.  */
12208 static int
12209 sh_register_move_cost (enum machine_mode mode,
12210                        reg_class_t srcclass, reg_class_t dstclass)
12211 {
12212   if (dstclass == T_REGS || dstclass == PR_REGS)
12213     return 10;
12214
12215   if (dstclass == MAC_REGS && srcclass == MAC_REGS)
12216     return 4;
12217
12218   if (mode == SImode && ! TARGET_SHMEDIA && TARGET_FMOVD
12219       && REGCLASS_HAS_FP_REG (srcclass)
12220       && REGCLASS_HAS_FP_REG (dstclass))
12221     return 4;
12222
12223   if (REGCLASS_HAS_FP_REG (dstclass) && srcclass == T_REGS)
12224     return ((TARGET_HARD_SH4 && !optimize_size) ? 10 : 7);
12225
12226   if ((REGCLASS_HAS_FP_REG (dstclass) && srcclass == MAC_REGS)
12227       || (dstclass == MAC_REGS && REGCLASS_HAS_FP_REG (srcclass)))
12228     return 9;
12229
12230   if ((REGCLASS_HAS_FP_REG (dstclass)
12231        && REGCLASS_HAS_GENERAL_REG (srcclass))
12232       || (REGCLASS_HAS_GENERAL_REG (dstclass)
12233           && REGCLASS_HAS_FP_REG (srcclass)))
12234     {
12235       /* Discourage trying to use fp regs for a pointer.  This also
12236          discourages fp regs with SImode because Pmode is an alias
12237          of SImode on this target.  See PR target/48596.  */
12238       int addend = (mode == Pmode) ? 40 : 0;
12239
12240       return (((TARGET_SHMEDIA ? 4 : TARGET_FMOVD ? 8 : 12) + addend)
12241               * ((GET_MODE_SIZE (mode) + 7) / 8U));
12242     }
12243
12244   if ((dstclass == FPUL_REGS
12245        && REGCLASS_HAS_GENERAL_REG (srcclass))
12246       || (srcclass == FPUL_REGS
12247           && REGCLASS_HAS_GENERAL_REG (dstclass)))
12248     return 5;
12249
12250   if ((dstclass == FPUL_REGS
12251        && (srcclass == PR_REGS || srcclass == MAC_REGS || srcclass == T_REGS))
12252       || (srcclass == FPUL_REGS
12253           && (dstclass == PR_REGS || dstclass == MAC_REGS)))
12254     return 7;
12255
12256   if ((srcclass == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
12257       || ((dstclass) == TARGET_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
12258     return 20;
12259
12260   /* ??? ptabs faults on (value & 0x3) == 0x3  */
12261   if (TARGET_SHMEDIA
12262       && ((srcclass) == TARGET_REGS || (srcclass) == SIBCALL_REGS))
12263     {
12264       if (sh_gettrcost >= 0)
12265         return sh_gettrcost;
12266       else if (!TARGET_PT_FIXED)
12267         return 100;
12268     }
12269
12270   if ((srcclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (dstclass))
12271       || (dstclass == FPSCR_REGS && ! REGCLASS_HAS_GENERAL_REG (srcclass)))
12272   return 4;
12273
12274   if (TARGET_SHMEDIA
12275       || (TARGET_FMOVD
12276           && ! REGCLASS_HAS_GENERAL_REG (srcclass)
12277           && ! REGCLASS_HAS_GENERAL_REG (dstclass)))
12278     return 2 * ((GET_MODE_SIZE (mode) + 7) / 8U);
12279
12280   return 2 * ((GET_MODE_SIZE (mode) + 3) / 4U);
12281 }
12282
12283 static rtx
12284 emit_load_ptr (rtx reg, rtx addr)
12285 {
12286   rtx mem = gen_const_mem (ptr_mode, addr);
12287
12288   if (Pmode != ptr_mode)
12289     mem = gen_rtx_SIGN_EXTEND (Pmode, mem);
12290   return emit_move_insn (reg, mem);
12291 }
12292
12293 static void
12294 sh_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
12295                     HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
12296                     tree function)
12297 {
12298   CUMULATIVE_ARGS cum;
12299   int structure_value_byref = 0;
12300   rtx this_rtx, this_value, sibcall, insns, funexp;
12301   tree funtype = TREE_TYPE (function);
12302   int simple_add = CONST_OK_FOR_ADD (delta);
12303   int did_load = 0;
12304   rtx scratch0, scratch1, scratch2;
12305   unsigned i;
12306
12307   reload_completed = 1;
12308   epilogue_completed = 1;
12309   crtl->uses_only_leaf_regs = 1;
12310
12311   emit_note (NOTE_INSN_PROLOGUE_END);
12312
12313   /* Find the "this" pointer.  We have such a wide range of ABIs for the
12314      SH that it's best to do this completely machine independently.
12315      "this" is passed as first argument, unless a structure return pointer
12316      comes first, in which case "this" comes second.  */
12317   INIT_CUMULATIVE_ARGS (cum, funtype, NULL_RTX, 0, 1);
12318 #ifndef PCC_STATIC_STRUCT_RETURN
12319   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
12320     structure_value_byref = 1;
12321 #endif /* not PCC_STATIC_STRUCT_RETURN */
12322   if (structure_value_byref && sh_struct_value_rtx (function, 0) == 0)
12323     {
12324       tree ptype = build_pointer_type (TREE_TYPE (funtype));
12325
12326       sh_function_arg_advance (pack_cumulative_args (&cum), Pmode, ptype, true);
12327     }
12328   this_rtx
12329     = sh_function_arg (pack_cumulative_args (&cum), Pmode, ptr_type_node, true);
12330
12331   /* For SHcompact, we only have r0 for a scratch register: r1 is the
12332      static chain pointer (even if you can't have nested virtual functions
12333      right now, someone might implement them sometime), and the rest of the
12334      registers are used for argument passing, are callee-saved, or reserved.  */
12335   /* We need to check call_used_regs / fixed_regs in case -fcall_saved-reg /
12336      -ffixed-reg has been used.  */
12337   if (! call_used_regs[0] || fixed_regs[0])
12338     error ("r0 needs to be available as a call-clobbered register");
12339   scratch0 = scratch1 = scratch2 = gen_rtx_REG (Pmode, 0);
12340   if (! TARGET_SH5)
12341     {
12342       if (call_used_regs[1] && ! fixed_regs[1])
12343         scratch1 = gen_rtx_REG (ptr_mode, 1);
12344       /* N.B., if not TARGET_HITACHI, register 2 is used to pass the pointer
12345          pointing where to return struct values.  */
12346       if (call_used_regs[3] && ! fixed_regs[3])
12347         scratch2 = gen_rtx_REG (Pmode, 3);
12348     }
12349   else if (TARGET_SHMEDIA)
12350     {
12351       for (i = FIRST_GENERAL_REG; i <= LAST_GENERAL_REG; i++)
12352         if (i != REGNO (scratch0) &&
12353             call_used_regs[i] && ! fixed_regs[i] && ! FUNCTION_ARG_REGNO_P (i))
12354           {
12355             scratch1 = gen_rtx_REG (ptr_mode, i);
12356             break;
12357           }
12358       if (scratch1 == scratch0)
12359         error ("need a second call-clobbered general purpose register");
12360       for (i = FIRST_TARGET_REG; i <= LAST_TARGET_REG; i++)
12361         if (call_used_regs[i] && ! fixed_regs[i])
12362           {
12363             scratch2 = gen_rtx_REG (Pmode, i);
12364             break;
12365           }
12366       if (scratch2 == scratch0)
12367         error ("need a call-clobbered target register");
12368     }
12369
12370   this_value = plus_constant (Pmode, this_rtx, delta);
12371   if (vcall_offset
12372       && (simple_add || scratch0 != scratch1)
12373       && strict_memory_address_p (ptr_mode, this_value))
12374     {
12375       emit_load_ptr (scratch0, this_value);
12376       did_load = 1;
12377     }
12378
12379   if (!delta)
12380     ; /* Do nothing.  */
12381   else if (simple_add)
12382     emit_move_insn (this_rtx, this_value);
12383   else
12384     {
12385       emit_move_insn (scratch1, GEN_INT (delta));
12386       emit_insn (gen_add2_insn (this_rtx, scratch1));
12387     }
12388
12389   if (vcall_offset)
12390     {
12391       rtx offset_addr;
12392
12393       if (!did_load)
12394         emit_load_ptr (scratch0, this_rtx);
12395
12396       offset_addr = plus_constant (Pmode, scratch0, vcall_offset);
12397       if (strict_memory_address_p (ptr_mode, offset_addr))
12398         ; /* Do nothing.  */
12399       else if (! TARGET_SH5 && scratch0 != scratch1)
12400         {
12401           /* scratch0 != scratch1, and we have indexed loads.  Get better
12402              schedule by loading the offset into r1 and using an indexed
12403              load - then the load of r1 can issue before the load from
12404              (this_rtx + delta) finishes.  */
12405           emit_move_insn (scratch1, GEN_INT (vcall_offset));
12406           offset_addr = gen_rtx_PLUS (Pmode, scratch0, scratch1);
12407         }
12408       else if (CONST_OK_FOR_ADD (vcall_offset))
12409         {
12410           emit_insn (gen_add2_insn (scratch0, GEN_INT (vcall_offset)));
12411           offset_addr = scratch0;
12412         }
12413       else if (scratch0 != scratch1)
12414         {
12415           emit_move_insn (scratch1, GEN_INT (vcall_offset));
12416           emit_insn (gen_add2_insn (scratch0, scratch1));
12417           offset_addr = scratch0;
12418         }
12419       else
12420         gcc_unreachable (); /* FIXME */
12421       emit_load_ptr (scratch0, offset_addr);
12422
12423       if (Pmode != ptr_mode)
12424         scratch0 = gen_rtx_TRUNCATE (ptr_mode, scratch0);
12425       emit_insn (gen_add2_insn (this_rtx, scratch0));
12426     }
12427
12428   /* Generate a tail call to the target function.  */
12429   if (! TREE_USED (function))
12430     {
12431       assemble_external (function);
12432       TREE_USED (function) = 1;
12433     }
12434   funexp = XEXP (DECL_RTL (function), 0);
12435   /* If the function is overridden, so is the thunk, hence we don't
12436      need GOT addressing even if this is a public symbol.  */
12437 #if 0
12438   if (TARGET_SH1 && ! flag_weak)
12439     sibcall = gen_sibcalli_thunk (funexp, const0_rtx);
12440   else
12441 #endif
12442   if (TARGET_SH2 && flag_pic)
12443     {
12444       sibcall = gen_sibcall_pcrel (funexp, const0_rtx);
12445       XEXP (XVECEXP (sibcall, 0, 2), 0) = scratch2;
12446     }
12447   else
12448     {
12449       if (TARGET_SHMEDIA && flag_pic)
12450         {
12451           funexp = gen_sym2PIC (funexp);
12452           PUT_MODE (funexp, Pmode);
12453         }
12454       emit_move_insn (scratch2, funexp);
12455       funexp = gen_rtx_MEM (FUNCTION_MODE, scratch2);
12456       sibcall = gen_sibcall (funexp, const0_rtx, NULL_RTX);
12457     }
12458   sibcall = emit_call_insn (sibcall);
12459   SIBLING_CALL_P (sibcall) = 1;
12460   use_reg (&CALL_INSN_FUNCTION_USAGE (sibcall), this_rtx);
12461   emit_barrier ();
12462
12463   /* Run just enough of rest_of_compilation to do scheduling and get
12464      the insns emitted.  Note that use_thunk calls
12465      assemble_start_function and assemble_end_function.  */
12466
12467   insns = get_insns ();
12468
12469   if (optimize > 0)
12470     {
12471       if (! cfun->cfg)
12472         init_flow (cfun);
12473       split_all_insns_noflow ();
12474     }
12475
12476   sh_reorg ();
12477   shorten_branches (insns);
12478   final_start_function (insns, file, 1);
12479   final (insns, file, 1);
12480   final_end_function ();
12481
12482   reload_completed = 0;
12483   epilogue_completed = 0;
12484 }
12485
12486 rtx
12487 function_symbol (rtx target, const char *name, enum sh_function_kind kind)
12488 {
12489   rtx sym;
12490
12491   /* If this is not an ordinary function, the name usually comes from a
12492      string literal or an sprintf buffer.  Make sure we use the same
12493      string consistently, so that cse will be able to unify address loads.  */
12494   if (kind != FUNCTION_ORDINARY)
12495     name = IDENTIFIER_POINTER (get_identifier (name));
12496   sym = gen_rtx_SYMBOL_REF (Pmode, name);
12497   SYMBOL_REF_FLAGS (sym) = SYMBOL_FLAG_FUNCTION;
12498   if (flag_pic)
12499     switch (kind)
12500       {
12501       case FUNCTION_ORDINARY:
12502         break;
12503       case SFUNC_GOT:
12504         {
12505           rtx reg = target ? target : gen_reg_rtx (Pmode);
12506
12507           emit_insn (gen_symGOT2reg (reg, sym));
12508           sym = reg;
12509           break;
12510         }
12511       case SFUNC_STATIC:
12512         {
12513           /* ??? To allow cse to work, we use GOTOFF relocations.
12514              We could add combiner patterns to transform this into
12515              straight pc-relative calls with sym2PIC / bsrf when
12516              label load and function call are still 1:1 and in the
12517              same basic block during combine.  */
12518           rtx reg = target ? target : gen_reg_rtx (Pmode);
12519
12520           emit_insn (gen_symGOTOFF2reg (reg, sym));
12521           sym = reg;
12522           break;
12523         }
12524       }
12525   if (target && sym != target)
12526     {
12527       emit_move_insn (target, sym);
12528       return target;
12529     }
12530   return sym;
12531 }
12532
12533 /* Find the number of a general purpose register in S.  */
12534 static int
12535 scavenge_reg (HARD_REG_SET *s)
12536 {
12537   int r;
12538   for (r = FIRST_GENERAL_REG; r <= LAST_GENERAL_REG; r++)
12539     if (TEST_HARD_REG_BIT (*s, r))
12540       return r;
12541   return -1;
12542 }
12543
12544 rtx
12545 sh_get_pr_initial_val (void)
12546 {
12547   rtx val;
12548
12549   /* ??? Unfortunately, get_hard_reg_initial_val doesn't always work for the
12550      PR register on SHcompact, because it might be clobbered by the prologue.
12551      We check first if that is known to be the case.  */
12552   if (TARGET_SHCOMPACT
12553       && ((crtl->args.info.call_cookie
12554            & ~ CALL_COOKIE_RET_TRAMP (1))
12555           || crtl->saves_all_registers))
12556     return gen_frame_mem (SImode, return_address_pointer_rtx);
12557
12558   /* If we haven't finished rtl generation, there might be a nonlocal label
12559      that we haven't seen yet.
12560      ??? get_hard_reg_initial_val fails if it is called after register
12561      allocation has started, unless it has been called before for the
12562      same register.  And even then, we end in trouble if we didn't use
12563      the register in the same basic block before.  So call
12564      get_hard_reg_initial_val now and wrap it in an unspec if we might
12565      need to replace it.  */
12566   /* ??? We also must do this for TARGET_SH1 in general, because otherwise
12567      combine can put the pseudo returned by get_hard_reg_initial_val into
12568      instructions that need a general purpose registers, which will fail to
12569      be recognized when the pseudo becomes allocated to PR.  */
12570   val
12571     = get_hard_reg_initial_val (Pmode, TARGET_SHMEDIA ? PR_MEDIA_REG : PR_REG);
12572   if (TARGET_SH1)
12573     return gen_rtx_UNSPEC (SImode, gen_rtvec (1, val), UNSPEC_RA);
12574   return val;
12575 }
12576
12577 bool
12578 sh_expand_t_scc (rtx operands[])
12579 {
12580   enum rtx_code code = GET_CODE (operands[1]);
12581   rtx target = operands[0];
12582   rtx op0 = operands[2];
12583   rtx op1 = operands[3];
12584   rtx result = target;
12585   HOST_WIDE_INT val;
12586
12587   if (!REG_P (op0) || REGNO (op0) != T_REG
12588       || !CONST_INT_P (op1))
12589     return false;
12590   if (!REG_P (result))
12591     result = gen_reg_rtx (SImode);
12592   val = INTVAL (op1);
12593   if ((code == EQ && val == 1) || (code == NE && val == 0))
12594     emit_insn (gen_movt (result, get_t_reg_rtx ()));
12595   else if ((code == EQ && val == 0) || (code == NE && val == 1))
12596     emit_insn (gen_movnegt (result, get_t_reg_rtx ()));
12597   else if (code == EQ || code == NE)
12598     emit_insn (gen_move_insn (result, GEN_INT (code == NE)));
12599   else
12600     return false;
12601   if (result != target)
12602     emit_move_insn (target, result);
12603   return true;
12604 }
12605
12606 /* INSN is an sfunc; return the rtx that describes the address used.  */
12607 static rtx
12608 extract_sfunc_addr (rtx insn)
12609 {
12610   rtx pattern, part = NULL_RTX;
12611   int len, i;
12612
12613   pattern = PATTERN (insn);
12614   len = XVECLEN (pattern, 0);
12615   for (i = 0; i < len; i++)
12616     {
12617       part = XVECEXP (pattern, 0, i);
12618       if (GET_CODE (part) == USE && GET_MODE (XEXP (part, 0)) == Pmode
12619           && GENERAL_REGISTER_P (true_regnum (XEXP (part, 0))))
12620         return XEXP (part, 0);
12621     }
12622   gcc_assert (GET_CODE (XVECEXP (pattern, 0, 0)) == UNSPEC_VOLATILE);
12623   return XVECEXP (XVECEXP (pattern, 0, 0), 0, 1);
12624 }
12625
12626 /* Verify that the register in use_sfunc_addr still agrees with the address
12627    used in the sfunc.  This prevents fill_slots_from_thread from changing
12628    use_sfunc_addr.
12629    INSN is the use_sfunc_addr instruction, and REG is the register it
12630    guards.  */
12631 bool
12632 check_use_sfunc_addr (rtx insn, rtx reg)
12633 {
12634   /* Search for the sfunc.  It should really come right after INSN.  */
12635   while ((insn = NEXT_INSN (insn)))
12636     {
12637       if (LABEL_P (insn) || JUMP_P (insn))
12638         break;
12639       if (! INSN_P (insn))
12640         continue;
12641
12642       if (GET_CODE (PATTERN (insn)) == SEQUENCE)
12643         insn = XVECEXP (PATTERN (insn), 0, 0);
12644       if (GET_CODE (PATTERN (insn)) != PARALLEL
12645           || get_attr_type (insn) != TYPE_SFUNC)
12646         continue;
12647       return rtx_equal_p (extract_sfunc_addr (insn), reg);
12648     }
12649   gcc_unreachable ();
12650 }
12651
12652 /* This function returns a constant rtx that represents 2**15 / pi in
12653    SFmode.  It's used to scale a fixed-point signed 16.16-bit fraction
12654    of a full circle back to an SFmode value, i.e. 0x10000 maps to 2*pi.  */
12655 static GTY(()) rtx sh_fsca_sf2int_rtx;
12656
12657 rtx
12658 sh_fsca_sf2int (void)
12659 {
12660   if (! sh_fsca_sf2int_rtx)
12661     {
12662       REAL_VALUE_TYPE rv;
12663
12664       real_from_string (&rv, "10430.378350470453");
12665       sh_fsca_sf2int_rtx = const_double_from_real_value (rv, SFmode);
12666     }
12667
12668   return sh_fsca_sf2int_rtx;
12669 }
12670
12671 /* This function returns a constant rtx that represents pi / 2**15 in
12672    SFmode.  It's used to scale SFmode angles, in radians, to a
12673    fixed-point signed 16.16-bit fraction of a full circle, i.e. 2*pi
12674    maps to 0x10000.  */
12675 static GTY(()) rtx sh_fsca_int2sf_rtx;
12676
12677 rtx
12678 sh_fsca_int2sf (void)
12679 {
12680   if (! sh_fsca_int2sf_rtx)
12681     {
12682       REAL_VALUE_TYPE rv;
12683
12684       real_from_string (&rv, "9.587379924285257e-5");
12685       sh_fsca_int2sf_rtx = const_double_from_real_value (rv, SFmode);
12686     }
12687
12688   return sh_fsca_int2sf_rtx;
12689 }
12690
12691 /* Initialize the CUMULATIVE_ARGS structure.  */
12692 void
12693 sh_init_cumulative_args (CUMULATIVE_ARGS *  pcum,
12694                          tree               fntype,
12695                          rtx                libname ATTRIBUTE_UNUSED,
12696                          tree               fndecl,
12697                          signed int         n_named_args,
12698                          enum machine_mode  mode)
12699 {
12700   pcum->arg_count [(int) SH_ARG_FLOAT] = 0;
12701   pcum->free_single_fp_reg = 0;
12702   pcum->stack_regs = 0;
12703   pcum->byref_regs = 0;
12704   pcum->byref = 0;
12705   pcum->outgoing = (n_named_args == -1) ? 0 : 1;
12706
12707   /* XXX - Should we check TARGET_HITACHI here ???  */
12708   pcum->renesas_abi = sh_attr_renesas_p (fntype) ? 1 : 0;
12709
12710   if (fntype)
12711     {
12712       pcum->force_mem = ((TARGET_HITACHI || pcum->renesas_abi)
12713                          && aggregate_value_p (TREE_TYPE (fntype), fndecl));
12714       pcum->prototype_p = prototype_p (fntype);
12715       pcum->arg_count [(int) SH_ARG_INT]
12716         = TARGET_SH5 && aggregate_value_p (TREE_TYPE (fntype), fndecl);
12717
12718       pcum->call_cookie
12719         = CALL_COOKIE_RET_TRAMP (TARGET_SHCOMPACT
12720                                  && pcum->arg_count [(int) SH_ARG_INT] == 0
12721                                  && (TYPE_MODE (TREE_TYPE (fntype)) == BLKmode
12722                                      ? int_size_in_bytes (TREE_TYPE (fntype))
12723                                      : GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (fntype)))) > 4
12724                                  && (BASE_RETURN_VALUE_REG (TYPE_MODE (TREE_TYPE (fntype)))
12725                                      == FIRST_RET_REG));
12726     }
12727   else
12728     {
12729       pcum->arg_count [(int) SH_ARG_INT] = 0;
12730       pcum->prototype_p = FALSE;
12731       if (mode != VOIDmode)
12732         {
12733           pcum->call_cookie =
12734             CALL_COOKIE_RET_TRAMP (TARGET_SHCOMPACT
12735                                    && GET_MODE_SIZE (mode) > 4
12736                                    && BASE_RETURN_VALUE_REG (mode) == FIRST_RET_REG);
12737
12738           /* If the default ABI is the Renesas ABI then all library
12739              calls must assume that the library will be using the
12740              Renesas ABI.  So if the function would return its result
12741              in memory then we must force the address of this memory
12742              block onto the stack.  Ideally we would like to call
12743              targetm.calls.return_in_memory() here but we do not have
12744              the TYPE or the FNDECL available so we synthesize the
12745              contents of that function as best we can.  */
12746           pcum->force_mem =
12747             (TARGET_DEFAULT & MASK_HITACHI)
12748             && (mode == BLKmode
12749                 || (GET_MODE_SIZE (mode) > 4
12750                     && !(mode == DFmode
12751                          && TARGET_FPU_DOUBLE)));
12752         }
12753       else
12754         {
12755           pcum->call_cookie = 0;
12756           pcum->force_mem = FALSE;
12757         }
12758     }
12759 }
12760
12761 /* Replace any occurrence of FROM(n) in X with TO(n).  The function does
12762    not enter into CONST_DOUBLE for the replace.
12763
12764    Note that copying is not done so X must not be shared unless all copies
12765    are to be modified.
12766
12767    This is like replace_rtx, except that we operate on N_REPLACEMENTS
12768    replacements simultaneously - FROM(n) is replacements[n*2] and to(n) is
12769    replacements[n*2+1] - and that we take mode changes into account.
12770
12771    If a replacement is ambiguous, return NULL_RTX.
12772
12773    If MODIFY is zero, don't modify any rtl in place,
12774    just return zero or nonzero for failure / success.  */
12775 rtx
12776 replace_n_hard_rtx (rtx x, rtx *replacements, int n_replacements, int modify)
12777 {
12778   int i, j;
12779   const char *fmt;
12780
12781   /* The following prevents loops occurrence when we change MEM in
12782      CONST_DOUBLE onto the same CONST_DOUBLE.  */
12783   if (x != NULL_RTX && GET_CODE (x) == CONST_DOUBLE)
12784     return x;
12785
12786   for (i = n_replacements - 1; i >= 0 ; i--)
12787   if (x == replacements[i*2] && GET_MODE (x) == GET_MODE (replacements[i*2+1]))
12788     return replacements[i*2+1];
12789
12790   /* Allow this function to make replacements in EXPR_LISTs.  */
12791   if (x == NULL_RTX)
12792     return NULL_RTX;
12793
12794   if (GET_CODE (x) == SUBREG)
12795     {
12796       rtx new_rtx = replace_n_hard_rtx (SUBREG_REG (x), replacements,
12797                                     n_replacements, modify);
12798
12799       if (CONST_INT_P (new_rtx))
12800         {
12801           x = simplify_subreg (GET_MODE (x), new_rtx,
12802                                GET_MODE (SUBREG_REG (x)),
12803                                SUBREG_BYTE (x));
12804           if (! x)
12805             abort ();
12806         }
12807       else if (modify)
12808         SUBREG_REG (x) = new_rtx;
12809
12810       return x;
12811     }
12812   else if (REG_P (x))
12813     {
12814       unsigned regno = REGNO (x);
12815       unsigned nregs = (regno < FIRST_PSEUDO_REGISTER
12816                         ? HARD_REGNO_NREGS (regno, GET_MODE (x)) : 1);
12817       rtx result = NULL_RTX;
12818
12819       for (i = n_replacements - 1; i >= 0; i--)
12820         {
12821           rtx from = replacements[i*2];
12822           rtx to = replacements[i*2+1];
12823           unsigned from_regno, from_nregs, to_regno, new_regno;
12824
12825           if (!REG_P (from))
12826             continue;
12827           from_regno = REGNO (from);
12828           from_nregs = (from_regno < FIRST_PSEUDO_REGISTER
12829                         ? HARD_REGNO_NREGS (from_regno, GET_MODE (from)) : 1);
12830           if (regno < from_regno + from_nregs && regno + nregs > from_regno)
12831             {
12832               if (regno < from_regno
12833                   || regno + nregs > from_regno + nregs
12834                   || !REG_P (to)
12835                   || result)
12836                 return NULL_RTX;
12837               to_regno = REGNO (to);
12838               if (to_regno < FIRST_PSEUDO_REGISTER)
12839                 {
12840                   new_regno = regno + to_regno - from_regno;
12841                   if ((unsigned) HARD_REGNO_NREGS (new_regno, GET_MODE (x))
12842                       != nregs)
12843                     return NULL_RTX;
12844                   result = gen_rtx_REG (GET_MODE (x), new_regno);
12845                 }
12846               else if (GET_MODE (x) <= GET_MODE (to))
12847                 result = gen_lowpart_common (GET_MODE (x), to);
12848               else
12849                 result = gen_lowpart_SUBREG (GET_MODE (x), to);
12850             }
12851         }
12852       return result ? result : x;
12853     }
12854   else if (GET_CODE (x) == ZERO_EXTEND)
12855     {
12856       rtx new_rtx = replace_n_hard_rtx (XEXP (x, 0), replacements,
12857                                     n_replacements, modify);
12858
12859       if (CONST_INT_P (new_rtx))
12860         {
12861           x = simplify_unary_operation (ZERO_EXTEND, GET_MODE (x),
12862                                         new_rtx, GET_MODE (XEXP (x, 0)));
12863           if (! x)
12864             abort ();
12865         }
12866       else if (modify)
12867         XEXP (x, 0) = new_rtx;
12868
12869       return x;
12870     }
12871
12872   fmt = GET_RTX_FORMAT (GET_CODE (x));
12873   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
12874     {
12875       rtx new_rtx;
12876
12877       if (fmt[i] == 'e')
12878         {
12879           new_rtx = replace_n_hard_rtx (XEXP (x, i), replacements,
12880                                     n_replacements, modify);
12881           if (!new_rtx)
12882             return NULL_RTX;
12883           if (modify)
12884             XEXP (x, i) = new_rtx;
12885         }
12886       else if (fmt[i] == 'E')
12887         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
12888           {
12889             new_rtx = replace_n_hard_rtx (XVECEXP (x, i, j), replacements,
12890                                       n_replacements, modify);
12891           if (!new_rtx)
12892             return NULL_RTX;
12893             if (modify)
12894               XVECEXP (x, i, j) = new_rtx;
12895           }
12896     }
12897
12898   return x;
12899 }
12900
12901 rtx
12902 sh_gen_truncate (enum machine_mode mode, rtx x, int need_sign_ext)
12903 {
12904   enum rtx_code code = TRUNCATE;
12905
12906   if (GET_CODE (x) == ZERO_EXTEND || GET_CODE (x) == SIGN_EXTEND)
12907     {
12908       rtx inner = XEXP (x, 0);
12909       enum machine_mode inner_mode = GET_MODE (inner);
12910
12911       if (inner_mode == mode)
12912         return inner;
12913       else if (GET_MODE_SIZE (inner_mode) >= GET_MODE_SIZE (mode))
12914         x = inner;
12915       else if (GET_MODE_SIZE (inner_mode) < GET_MODE_SIZE (mode)
12916                && (! need_sign_ext || GET_CODE (x) == SIGN_EXTEND))
12917         {
12918           code = GET_CODE (x);
12919           x = inner;
12920         }
12921     }
12922   return gen_rtx_fmt_e (code, mode, x);
12923 }
12924
12925 /* Called via for_each_rtx after reload, to clean up truncates of
12926    registers that span multiple actual hard registers.  */
12927 int
12928 shmedia_cleanup_truncate (rtx *p, void *n_changes)
12929 {
12930   rtx x = *p, reg;
12931
12932   if (GET_CODE (x) != TRUNCATE)
12933     return 0;
12934   reg = XEXP (x, 0);
12935   if (GET_MODE_SIZE (GET_MODE (reg)) > 8 && REG_P (reg))
12936     {
12937       enum machine_mode reg_mode = GET_MODE (reg);
12938       XEXP (x, 0) = simplify_subreg (DImode, reg, reg_mode,
12939                                      subreg_lowpart_offset (DImode, reg_mode));
12940       *(int*) n_changes += 1;
12941       return -1;
12942     }
12943   return 0;
12944 }
12945
12946 /* Load and store depend on the highpart of the address.  However,
12947    set_attr_alternative does not give well-defined results before reload,
12948    so we must look at the rtl ourselves to see if any of the feeding
12949    registers is used in a memref.
12950
12951    Called by sh_contains_memref_p via for_each_rtx.  */
12952 static int
12953 sh_contains_memref_p_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
12954 {
12955   return (MEM_P (*loc));
12956 }
12957
12958 /* Return true iff INSN contains a MEM.  */
12959 bool
12960 sh_contains_memref_p (rtx insn)
12961 {
12962   return for_each_rtx (&PATTERN (insn), &sh_contains_memref_p_1, NULL);
12963 }
12964
12965 /* Return true iff INSN loads a banked register.  */
12966 bool
12967 sh_loads_bankedreg_p (rtx insn)
12968 {
12969   if (GET_CODE (PATTERN (insn)) == SET)
12970     {
12971       rtx op = SET_DEST (PATTERN(insn));
12972       if (REG_P (op) && BANKED_REGISTER_P (REGNO (op)))
12973         return true;
12974     }
12975
12976   return false;
12977 }
12978
12979 /* FNADDR is the MEM expression from a call expander.  Return an address
12980    to use in an SHmedia insn pattern.  */
12981 rtx
12982 shmedia_prepare_call_address (rtx fnaddr, int is_sibcall)
12983 {
12984   int is_sym;
12985
12986   fnaddr = XEXP (fnaddr, 0);
12987   is_sym = GET_CODE (fnaddr) == SYMBOL_REF;
12988   if (flag_pic && is_sym)
12989     {
12990       if (! SYMBOL_REF_LOCAL_P (fnaddr))
12991         {
12992           rtx reg = gen_reg_rtx (Pmode);
12993
12994           /* We must not use GOTPLT for sibcalls, because PIC_REG
12995              must be restored before the PLT code gets to run.  */
12996           if (is_sibcall)
12997             emit_insn (gen_symGOT2reg (reg, fnaddr));
12998           else
12999             emit_insn (gen_symGOTPLT2reg (reg, fnaddr));
13000           fnaddr = reg;
13001         }
13002       else
13003         {
13004           fnaddr = gen_sym2PIC (fnaddr);
13005           PUT_MODE (fnaddr, Pmode);
13006         }
13007     }
13008   /* If ptabs might trap, make this visible to the rest of the compiler.
13009      We generally assume that symbols pertain to valid locations, but
13010      it is possible to generate invalid symbols with asm or linker tricks.
13011      In a list of functions where each returns its successor, an invalid
13012      symbol might denote an empty list.  */
13013   if (!TARGET_PT_FIXED
13014       && (!is_sym || TARGET_INVALID_SYMBOLS)
13015       && (!REG_P (fnaddr) || ! TARGET_REGISTER_P (REGNO (fnaddr))))
13016     {
13017       rtx tr = gen_reg_rtx (PDImode);
13018
13019       emit_insn (gen_ptabs (tr, fnaddr));
13020       fnaddr = tr;
13021     }
13022   else if (! target_reg_operand (fnaddr, Pmode))
13023     fnaddr = copy_to_mode_reg (Pmode, fnaddr);
13024   return fnaddr;
13025 }
13026
13027 /* Implement TARGET_PREFERRED_RELOAD_CLASS.  */
13028 static reg_class_t
13029 sh_preferred_reload_class (rtx x, reg_class_t rclass)
13030 {
13031   if (rclass == NO_REGS
13032       && TARGET_SHMEDIA
13033       && (CONST_DOUBLE_P (x)
13034           || GET_CODE (x) == SYMBOL_REF
13035           || PIC_ADDR_P (x)))
13036     return GENERAL_REGS;
13037
13038   return rclass;
13039 }
13040
13041 /* Implement TARGET_SECONDARY_RELOAD.  */
13042 static reg_class_t
13043 sh_secondary_reload (bool in_p, rtx x, reg_class_t rclass_i,
13044                      enum machine_mode mode, secondary_reload_info *sri)
13045 {
13046   enum reg_class rclass = (enum reg_class) rclass_i;
13047
13048   if (MEM_P (x) && GET_CODE (XEXP (x, 0)) == PLUS
13049       && REG_P (XEXP (XEXP (x, 0), 0))
13050       && REGNO (XEXP (XEXP (x, 0), 0)) == GBR_REG)
13051     return rclass == R0_REGS ? NO_REGS : R0_REGS;
13052
13053   if (MEM_P (x) && REG_P (XEXP (x, 0)) && REGNO (XEXP (x, 0)) == GBR_REG)
13054     return rclass == R0_REGS ? NO_REGS : R0_REGS;
13055
13056   if (REG_P (x) && REGNO (x) == GBR_REG)
13057     return NO_REGS;
13058
13059   if (in_p)
13060     {
13061       if (REGCLASS_HAS_FP_REG (rclass)
13062           && ! TARGET_SHMEDIA
13063           && immediate_operand ((x), mode)
13064           && ! ((fp_zero_operand (x) || fp_one_operand (x))
13065                 && mode == SFmode && fldi_ok ()))
13066         switch (mode)
13067           {
13068           case SFmode:
13069             sri->icode = CODE_FOR_reload_insf__frn;
13070             return NO_REGS;
13071           case DFmode:
13072             sri->icode = CODE_FOR_reload_indf__frn;
13073             return NO_REGS;
13074           case SImode:
13075             /* ??? If we knew that we are in the appropriate mode -
13076                single precision - we could use a reload pattern directly.  */
13077             return FPUL_REGS;
13078           default:
13079             abort ();
13080           }
13081       if (rclass == FPUL_REGS
13082           && ((REG_P (x) && (REGNO (x) == MACL_REG || REGNO (x) == MACH_REG
13083                              || REGNO (x) == T_REG))
13084               || GET_CODE (x) == PLUS))
13085         return GENERAL_REGS;
13086       if (rclass == FPUL_REGS && immediate_operand (x, mode))
13087         {
13088           if (satisfies_constraint_I08 (x) || fp_zero_operand (x))
13089             return GENERAL_REGS;
13090           else if (mode == SFmode)
13091             return FP_REGS;
13092           sri->icode = CODE_FOR_reload_insi__i_fpul;
13093           return NO_REGS;
13094         }
13095       if (rclass == FPSCR_REGS
13096           && ((REG_P (x) && REGNO (x) >= FIRST_PSEUDO_REGISTER)
13097               || (MEM_P (x) && GET_CODE (XEXP (x, 0)) == PLUS)))
13098         return GENERAL_REGS;
13099       if (REGCLASS_HAS_FP_REG (rclass)
13100           && TARGET_SHMEDIA
13101           && immediate_operand (x, mode)
13102           && x != CONST0_RTX (GET_MODE (x))
13103           && GET_MODE (x) != V4SFmode)
13104         return GENERAL_REGS;
13105       if ((mode == QImode || mode == HImode)
13106           && TARGET_SHMEDIA && inqhi_operand (x, mode))
13107         {
13108           sri->icode = ((mode == QImode)
13109                         ? CODE_FOR_reload_inqi : CODE_FOR_reload_inhi);
13110           return NO_REGS;
13111         }
13112       if (TARGET_SHMEDIA && rclass == GENERAL_REGS
13113           && (GET_CODE (x) == LABEL_REF || PIC_ADDR_P (x)))
13114         return TARGET_REGS;
13115     } /* end of input-only processing.  */
13116
13117   if (((REGCLASS_HAS_FP_REG (rclass)
13118         && (REG_P (x)
13119             && (GENERAL_OR_AP_REGISTER_P (REGNO (x))
13120                 || (FP_REGISTER_P (REGNO (x)) && mode == SImode
13121                     && TARGET_FMOVD))))
13122        || (REGCLASS_HAS_GENERAL_REG (rclass)
13123            && REG_P (x)
13124            && FP_REGISTER_P (REGNO (x))))
13125       && ! TARGET_SHMEDIA
13126       && (mode == SFmode || mode == SImode))
13127     return FPUL_REGS;
13128   if ((rclass == FPUL_REGS
13129        || (REGCLASS_HAS_FP_REG (rclass)
13130            && ! TARGET_SHMEDIA && mode == SImode))
13131       && (MEM_P (x)
13132           || (REG_P (x)
13133               && (REGNO (x) >= FIRST_PSEUDO_REGISTER
13134                   || REGNO (x) == T_REG
13135                   || system_reg_operand (x, VOIDmode)))))
13136     {
13137       if (rclass == FPUL_REGS)
13138         return GENERAL_REGS;
13139       return FPUL_REGS;
13140     }
13141   if ((rclass == TARGET_REGS
13142        || (TARGET_SHMEDIA && rclass == SIBCALL_REGS))
13143       && !satisfies_constraint_Csy (x)
13144       && (!REG_P (x) || ! GENERAL_REGISTER_P (REGNO (x))))
13145     return GENERAL_REGS;
13146   if ((rclass == MAC_REGS || rclass == PR_REGS)
13147       && REG_P (x) && ! GENERAL_REGISTER_P (REGNO (x))
13148       && rclass != REGNO_REG_CLASS (REGNO (x)))
13149     return GENERAL_REGS;
13150   if (rclass != GENERAL_REGS && REG_P (x)
13151       && TARGET_REGISTER_P (REGNO (x)))
13152     return GENERAL_REGS;
13153
13154  /* If here fall back to loading FPUL register through general registers.
13155     This case can happen when movsi_ie insn is picked initially to
13156     load/store the FPUL register from/to another register, and then the
13157     other register is allocated on the stack.  */
13158   if (rclass == FPUL_REGS && true_regnum (x) == -1)
13159     return GENERAL_REGS;
13160
13161   /* Force mov.b / mov.w displacement addressing insn to use R0 as
13162      the other operand.
13163      On SH2A could also just leave it alone here, which would result in a
13164      4 byte move insn being generated instead.  However, for this to work
13165      the insns must have the appropriate alternatives.  */
13166   if ((mode == QImode || mode == HImode) && rclass != R0_REGS
13167       && satisfies_constraint_Sdd (x)
13168       && disp_addr_displacement (x) <= max_mov_insn_displacement (mode, false))
13169     return R0_REGS;
13170
13171   /* When reload is trying to address a QImode or HImode subreg on the stack, 
13172      force any subreg byte into R0_REGS, as this is going to become a
13173      displacement address.
13174      We could restrict this to SUBREG_BYTE (x) > 0, but if the actual reg
13175      is on the stack, the memref to it might already require a displacement
13176      and that has to be added to the final address.  At this point we don't
13177      know the cumulative displacement so we assume the worst case.  */
13178   if ((mode == QImode || mode == HImode) && rclass != R0_REGS 
13179       && GET_CODE (x) == SUBREG && true_regnum (x) == -1)
13180     return R0_REGS;
13181
13182   return NO_REGS;
13183 }
13184
13185 static void
13186 sh_conditional_register_usage (void)
13187 {
13188   int regno;
13189   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno ++)
13190     if (! VALID_REGISTER_P (regno))
13191       fixed_regs[regno] = call_used_regs[regno] = 1;
13192   /* R8 and R9 are call-clobbered on SH5, but not on earlier SH ABIs.  */
13193   if (TARGET_SH5)
13194     {
13195       call_used_regs[FIRST_GENERAL_REG + 8]
13196         = call_used_regs[FIRST_GENERAL_REG + 9] = 1;
13197       call_really_used_regs[FIRST_GENERAL_REG + 8]
13198         = call_really_used_regs[FIRST_GENERAL_REG + 9] = 1;
13199     }
13200   if (TARGET_SHMEDIA)
13201     {
13202       regno_reg_class[FIRST_GENERAL_REG] = GENERAL_REGS;
13203       CLEAR_HARD_REG_SET (reg_class_contents[FP0_REGS]);
13204       regno_reg_class[FIRST_FP_REG] = FP_REGS;
13205     }
13206   if (flag_pic)
13207     {
13208       fixed_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
13209       call_used_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
13210     }
13211   /* Renesas saves and restores mac registers on call.  */
13212   if (TARGET_HITACHI && ! TARGET_NOMACSAVE)
13213     {
13214       call_really_used_regs[MACH_REG] = 0;
13215       call_really_used_regs[MACL_REG] = 0;
13216     }
13217   for (regno = FIRST_FP_REG + (TARGET_LITTLE_ENDIAN != 0);
13218        regno <= LAST_FP_REG; regno += 2)
13219     SET_HARD_REG_BIT (reg_class_contents[DF_HI_REGS], regno);
13220   if (TARGET_SHMEDIA)
13221     {
13222       for (regno = FIRST_TARGET_REG; regno <= LAST_TARGET_REG; regno ++)
13223         if (! fixed_regs[regno] && call_really_used_regs[regno])
13224           SET_HARD_REG_BIT (reg_class_contents[SIBCALL_REGS], regno);
13225     }
13226   else
13227     for (regno = FIRST_GENERAL_REG; regno <= LAST_GENERAL_REG; regno++)
13228       if (! fixed_regs[regno] && call_really_used_regs[regno])
13229         SET_HARD_REG_BIT (reg_class_contents[SIBCALL_REGS], regno);
13230 }
13231
13232 /* Implement TARGET_LEGITIMATE_CONSTANT_P
13233
13234    can_store_by_pieces constructs VOIDmode CONST_DOUBLEs.  */
13235 static bool
13236 sh_legitimate_constant_p (enum machine_mode mode, rtx x)
13237 {
13238   return (TARGET_SHMEDIA
13239           ? ((mode != DFmode && GET_MODE_CLASS (mode) != MODE_VECTOR_FLOAT)
13240              || x == CONST0_RTX (mode)
13241              || !TARGET_SHMEDIA_FPU
13242              || TARGET_SHMEDIA64)
13243           : (GET_CODE (x) != CONST_DOUBLE
13244              || mode == DFmode || mode == SFmode
13245              || mode == DImode || GET_MODE (x) == VOIDmode));
13246 }
13247
13248 enum sh_divide_strategy_e sh_div_strategy = SH_DIV_STRATEGY_DEFAULT;
13249
13250 static void
13251 sh_init_sync_libfuncs (void)
13252 {
13253   init_sync_libfuncs (UNITS_PER_WORD);
13254 }
13255
13256 /* Return true if it is appropriate to emit `ret' instructions in the
13257    body of a function.  */
13258 bool
13259 sh_can_use_simple_return_p (void)
13260 {
13261   HARD_REG_SET live_regs_mask;
13262   int d;
13263
13264   /* Some targets require special return insns.  */
13265   if (TARGET_SHMEDIA
13266       || (TARGET_SHCOMPACT
13267           && (crtl->args.info.call_cookie & CALL_COOKIE_RET_TRAMP (1))))
13268     return false;
13269
13270   if (! reload_completed || frame_pointer_needed)
13271     return false;
13272
13273   /* Moving prologue around does't reduce the size.  */
13274   if (optimize_function_for_size_p (cfun))
13275     return false;
13276
13277   /* Finally, allow for pr save.  */
13278   d = calc_live_regs (&live_regs_mask);
13279
13280   if (rounded_frame_size (d) > 4)
13281    return false;
13282
13283   return true;
13284 }
13285
13286 /*------------------------------------------------------------------------------
13287   Address mode optimization support code
13288 */
13289
13290 typedef HOST_WIDE_INT disp_t;
13291 static const disp_t MIN_DISP = HOST_WIDE_INT_MIN;
13292 static const disp_t MAX_DISP = HOST_WIDE_INT_MAX;
13293 static const disp_t INVALID_DISP = MAX_DISP;
13294
13295 /* A memory reference which is described by a base register and a
13296    displacement.  */
13297 class base_reg_disp
13298 {
13299 public:
13300   base_reg_disp (rtx br, disp_t d);
13301
13302   bool is_reg (void) const;
13303   bool is_disp (void) const;
13304   rtx reg (void) const;
13305   disp_t disp (void) const;
13306
13307 private:
13308   rtx reg_;
13309   disp_t disp_;
13310 };
13311
13312 inline
13313 base_reg_disp::base_reg_disp (rtx br, disp_t d)
13314 : reg_ (br), disp_ (d)
13315 {
13316 }
13317  
13318 inline bool
13319 base_reg_disp::is_reg (void) const
13320 {
13321   return reg_ != NULL_RTX && disp_ != INVALID_DISP;
13322 }
13323
13324 inline bool
13325 base_reg_disp::is_disp (void) const
13326 {
13327   return reg_ == NULL_RTX && disp_ != INVALID_DISP;
13328 }
13329
13330 inline rtx
13331 base_reg_disp::reg (void) const
13332 {
13333   return reg_;
13334 }
13335
13336 inline disp_t
13337 base_reg_disp::disp (void) const
13338 {
13339   return disp_;
13340 }
13341
13342 /* Find the base register and calculate the displacement for a given
13343    address rtx 'x'.
13344    This is done by walking the insn list backwards and following SET insns
13345    that set the value of the specified reg 'x'.  */
13346 static base_reg_disp
13347 sh_find_base_reg_disp (rtx insn, rtx x, disp_t disp = 0, rtx base_reg = NULL)
13348 {
13349   if (REG_P (x))
13350     {
13351       if (REGNO (x) == GBR_REG)
13352         return base_reg_disp (x, disp);
13353
13354       /* We've reached a hard-reg.  This is probably the point where
13355          function args are copied to pseudos.  Do not go any further and
13356          stick to the pseudo.  If the original mem addr was in a hard reg
13357          from the beginning, it will become the base reg.  */
13358       if (REGNO (x) < FIRST_PSEUDO_REGISTER)
13359         return base_reg_disp (base_reg != NULL ? base_reg : x, disp);
13360
13361       /* Try to find the previous insn that sets the reg.  */
13362       for (rtx i = prev_nonnote_insn (insn); i != NULL;
13363            i = prev_nonnote_insn (i))
13364         {
13365           if (REGNO_REG_SET_P (regs_invalidated_by_call_regset, GBR_REG)
13366               && CALL_P (i))
13367             break;
13368
13369           if (!NONJUMP_INSN_P (i))
13370             continue;
13371
13372           rtx p = PATTERN (i);
13373           if (p != NULL && GET_CODE (p) == SET && REG_P (XEXP (p, 0))
13374               && REGNO (XEXP (p, 0)) == REGNO (x))
13375             {
13376               /* If the recursion can't find out any more details about the
13377                  source of the set, then this reg becomes our new base reg.  */
13378               return sh_find_base_reg_disp (i, XEXP (p, 1), disp, XEXP (p, 0));
13379             }
13380         }
13381
13382     /* When here, no previous insn was found that sets the reg.
13383        The input reg is already the base reg.  */
13384     return base_reg_disp (x, disp);
13385   }
13386
13387   else if (GET_CODE (x) == PLUS)
13388     {
13389       base_reg_disp left_val = sh_find_base_reg_disp (insn, XEXP (x, 0));
13390       base_reg_disp right_val = sh_find_base_reg_disp (insn, XEXP (x, 1));
13391
13392       /* Either left or right val must be a reg.
13393          We don't handle the case of 'reg + reg' here.  */
13394       if (left_val.is_reg () && right_val.is_disp ())
13395         return base_reg_disp (left_val.reg (), left_val.disp ()
13396                                                + right_val.disp () + disp);
13397       else if (right_val.is_reg () && left_val.is_disp ())
13398         return base_reg_disp (right_val.reg (), right_val.disp ()
13399                                                 + left_val.disp () + disp);
13400       else
13401         return base_reg_disp (base_reg, disp);
13402     }
13403
13404   else if (CONST_INT_P (x))
13405     return base_reg_disp (NULL, disp + INTVAL (x));
13406
13407   /* Didn't find anything useful.  */
13408   return base_reg_disp (base_reg, disp);
13409 }
13410
13411 /* Given an insn and a memory operand, try to find an equivalent GBR
13412    based memory address and return the corresponding new memory address.
13413    Return NULL_RTX if not found.  */
13414 rtx
13415 sh_find_equiv_gbr_addr (rtx insn, rtx mem)
13416 {
13417   if (!MEM_P (mem))
13418     return NULL_RTX;
13419
13420   /* Leave post/pre inc/dec or any other side effect addresses alone.  */
13421   if (side_effects_p (XEXP (mem, 0)))
13422     return NULL_RTX;
13423
13424   base_reg_disp gbr_disp = sh_find_base_reg_disp (insn, XEXP (mem, 0));
13425
13426   if (gbr_disp.is_reg () && REGNO (gbr_disp.reg ()) == GBR_REG)
13427     {
13428       rtx disp = GEN_INT (gbr_disp.disp ());
13429       if (gbr_displacement (disp, GET_MODE (mem)))
13430         return gen_rtx_PLUS (SImode, gen_rtx_REG (SImode, GBR_REG), disp);
13431     }
13432
13433   return NULL_RTX;
13434 }
13435
13436 /*------------------------------------------------------------------------------
13437   Manual insn combine support code.
13438 */
13439
13440 /* Given a reg rtx and a start insn, try to find the insn that sets the
13441    specified reg by using the specified insn stepping function, such as 
13442    'prev_nonnote_insn_bb'.  When the insn is found, try to extract the rtx
13443    of the reg set.  */
13444 set_of_reg
13445 sh_find_set_of_reg (rtx reg, rtx insn, rtx(*stepfunc)(rtx))
13446 {
13447   set_of_reg result;
13448   result.insn = insn;
13449   result.set_rtx = NULL_RTX;
13450   result.set_src = NULL_RTX;
13451
13452   if (!REG_P (reg) || insn == NULL_RTX)
13453     return result;
13454
13455   for (result.insn = stepfunc (insn); result.insn != NULL_RTX;
13456        result.insn = stepfunc (result.insn))
13457     {
13458       if (BARRIER_P (result.insn))
13459         return result;
13460       if (!NONJUMP_INSN_P (result.insn))
13461         continue;
13462       if (reg_set_p (reg, result.insn))
13463         {
13464           result.set_rtx = set_of (reg, result.insn);
13465
13466           if (result.set_rtx == NULL_RTX || GET_CODE (result.set_rtx) != SET)
13467             return result;
13468
13469           result.set_src = XEXP (result.set_rtx, 1);
13470           return result;
13471         }
13472     }
13473
13474   return result;
13475 }
13476
13477 /* Given an op rtx and an insn, try to find out whether the result of the
13478    specified op consists only of logical operations on T bit stores.  */
13479 bool
13480 sh_is_logical_t_store_expr (rtx op, rtx insn)
13481 {
13482   if (!logical_operator (op, SImode))
13483     return false;
13484
13485   rtx ops[2] = { XEXP (op, 0), XEXP (op, 1) };
13486   int op_is_t_count = 0;
13487
13488   for (int i = 0; i < 2; ++i)
13489     {
13490       if (t_reg_operand (ops[i], VOIDmode)
13491           || negt_reg_operand (ops[i], VOIDmode))
13492         op_is_t_count++;
13493
13494       else
13495         {
13496           set_of_reg op_set = sh_find_set_of_reg (ops[i], insn,
13497                                                   prev_nonnote_insn_bb);
13498           if (op_set.set_src == NULL_RTX)
13499             continue;
13500
13501           if (t_reg_operand (op_set.set_src, VOIDmode)
13502               || negt_reg_operand (op_set.set_src, VOIDmode)
13503               || sh_is_logical_t_store_expr (op_set.set_src, op_set.insn))
13504               op_is_t_count++;
13505         }
13506     }
13507   
13508   return op_is_t_count == 2;
13509 }
13510
13511 /* Given the operand that is extended in a sign/zero extend insn, and the
13512    insn, try to figure out whether the sign/zero extension can be replaced
13513    by a simple reg-reg copy.  If so, the replacement reg rtx is returned,
13514    NULL_RTX otherwise.  */
13515 rtx
13516 sh_try_omit_signzero_extend (rtx extended_op, rtx insn)
13517 {
13518   if (REG_P (extended_op))
13519     extended_op = extended_op;
13520   else if (GET_CODE (extended_op) == SUBREG && REG_P (SUBREG_REG (extended_op)))
13521     extended_op = SUBREG_REG (extended_op);
13522   else
13523     return NULL_RTX;
13524
13525   /* Reg moves must be of the same mode.  */
13526   if (GET_MODE (extended_op) != SImode)
13527     return NULL_RTX;
13528
13529   set_of_reg s = sh_find_set_of_reg (extended_op, insn, prev_nonnote_insn_bb);
13530   if (s.set_src == NULL_RTX)
13531     return NULL_RTX;
13532
13533   if (t_reg_operand (s.set_src, VOIDmode)
13534       || negt_reg_operand (s.set_src, VOIDmode))
13535     return extended_op;
13536
13537   /* If the zero extended reg was formed by a logical operation, check the
13538      operands of the logical operation.  If both originated from T bit
13539      stores the zero extension can be eliminated.  */
13540   else if (sh_is_logical_t_store_expr (s.set_src, s.insn))
13541     return extended_op;
13542
13543   return NULL_RTX;
13544 }
13545
13546 #include "gt-sh.h"