OSDN Git Service

2010-11-08 Joern Rennecke <amylaar@spamcop.net>
[pf3gnuchains/gcc-fork.git] / gcc / config / frv / frv.c
1 /* Copyright (C) 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
2    2008, 2009, 2010  Free Software Foundation, Inc.
3    Contributed by Red Hat, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "regs.h"
28 #include "hard-reg-set.h"
29 #include "insn-config.h"
30 #include "conditions.h"
31 #include "insn-flags.h"
32 #include "output.h"
33 #include "insn-attr.h"
34 #include "flags.h"
35 #include "recog.h"
36 #include "reload.h"
37 #include "expr.h"
38 #include "obstack.h"
39 #include "except.h"
40 #include "function.h"
41 #include "optabs.h"
42 #include "diagnostic-core.h"
43 #include "toplev.h"
44 #include "basic-block.h"
45 #include "tm_p.h"
46 #include "ggc.h"
47 #include <ctype.h>
48 #include "target.h"
49 #include "target-def.h"
50 #include "targhooks.h"
51 #include "integrate.h"
52 #include "langhooks.h"
53 #include "df.h"
54
55 #ifndef FRV_INLINE
56 #define FRV_INLINE inline
57 #endif
58
59 /* The maximum number of distinct NOP patterns.  There are three:
60    nop, fnop and mnop.  */
61 #define NUM_NOP_PATTERNS 3
62
63 /* Classification of instructions and units: integer, floating-point/media,
64    branch and control.  */
65 enum frv_insn_group { GROUP_I, GROUP_FM, GROUP_B, GROUP_C, NUM_GROUPS };
66
67 /* The DFA names of the units, in packet order.  */
68 static const char *const frv_unit_names[] =
69 {
70   "c",
71   "i0", "f0",
72   "i1", "f1",
73   "i2", "f2",
74   "i3", "f3",
75   "b0", "b1"
76 };
77
78 /* The classification of each unit in frv_unit_names[].  */
79 static const enum frv_insn_group frv_unit_groups[ARRAY_SIZE (frv_unit_names)] =
80 {
81   GROUP_C,
82   GROUP_I, GROUP_FM,
83   GROUP_I, GROUP_FM,
84   GROUP_I, GROUP_FM,
85   GROUP_I, GROUP_FM,
86   GROUP_B, GROUP_B
87 };
88
89 /* Return the DFA unit code associated with the Nth unit of integer
90    or floating-point group GROUP,  */
91 #define NTH_UNIT(GROUP, N) frv_unit_codes[(GROUP) + (N) * 2 + 1]
92
93 /* Return the number of integer or floating-point unit UNIT
94    (1 for I1, 2 for F2, etc.).  */
95 #define UNIT_NUMBER(UNIT) (((UNIT) - 1) / 2)
96
97 /* The DFA unit number for each unit in frv_unit_names[].  */
98 static int frv_unit_codes[ARRAY_SIZE (frv_unit_names)];
99
100 /* FRV_TYPE_TO_UNIT[T] is the last unit in frv_unit_names[] that can issue
101    an instruction of type T.  The value is ARRAY_SIZE (frv_unit_names) if
102    no instruction of type T has been seen.  */
103 static unsigned int frv_type_to_unit[TYPE_UNKNOWN + 1];
104
105 /* An array of dummy nop INSNs, one for each type of nop that the
106    target supports.  */
107 static GTY(()) rtx frv_nops[NUM_NOP_PATTERNS];
108
109 /* The number of nop instructions in frv_nops[].  */
110 static unsigned int frv_num_nops;
111
112   /* The type of access.  FRV_IO_UNKNOWN means the access can be either
113      a read or a write.  */
114 enum frv_io_type { FRV_IO_UNKNOWN, FRV_IO_READ, FRV_IO_WRITE };
115
116 /* Information about one __builtin_read or __builtin_write access, or
117    the combination of several such accesses.  The most general value
118    is all-zeros (an unknown access to an unknown address).  */
119 struct frv_io {
120   enum frv_io_type type;
121
122   /* The constant address being accessed, or zero if not known.  */
123   HOST_WIDE_INT const_address;
124
125   /* The run-time address, as used in operand 0 of the membar pattern.  */
126   rtx var_address;
127 };
128
129 /* Return true if instruction INSN should be packed with the following
130    instruction.  */
131 #define PACKING_FLAG_P(INSN) (GET_MODE (INSN) == TImode)
132
133 /* Set the value of PACKING_FLAG_P(INSN).  */
134 #define SET_PACKING_FLAG(INSN) PUT_MODE (INSN, TImode)
135 #define CLEAR_PACKING_FLAG(INSN) PUT_MODE (INSN, VOIDmode)
136
137 /* Loop with REG set to each hard register in rtx X.  */
138 #define FOR_EACH_REGNO(REG, X)                                          \
139   for (REG = REGNO (X);                                                 \
140        REG < REGNO (X) + HARD_REGNO_NREGS (REGNO (X), GET_MODE (X));    \
141        REG++)
142
143 /* This structure contains machine specific function data.  */
144 struct GTY(()) machine_function
145 {
146   /* True if we have created an rtx that relies on the stack frame.  */
147   int frame_needed;
148
149   /* True if this function contains at least one __builtin_{read,write}*.  */
150   bool has_membar_p;
151 };
152
153 /* Temporary register allocation support structure.  */
154 typedef struct frv_tmp_reg_struct
155   {
156     HARD_REG_SET regs;          /* possible registers to allocate */
157     int next_reg[N_REG_CLASSES];        /* next register to allocate per class */
158   }
159 frv_tmp_reg_t;
160
161 /* Register state information for VLIW re-packing phase.  */
162 #define REGSTATE_CC_MASK        0x07    /* Mask to isolate CCn for cond exec */
163 #define REGSTATE_MODIFIED       0x08    /* reg modified in current VLIW insn */
164 #define REGSTATE_IF_TRUE        0x10    /* reg modified in cond exec true */
165 #define REGSTATE_IF_FALSE       0x20    /* reg modified in cond exec false */
166
167 #define REGSTATE_IF_EITHER      (REGSTATE_IF_TRUE | REGSTATE_IF_FALSE)
168
169 typedef unsigned char regstate_t;
170
171 /* Used in frv_frame_accessor_t to indicate the direction of a register-to-
172    memory move.  */
173 enum frv_stack_op
174 {
175   FRV_LOAD,
176   FRV_STORE
177 };
178
179 /* Information required by frv_frame_access.  */
180 typedef struct
181 {
182   /* This field is FRV_LOAD if registers are to be loaded from the stack and
183      FRV_STORE if they should be stored onto the stack.  FRV_STORE implies
184      the move is being done by the prologue code while FRV_LOAD implies it
185      is being done by the epilogue.  */
186   enum frv_stack_op op;
187
188   /* The base register to use when accessing the stack.  This may be the
189      frame pointer, stack pointer, or a temporary.  The choice of register
190      depends on which part of the frame is being accessed and how big the
191      frame is.  */
192   rtx base;
193
194   /* The offset of BASE from the bottom of the current frame, in bytes.  */
195   int base_offset;
196 } frv_frame_accessor_t;
197
198 /* Conditional execution support gathered together in one structure.  */
199 typedef struct
200   {
201     /* Linked list of insns to add if the conditional execution conversion was
202        successful.  Each link points to an EXPR_LIST which points to the pattern
203        of the insn to add, and the insn to be inserted before.  */
204     rtx added_insns_list;
205
206     /* Identify which registers are safe to allocate for if conversions to
207        conditional execution.  We keep the last allocated register in the
208        register classes between COND_EXEC statements.  This will mean we allocate
209        different registers for each different COND_EXEC group if we can.  This
210        might allow the scheduler to intermix two different COND_EXEC sections.  */
211     frv_tmp_reg_t tmp_reg;
212
213     /* For nested IFs, identify which CC registers are used outside of setting
214        via a compare isnsn, and using via a check insn.  This will allow us to
215        know if we can rewrite the register to use a different register that will
216        be paired with the CR register controlling the nested IF-THEN blocks.  */
217     HARD_REG_SET nested_cc_ok_rewrite;
218
219     /* Temporary registers allocated to hold constants during conditional
220        execution.  */
221     rtx scratch_regs[FIRST_PSEUDO_REGISTER];
222
223     /* Current number of temp registers available.  */
224     int cur_scratch_regs;
225
226     /* Number of nested conditional execution blocks.  */
227     int num_nested_cond_exec;
228
229     /* Map of insns that set up constants in scratch registers.  */
230     bitmap scratch_insns_bitmap;
231
232     /* Conditional execution test register (CC0..CC7).  */
233     rtx cr_reg;
234
235     /* Conditional execution compare register that is paired with cr_reg, so that
236        nested compares can be done.  The csubcc and caddcc instructions don't
237        have enough bits to specify both a CC register to be set and a CR register
238        to do the test on, so the same bit number is used for both.  Needless to
239        say, this is rather inconvenient for GCC.  */
240     rtx nested_cc_reg;
241
242     /* Extra CR registers used for &&, ||.  */
243     rtx extra_int_cr;
244     rtx extra_fp_cr;
245
246     /* Previous CR used in nested if, to make sure we are dealing with the same
247        nested if as the previous statement.  */
248     rtx last_nested_if_cr;
249   }
250 frv_ifcvt_t;
251
252 static /* GTY(()) */ frv_ifcvt_t frv_ifcvt;
253
254 /* Map register number to smallest register class.  */
255 enum reg_class regno_reg_class[FIRST_PSEUDO_REGISTER];
256
257 /* Map class letter into register class.  */
258 enum reg_class reg_class_from_letter[256];
259
260 /* Cached value of frv_stack_info.  */
261 static frv_stack_t *frv_stack_cache = (frv_stack_t *)0;
262
263 /* -mcpu= support */
264 frv_cpu_t frv_cpu_type = CPU_TYPE;      /* value of -mcpu= */
265
266 /* Forward references */
267
268 static bool frv_handle_option                   (size_t, const char *, int);
269 static void frv_option_override                 (void);
270 static bool frv_legitimate_address_p            (enum machine_mode, rtx, bool);
271 static int frv_default_flags_for_cpu            (void);
272 static int frv_string_begins_with               (const_tree, const char *);
273 static FRV_INLINE bool frv_small_data_reloc_p   (rtx, int);
274 static void frv_print_operand                   (FILE *, rtx, int);
275 static void frv_print_operand_address           (FILE *, rtx);
276 static bool frv_print_operand_punct_valid_p     (unsigned char code);
277 static void frv_print_operand_memory_reference_reg
278                                                 (FILE *, rtx);
279 static void frv_print_operand_memory_reference  (FILE *, rtx, int);
280 static int frv_print_operand_jump_hint          (rtx);
281 static const char *comparison_string            (enum rtx_code, rtx);
282 static rtx frv_function_value                   (const_tree, const_tree,
283                                                  bool);
284 static rtx frv_libcall_value                    (enum machine_mode,
285                                                  const_rtx);
286 static FRV_INLINE int frv_regno_ok_for_base_p   (int, int);
287 static rtx single_set_pattern                   (rtx);
288 static int frv_function_contains_far_jump       (void);
289 static rtx frv_alloc_temp_reg                   (frv_tmp_reg_t *,
290                                                  enum reg_class,
291                                                  enum machine_mode,
292                                                  int, int);
293 static rtx frv_frame_offset_rtx                 (int);
294 static rtx frv_frame_mem                        (enum machine_mode, rtx, int);
295 static rtx frv_dwarf_store                      (rtx, int);
296 static void frv_frame_insn                      (rtx, rtx);
297 static void frv_frame_access                    (frv_frame_accessor_t*,
298                                                  rtx, int);
299 static void frv_frame_access_multi              (frv_frame_accessor_t*,
300                                                  frv_stack_t *, int);
301 static void frv_frame_access_standard_regs      (enum frv_stack_op,
302                                                  frv_stack_t *);
303 static struct machine_function *frv_init_machine_status         (void);
304 static rtx frv_int_to_acc                       (enum insn_code, int, rtx);
305 static enum machine_mode frv_matching_accg_mode (enum machine_mode);
306 static rtx frv_read_argument                    (tree, unsigned int);
307 static rtx frv_read_iacc_argument               (enum machine_mode, tree, unsigned int);
308 static int frv_check_constant_argument          (enum insn_code, int, rtx);
309 static rtx frv_legitimize_target                (enum insn_code, rtx);
310 static rtx frv_legitimize_argument              (enum insn_code, int, rtx);
311 static rtx frv_legitimize_tls_address           (rtx, enum tls_model);
312 static rtx frv_legitimize_address               (rtx, rtx, enum machine_mode);
313 static rtx frv_expand_set_builtin               (enum insn_code, tree, rtx);
314 static rtx frv_expand_unop_builtin              (enum insn_code, tree, rtx);
315 static rtx frv_expand_binop_builtin             (enum insn_code, tree, rtx);
316 static rtx frv_expand_cut_builtin               (enum insn_code, tree, rtx);
317 static rtx frv_expand_binopimm_builtin          (enum insn_code, tree, rtx);
318 static rtx frv_expand_voidbinop_builtin         (enum insn_code, tree);
319 static rtx frv_expand_int_void2arg              (enum insn_code, tree);
320 static rtx frv_expand_prefetches                (enum insn_code, tree);
321 static rtx frv_expand_voidtriop_builtin         (enum insn_code, tree);
322 static rtx frv_expand_voidaccop_builtin         (enum insn_code, tree);
323 static rtx frv_expand_mclracc_builtin           (tree);
324 static rtx frv_expand_mrdacc_builtin            (enum insn_code, tree);
325 static rtx frv_expand_mwtacc_builtin            (enum insn_code, tree);
326 static rtx frv_expand_noargs_builtin            (enum insn_code);
327 static void frv_split_iacc_move                 (rtx, rtx);
328 static rtx frv_emit_comparison                  (enum rtx_code, rtx, rtx);
329 static int frv_clear_registers_used             (rtx *, void *);
330 static void frv_ifcvt_add_insn                  (rtx, rtx, int);
331 static rtx frv_ifcvt_rewrite_mem                (rtx, enum machine_mode, rtx);
332 static rtx frv_ifcvt_load_value                 (rtx, rtx);
333 static int frv_acc_group_1                      (rtx *, void *);
334 static unsigned int frv_insn_unit               (rtx);
335 static bool frv_issues_to_branch_unit_p         (rtx);
336 static int frv_cond_flags                       (rtx);
337 static bool frv_regstate_conflict_p             (regstate_t, regstate_t);
338 static int frv_registers_conflict_p_1           (rtx *, void *);
339 static bool frv_registers_conflict_p            (rtx);
340 static void frv_registers_update_1              (rtx, const_rtx, void *);
341 static void frv_registers_update                (rtx);
342 static void frv_start_packet                    (void);
343 static void frv_start_packet_block              (void);
344 static void frv_finish_packet                   (void (*) (void));
345 static bool frv_pack_insn_p                     (rtx);
346 static void frv_add_insn_to_packet              (rtx);
347 static void frv_insert_nop_in_packet            (rtx);
348 static bool frv_for_each_packet                 (void (*) (void));
349 static bool frv_sort_insn_group_1               (enum frv_insn_group,
350                                                  unsigned int, unsigned int,
351                                                  unsigned int, unsigned int,
352                                                  state_t);
353 static int frv_compare_insns                    (const void *, const void *);
354 static void frv_sort_insn_group                 (enum frv_insn_group);
355 static void frv_reorder_packet                  (void);
356 static void frv_fill_unused_units               (enum frv_insn_group);
357 static void frv_align_label                     (void);
358 static void frv_reorg_packet                    (void);
359 static void frv_register_nop                    (rtx);
360 static void frv_reorg                           (void);
361 static void frv_pack_insns                      (void);
362 static void frv_function_prologue               (FILE *, HOST_WIDE_INT);
363 static void frv_function_epilogue               (FILE *, HOST_WIDE_INT);
364 static bool frv_assemble_integer                (rtx, unsigned, int);
365 static void frv_init_builtins                   (void);
366 static rtx frv_expand_builtin                   (tree, rtx, rtx, enum machine_mode, int);
367 static void frv_init_libfuncs                   (void);
368 static bool frv_in_small_data_p                 (const_tree);
369 static void frv_asm_output_mi_thunk
370   (FILE *, tree, HOST_WIDE_INT, HOST_WIDE_INT, tree);
371 static void frv_setup_incoming_varargs          (CUMULATIVE_ARGS *,
372                                                  enum machine_mode,
373                                                  tree, int *, int);
374 static rtx frv_expand_builtin_saveregs          (void);
375 static void frv_expand_builtin_va_start         (tree, rtx);
376 static bool frv_rtx_costs                       (rtx, int, int, int*, bool);
377 static int frv_register_move_cost               (enum machine_mode,
378                                                  reg_class_t, reg_class_t);
379 static int frv_memory_move_cost                 (enum machine_mode,
380                                                  reg_class_t, bool);
381 static void frv_asm_out_constructor             (rtx, int);
382 static void frv_asm_out_destructor              (rtx, int);
383 static bool frv_function_symbol_referenced_p    (rtx);
384 static bool frv_cannot_force_const_mem          (rtx);
385 static const char *unspec_got_name              (int);
386 static void frv_output_const_unspec             (FILE *,
387                                                  const struct frv_unspec *);
388 static bool frv_function_ok_for_sibcall         (tree, tree);
389 static rtx frv_struct_value_rtx                 (tree, int);
390 static bool frv_must_pass_in_stack (enum machine_mode mode, const_tree type);
391 static int frv_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
392                                   tree, bool);
393 static rtx frv_function_arg (CUMULATIVE_ARGS *, enum machine_mode,
394                              const_tree, bool);
395 static rtx frv_function_incoming_arg (CUMULATIVE_ARGS *, enum machine_mode,
396                                       const_tree, bool);
397 static void frv_function_arg_advance (CUMULATIVE_ARGS *, enum machine_mode,
398                                        const_tree, bool);
399 static void frv_output_dwarf_dtprel             (FILE *, int, rtx)
400   ATTRIBUTE_UNUSED;
401 static reg_class_t frv_secondary_reload         (bool, rtx, reg_class_t,
402                                                  enum machine_mode,
403                                                  secondary_reload_info *);
404 static bool frv_frame_pointer_required          (void);
405 static bool frv_can_eliminate                   (const int, const int);
406 static void frv_trampoline_init                 (rtx, tree, rtx);
407 static bool frv_class_likely_spilled_p          (reg_class_t);
408
409 /* Implement TARGET_OPTION_OPTIMIZATION_TABLE.  */
410 static const struct default_options frv_option_optimization_table[] =
411   {
412     { OPT_LEVELS_1_PLUS, OPT_fomit_frame_pointer, NULL, 1 },
413     { OPT_LEVELS_NONE, 0, NULL, 0 }
414   };
415 \f
416 /* Allow us to easily change the default for -malloc-cc.  */
417 #ifndef DEFAULT_NO_ALLOC_CC
418 #define MASK_DEFAULT_ALLOC_CC   MASK_ALLOC_CC
419 #else
420 #define MASK_DEFAULT_ALLOC_CC   0
421 #endif
422 \f
423 /* Initialize the GCC target structure.  */
424 #undef TARGET_PRINT_OPERAND
425 #define TARGET_PRINT_OPERAND frv_print_operand
426 #undef TARGET_PRINT_OPERAND_ADDRESS
427 #define TARGET_PRINT_OPERAND_ADDRESS frv_print_operand_address
428 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
429 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P frv_print_operand_punct_valid_p
430 #undef  TARGET_ASM_FUNCTION_PROLOGUE
431 #define TARGET_ASM_FUNCTION_PROLOGUE frv_function_prologue
432 #undef  TARGET_ASM_FUNCTION_EPILOGUE
433 #define TARGET_ASM_FUNCTION_EPILOGUE frv_function_epilogue
434 #undef  TARGET_ASM_INTEGER
435 #define TARGET_ASM_INTEGER frv_assemble_integer
436 #undef TARGET_DEFAULT_TARGET_FLAGS
437 #define TARGET_DEFAULT_TARGET_FLAGS             \
438   (MASK_DEFAULT_ALLOC_CC                        \
439    | MASK_COND_MOVE                             \
440    | MASK_SCC                                   \
441    | MASK_COND_EXEC                             \
442    | MASK_VLIW_BRANCH                           \
443    | MASK_MULTI_CE                              \
444    | MASK_NESTED_CE)
445 #undef TARGET_HANDLE_OPTION
446 #define TARGET_HANDLE_OPTION frv_handle_option
447 #undef TARGET_OPTION_OVERRIDE
448 #define TARGET_OPTION_OVERRIDE frv_option_override
449 #undef TARGET_OPTION_OPTIMIZATION_TABLE
450 #define TARGET_OPTION_OPTIMIZATION_TABLE frv_option_optimization_table
451 #undef TARGET_INIT_BUILTINS
452 #define TARGET_INIT_BUILTINS frv_init_builtins
453 #undef TARGET_EXPAND_BUILTIN
454 #define TARGET_EXPAND_BUILTIN frv_expand_builtin
455 #undef TARGET_INIT_LIBFUNCS
456 #define TARGET_INIT_LIBFUNCS frv_init_libfuncs
457 #undef TARGET_IN_SMALL_DATA_P
458 #define TARGET_IN_SMALL_DATA_P frv_in_small_data_p
459 #undef TARGET_REGISTER_MOVE_COST
460 #define TARGET_REGISTER_MOVE_COST frv_register_move_cost
461 #undef TARGET_MEMORY_MOVE_COST
462 #define TARGET_MEMORY_MOVE_COST frv_memory_move_cost
463 #undef TARGET_RTX_COSTS
464 #define TARGET_RTX_COSTS frv_rtx_costs
465 #undef TARGET_ASM_CONSTRUCTOR
466 #define TARGET_ASM_CONSTRUCTOR frv_asm_out_constructor
467 #undef TARGET_ASM_DESTRUCTOR
468 #define TARGET_ASM_DESTRUCTOR frv_asm_out_destructor
469
470 #undef TARGET_ASM_OUTPUT_MI_THUNK
471 #define TARGET_ASM_OUTPUT_MI_THUNK frv_asm_output_mi_thunk
472 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
473 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK default_can_output_mi_thunk_no_vcall
474
475 #undef  TARGET_SCHED_ISSUE_RATE
476 #define TARGET_SCHED_ISSUE_RATE frv_issue_rate
477
478 #undef TARGET_LEGITIMIZE_ADDRESS
479 #define TARGET_LEGITIMIZE_ADDRESS frv_legitimize_address
480
481 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
482 #define TARGET_FUNCTION_OK_FOR_SIBCALL frv_function_ok_for_sibcall
483 #undef TARGET_CANNOT_FORCE_CONST_MEM
484 #define TARGET_CANNOT_FORCE_CONST_MEM frv_cannot_force_const_mem
485
486 #undef TARGET_HAVE_TLS
487 #define TARGET_HAVE_TLS HAVE_AS_TLS
488
489 #undef TARGET_STRUCT_VALUE_RTX
490 #define TARGET_STRUCT_VALUE_RTX frv_struct_value_rtx
491 #undef TARGET_MUST_PASS_IN_STACK
492 #define TARGET_MUST_PASS_IN_STACK frv_must_pass_in_stack
493 #undef TARGET_PASS_BY_REFERENCE
494 #define TARGET_PASS_BY_REFERENCE hook_pass_by_reference_must_pass_in_stack
495 #undef TARGET_ARG_PARTIAL_BYTES
496 #define TARGET_ARG_PARTIAL_BYTES frv_arg_partial_bytes
497 #undef TARGET_FUNCTION_ARG
498 #define TARGET_FUNCTION_ARG frv_function_arg
499 #undef TARGET_FUNCTION_INCOMING_ARG
500 #define TARGET_FUNCTION_INCOMING_ARG frv_function_incoming_arg
501 #undef TARGET_FUNCTION_ARG_ADVANCE
502 #define TARGET_FUNCTION_ARG_ADVANCE frv_function_arg_advance
503
504 #undef TARGET_EXPAND_BUILTIN_SAVEREGS
505 #define TARGET_EXPAND_BUILTIN_SAVEREGS frv_expand_builtin_saveregs
506 #undef TARGET_SETUP_INCOMING_VARARGS
507 #define TARGET_SETUP_INCOMING_VARARGS frv_setup_incoming_varargs
508 #undef TARGET_MACHINE_DEPENDENT_REORG
509 #define TARGET_MACHINE_DEPENDENT_REORG frv_reorg
510
511 #undef TARGET_EXPAND_BUILTIN_VA_START
512 #define TARGET_EXPAND_BUILTIN_VA_START frv_expand_builtin_va_start
513
514 #if HAVE_AS_TLS
515 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
516 #define TARGET_ASM_OUTPUT_DWARF_DTPREL frv_output_dwarf_dtprel
517 #endif
518
519 #undef TARGET_CLASS_LIKELY_SPILLED_P
520 #define TARGET_CLASS_LIKELY_SPILLED_P frv_class_likely_spilled_p
521
522 #undef  TARGET_SECONDARY_RELOAD
523 #define TARGET_SECONDARY_RELOAD frv_secondary_reload
524
525 #undef TARGET_LEGITIMATE_ADDRESS_P
526 #define TARGET_LEGITIMATE_ADDRESS_P frv_legitimate_address_p
527
528 #undef TARGET_FRAME_POINTER_REQUIRED
529 #define TARGET_FRAME_POINTER_REQUIRED frv_frame_pointer_required
530
531 #undef TARGET_CAN_ELIMINATE
532 #define TARGET_CAN_ELIMINATE frv_can_eliminate
533
534 #undef TARGET_TRAMPOLINE_INIT
535 #define TARGET_TRAMPOLINE_INIT frv_trampoline_init
536
537 #undef TARGET_FUNCTION_VALUE
538 #define TARGET_FUNCTION_VALUE frv_function_value
539 #undef TARGET_LIBCALL_VALUE
540 #define TARGET_LIBCALL_VALUE frv_libcall_value
541
542 struct gcc_target targetm = TARGET_INITIALIZER;
543
544 #define FRV_SYMBOL_REF_TLS_P(RTX) \
545   (GET_CODE (RTX) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (RTX) != 0)
546
547 \f
548 /* Any function call that satisfies the machine-independent
549    requirements is eligible on FR-V.  */
550
551 static bool
552 frv_function_ok_for_sibcall (tree decl ATTRIBUTE_UNUSED,
553                              tree exp ATTRIBUTE_UNUSED)
554 {
555   return true;
556 }
557
558 /* Return true if SYMBOL is a small data symbol and relocation RELOC
559    can be used to access it directly in a load or store.  */
560
561 static FRV_INLINE bool
562 frv_small_data_reloc_p (rtx symbol, int reloc)
563 {
564   return (GET_CODE (symbol) == SYMBOL_REF
565           && SYMBOL_REF_SMALL_P (symbol)
566           && (!TARGET_FDPIC || flag_pic == 1)
567           && (reloc == R_FRV_GOTOFF12 || reloc == R_FRV_GPREL12));
568 }
569
570 /* Return true if X is a valid relocation unspec.  If it is, fill in UNSPEC
571    appropriately.  */
572
573 bool
574 frv_const_unspec_p (rtx x, struct frv_unspec *unspec)
575 {
576   if (GET_CODE (x) == CONST)
577     {
578       unspec->offset = 0;
579       x = XEXP (x, 0);
580       if (GET_CODE (x) == PLUS && GET_CODE (XEXP (x, 1)) == CONST_INT)
581         {
582           unspec->offset += INTVAL (XEXP (x, 1));
583           x = XEXP (x, 0);
584         }
585       if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_GOT)
586         {
587           unspec->symbol = XVECEXP (x, 0, 0);
588           unspec->reloc = INTVAL (XVECEXP (x, 0, 1));
589
590           if (unspec->offset == 0)
591             return true;
592
593           if (frv_small_data_reloc_p (unspec->symbol, unspec->reloc)
594               && unspec->offset > 0
595               && unspec->offset < g_switch_value)
596             return true;
597         }
598     }
599   return false;
600 }
601
602 /* Decide whether we can force certain constants to memory.  If we
603    decide we can't, the caller should be able to cope with it in
604    another way.
605
606    We never allow constants to be forced into memory for TARGET_FDPIC.
607    This is necessary for several reasons:
608
609    1. Since LEGITIMATE_CONSTANT_P rejects constant pool addresses, the
610       target-independent code will try to force them into the constant
611       pool, thus leading to infinite recursion.
612
613    2. We can never introduce new constant pool references during reload.
614       Any such reference would require use of the pseudo FDPIC register.
615
616    3. We can't represent a constant added to a function pointer (which is
617       not the same as a pointer to a function+constant).
618
619    4. In many cases, it's more efficient to calculate the constant in-line.  */
620
621 static bool
622 frv_cannot_force_const_mem (rtx x ATTRIBUTE_UNUSED)
623 {
624   return TARGET_FDPIC;
625 }
626 \f
627 /* Implement TARGET_HANDLE_OPTION.  */
628
629 static bool
630 frv_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
631 {
632   switch (code)
633     {
634     case OPT_mcpu_:
635       if (strcmp (arg, "simple") == 0)
636         frv_cpu_type = FRV_CPU_SIMPLE;
637       else if (strcmp (arg, "tomcat") == 0)
638         frv_cpu_type = FRV_CPU_TOMCAT;
639       else if (strcmp (arg, "fr550") == 0)
640         frv_cpu_type = FRV_CPU_FR550;
641       else if (strcmp (arg, "fr500") == 0)
642         frv_cpu_type = FRV_CPU_FR500;
643       else if (strcmp (arg, "fr450") == 0)
644         frv_cpu_type = FRV_CPU_FR450;
645       else if (strcmp (arg, "fr405") == 0)
646         frv_cpu_type = FRV_CPU_FR405;
647       else if (strcmp (arg, "fr400") == 0)
648         frv_cpu_type = FRV_CPU_FR400;
649       else if (strcmp (arg, "fr300") == 0)
650         frv_cpu_type = FRV_CPU_FR300;
651       else if (strcmp (arg, "frv") == 0)
652         frv_cpu_type = FRV_CPU_GENERIC;
653       else
654         return false;
655       return true;
656
657     default:
658       return true;
659     }
660 }
661
662 static int
663 frv_default_flags_for_cpu (void)
664 {
665   switch (frv_cpu_type)
666     {
667     case FRV_CPU_GENERIC:
668       return MASK_DEFAULT_FRV;
669
670     case FRV_CPU_FR550:
671       return MASK_DEFAULT_FR550;
672
673     case FRV_CPU_FR500:
674     case FRV_CPU_TOMCAT:
675       return MASK_DEFAULT_FR500;
676
677     case FRV_CPU_FR450:
678       return MASK_DEFAULT_FR450;
679
680     case FRV_CPU_FR405:
681     case FRV_CPU_FR400:
682       return MASK_DEFAULT_FR400;
683
684     case FRV_CPU_FR300:
685     case FRV_CPU_SIMPLE:
686       return MASK_DEFAULT_SIMPLE;
687
688     default:
689       gcc_unreachable ();
690     }
691 }
692
693 /* Implement TARGET_OPTION_OVERRIDE.  */
694
695 static void
696 frv_option_override (void)
697 {
698   int regno;
699   unsigned int i;
700
701   target_flags |= (frv_default_flags_for_cpu () & ~target_flags_explicit);
702
703   /* -mlibrary-pic sets -fPIC and -G0 and also suppresses warnings from the
704      linker about linking pic and non-pic code.  */
705   if (TARGET_LIBPIC)
706     {
707       if (!flag_pic)            /* -fPIC */
708         flag_pic = 2;
709
710       if (!global_options_set.x_g_switch_value) /* -G0 */
711         {
712           g_switch_value = 0;
713         }
714     }
715
716   /* A C expression whose value is a register class containing hard
717      register REGNO.  In general there is more than one such class;
718      choose a class which is "minimal", meaning that no smaller class
719      also contains the register.  */
720
721   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
722     {
723       enum reg_class rclass;
724
725       if (GPR_P (regno))
726         {
727           int gpr_reg = regno - GPR_FIRST;
728
729           if (gpr_reg == GR8_REG)
730             rclass = GR8_REGS;
731
732           else if (gpr_reg == GR9_REG)
733             rclass = GR9_REGS;
734
735           else if (gpr_reg == GR14_REG)
736             rclass = FDPIC_FPTR_REGS;
737
738           else if (gpr_reg == FDPIC_REGNO)
739             rclass = FDPIC_REGS;
740
741           else if ((gpr_reg & 3) == 0)
742             rclass = QUAD_REGS;
743
744           else if ((gpr_reg & 1) == 0)
745             rclass = EVEN_REGS;
746
747           else
748             rclass = GPR_REGS;
749         }
750
751       else if (FPR_P (regno))
752         {
753           int fpr_reg = regno - GPR_FIRST;
754           if ((fpr_reg & 3) == 0)
755             rclass = QUAD_FPR_REGS;
756
757           else if ((fpr_reg & 1) == 0)
758             rclass = FEVEN_REGS;
759
760           else
761             rclass = FPR_REGS;
762         }
763
764       else if (regno == LR_REGNO)
765         rclass = LR_REG;
766
767       else if (regno == LCR_REGNO)
768         rclass = LCR_REG;
769
770       else if (ICC_P (regno))
771         rclass = ICC_REGS;
772
773       else if (FCC_P (regno))
774         rclass = FCC_REGS;
775
776       else if (ICR_P (regno))
777         rclass = ICR_REGS;
778
779       else if (FCR_P (regno))
780         rclass = FCR_REGS;
781
782       else if (ACC_P (regno))
783         {
784           int r = regno - ACC_FIRST;
785           if ((r & 3) == 0)
786             rclass = QUAD_ACC_REGS;
787           else if ((r & 1) == 0)
788             rclass = EVEN_ACC_REGS;
789           else
790             rclass = ACC_REGS;
791         }
792
793       else if (ACCG_P (regno))
794         rclass = ACCG_REGS;
795
796       else
797         rclass = NO_REGS;
798
799       regno_reg_class[regno] = rclass;
800     }
801
802   /* Check for small data option */
803   if (!global_options_set.x_g_switch_value && !TARGET_LIBPIC)
804     g_switch_value = SDATA_DEFAULT_SIZE;
805
806   /* A C expression which defines the machine-dependent operand
807      constraint letters for register classes.  If CHAR is such a
808      letter, the value should be the register class corresponding to
809      it.  Otherwise, the value should be `NO_REGS'.  The register
810      letter `r', corresponding to class `GENERAL_REGS', will not be
811      passed to this macro; you do not need to handle it.
812
813      The following letters are unavailable, due to being used as
814      constraints:
815         '0'..'9'
816         '<', '>'
817         'E', 'F', 'G', 'H'
818         'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P'
819         'Q', 'R', 'S', 'T', 'U'
820         'V', 'X'
821         'g', 'i', 'm', 'n', 'o', 'p', 'r', 's' */
822
823   for (i = 0; i < 256; i++)
824     reg_class_from_letter[i] = NO_REGS;
825
826   reg_class_from_letter['a'] = ACC_REGS;
827   reg_class_from_letter['b'] = EVEN_ACC_REGS;
828   reg_class_from_letter['c'] = CC_REGS;
829   reg_class_from_letter['d'] = GPR_REGS;
830   reg_class_from_letter['e'] = EVEN_REGS;
831   reg_class_from_letter['f'] = FPR_REGS;
832   reg_class_from_letter['h'] = FEVEN_REGS;
833   reg_class_from_letter['l'] = LR_REG;
834   reg_class_from_letter['q'] = QUAD_REGS;
835   reg_class_from_letter['t'] = ICC_REGS;
836   reg_class_from_letter['u'] = FCC_REGS;
837   reg_class_from_letter['v'] = ICR_REGS;
838   reg_class_from_letter['w'] = FCR_REGS;
839   reg_class_from_letter['x'] = QUAD_FPR_REGS;
840   reg_class_from_letter['y'] = LCR_REG;
841   reg_class_from_letter['z'] = SPR_REGS;
842   reg_class_from_letter['A'] = QUAD_ACC_REGS;
843   reg_class_from_letter['B'] = ACCG_REGS;
844   reg_class_from_letter['C'] = CR_REGS;
845   reg_class_from_letter['W'] = FDPIC_CALL_REGS; /* gp14+15 */
846   reg_class_from_letter['Z'] = FDPIC_REGS; /* gp15 */
847
848   /* There is no single unaligned SI op for PIC code.  Sometimes we
849      need to use ".4byte" and sometimes we need to use ".picptr".
850      See frv_assemble_integer for details.  */
851   if (flag_pic || TARGET_FDPIC)
852     targetm.asm_out.unaligned_op.si = 0;
853
854   if ((target_flags_explicit & MASK_LINKED_FP) == 0)
855     target_flags |= MASK_LINKED_FP;
856
857   if ((target_flags_explicit & MASK_OPTIMIZE_MEMBAR) == 0)
858     target_flags |= MASK_OPTIMIZE_MEMBAR;
859
860   for (i = 0; i < ARRAY_SIZE (frv_unit_names); i++)
861     frv_unit_codes[i] = get_cpu_unit_code (frv_unit_names[i]);
862
863   for (i = 0; i < ARRAY_SIZE (frv_type_to_unit); i++)
864     frv_type_to_unit[i] = ARRAY_SIZE (frv_unit_codes);
865
866   init_machine_status = frv_init_machine_status;
867 }
868
869 \f
870 /* Return true if NAME (a STRING_CST node) begins with PREFIX.  */
871
872 static int
873 frv_string_begins_with (const_tree name, const char *prefix)
874 {
875   const int prefix_len = strlen (prefix);
876
877   /* Remember: NAME's length includes the null terminator.  */
878   return (TREE_STRING_LENGTH (name) > prefix_len
879           && strncmp (TREE_STRING_POINTER (name), prefix, prefix_len) == 0);
880 }
881 \f
882 /* Zero or more C statements that may conditionally modify two variables
883    `fixed_regs' and `call_used_regs' (both of type `char []') after they have
884    been initialized from the two preceding macros.
885
886    This is necessary in case the fixed or call-clobbered registers depend on
887    target flags.
888
889    You need not define this macro if it has no work to do.
890
891    If the usage of an entire class of registers depends on the target flags,
892    you may indicate this to GCC by using this macro to modify `fixed_regs' and
893    `call_used_regs' to 1 for each of the registers in the classes which should
894    not be used by GCC.  Also define the macro `REG_CLASS_FROM_LETTER' to return
895    `NO_REGS' if it is called with a letter for a class that shouldn't be used.
896
897    (However, if this class is not included in `GENERAL_REGS' and all of the
898    insn patterns whose constraints permit this class are controlled by target
899    switches, then GCC will automatically avoid using these registers when the
900    target switches are opposed to them.)  */
901
902 void
903 frv_conditional_register_usage (void)
904 {
905   int i;
906
907   for (i = GPR_FIRST + NUM_GPRS; i <= GPR_LAST; i++)
908     fixed_regs[i] = call_used_regs[i] = 1;
909
910   for (i = FPR_FIRST + NUM_FPRS; i <= FPR_LAST; i++)
911     fixed_regs[i] = call_used_regs[i] = 1;
912
913   /* Reserve the registers used for conditional execution.  At present, we need
914      1 ICC and 1 ICR register.  */
915   fixed_regs[ICC_TEMP] = call_used_regs[ICC_TEMP] = 1;
916   fixed_regs[ICR_TEMP] = call_used_regs[ICR_TEMP] = 1;
917
918   if (TARGET_FIXED_CC)
919     {
920       fixed_regs[ICC_FIRST] = call_used_regs[ICC_FIRST] = 1;
921       fixed_regs[FCC_FIRST] = call_used_regs[FCC_FIRST] = 1;
922       fixed_regs[ICR_FIRST] = call_used_regs[ICR_FIRST] = 1;
923       fixed_regs[FCR_FIRST] = call_used_regs[FCR_FIRST] = 1;
924     }
925
926   if (TARGET_FDPIC)
927     fixed_regs[GPR_FIRST + 16] = fixed_regs[GPR_FIRST + 17] =
928       call_used_regs[GPR_FIRST + 16] = call_used_regs[GPR_FIRST + 17] = 0;
929
930 #if 0
931   /* If -fpic, SDA_BASE_REG is the PIC register.  */
932   if (g_switch_value == 0 && !flag_pic)
933     fixed_regs[SDA_BASE_REG] = call_used_regs[SDA_BASE_REG] = 0;
934
935   if (!flag_pic)
936     fixed_regs[PIC_REGNO] = call_used_regs[PIC_REGNO] = 0;
937 #endif
938 }
939
940 \f
941 /*
942  * Compute the stack frame layout
943  *
944  * Register setup:
945  * +---------------+-----------------------+-----------------------+
946  * |Register       |type                   |caller-save/callee-save|
947  * +---------------+-----------------------+-----------------------+
948  * |GR0            |Zero register          |        -              |
949  * |GR1            |Stack pointer(SP)      |        -              |
950  * |GR2            |Frame pointer(FP)      |        -              |
951  * |GR3            |Hidden parameter       |        caller save    |
952  * |GR4-GR7        |        -              |        caller save    |
953  * |GR8-GR13       |Argument register      |        caller save    |
954  * |GR14-GR15      |        -              |        caller save    |
955  * |GR16-GR31      |        -              |        callee save    |
956  * |GR32-GR47      |        -              |        caller save    |
957  * |GR48-GR63      |        -              |        callee save    |
958  * |FR0-FR15       |        -              |        caller save    |
959  * |FR16-FR31      |        -              |        callee save    |
960  * |FR32-FR47      |        -              |        caller save    |
961  * |FR48-FR63      |        -              |        callee save    |
962  * +---------------+-----------------------+-----------------------+
963  *
964  * Stack frame setup:
965  * Low
966  *     SP-> |-----------------------------------|
967  *          |         Argument area             |
968  *          |-----------------------------------|
969  *          |    Register save area             |
970  *          |-----------------------------------|
971  *          |   Local variable save area        |
972  *     FP-> |-----------------------------------|
973  *          |       Old FP                      |
974  *          |-----------------------------------|
975  *          |    Hidden parameter save area     |
976  *          |-----------------------------------|
977  *          | Return address(LR) storage area   |
978  *          |-----------------------------------|
979  *          |     Padding for alignment         |
980  *          |-----------------------------------|
981  *          |     Register argument area        |
982  * OLD SP-> |-----------------------------------|
983  *          |       Parameter area              |
984  *          |-----------------------------------|
985  * High
986  *
987  * Argument area/Parameter area:
988  *
989  * When a function is called, this area is used for argument transfer.  When
990  * the argument is set up by the caller function, this area is referred to as
991  * the argument area.  When the argument is referenced by the callee function,
992  * this area is referred to as the parameter area.  The area is allocated when
993  * all arguments cannot be placed on the argument register at the time of
994  * argument transfer.
995  *
996  * Register save area:
997  *
998  * This is a register save area that must be guaranteed for the caller
999  * function.  This area is not secured when the register save operation is not
1000  * needed.
1001  *
1002  * Local variable save area:
1003  *
1004  * This is the area for local variables and temporary variables.
1005  *
1006  * Old FP:
1007  *
1008  * This area stores the FP value of the caller function.
1009  *
1010  * Hidden parameter save area:
1011  *
1012  * This area stores the start address of the return value storage
1013  * area for a struct/union return function.
1014  * When a struct/union is used as the return value, the caller
1015  * function stores the return value storage area start address in
1016  * register GR3 and passes it to the caller function.
1017  * The callee function interprets the address stored in the GR3
1018  * as the return value storage area start address.
1019  * When register GR3 needs to be saved into memory, the callee
1020  * function saves it in the hidden parameter save area.  This
1021  * area is not secured when the save operation is not needed.
1022  *
1023  * Return address(LR) storage area:
1024  *
1025  * This area saves the LR.  The LR stores the address of a return to the caller
1026  * function for the purpose of function calling.
1027  *
1028  * Argument register area:
1029  *
1030  * This area saves the argument register.  This area is not secured when the
1031  * save operation is not needed.
1032  *
1033  * Argument:
1034  *
1035  * Arguments, the count of which equals the count of argument registers (6
1036  * words), are positioned in registers GR8 to GR13 and delivered to the callee
1037  * function.  When a struct/union return function is called, the return value
1038  * area address is stored in register GR3.  Arguments not placed in the
1039  * argument registers will be stored in the stack argument area for transfer
1040  * purposes.  When an 8-byte type argument is to be delivered using registers,
1041  * it is divided into two and placed in two registers for transfer.  When
1042  * argument registers must be saved to memory, the callee function secures an
1043  * argument register save area in the stack.  In this case, a continuous
1044  * argument register save area must be established in the parameter area.  The
1045  * argument register save area must be allocated as needed to cover the size of
1046  * the argument register to be saved.  If the function has a variable count of
1047  * arguments, it saves all argument registers in the argument register save
1048  * area.
1049  *
1050  * Argument Extension Format:
1051  *
1052  * When an argument is to be stored in the stack, its type is converted to an
1053  * extended type in accordance with the individual argument type.  The argument
1054  * is freed by the caller function after the return from the callee function is
1055  * made.
1056  *
1057  * +-----------------------+---------------+------------------------+
1058  * |    Argument Type      |Extended Type  |Stack Storage Size(byte)|
1059  * +-----------------------+---------------+------------------------+
1060  * |char                   |int            |        4               |
1061  * |signed char            |int            |        4               |
1062  * |unsigned char          |int            |        4               |
1063  * |[signed] short int     |int            |        4               |
1064  * |unsigned short int     |int            |        4               |
1065  * |[signed] int           |No extension   |        4               |
1066  * |unsigned int           |No extension   |        4               |
1067  * |[signed] long int      |No extension   |        4               |
1068  * |unsigned long int      |No extension   |        4               |
1069  * |[signed] long long int |No extension   |        8               |
1070  * |unsigned long long int |No extension   |        8               |
1071  * |float                  |double         |        8               |
1072  * |double                 |No extension   |        8               |
1073  * |long double            |No extension   |        8               |
1074  * |pointer                |No extension   |        4               |
1075  * |struct/union           |-              |        4 (*1)          |
1076  * +-----------------------+---------------+------------------------+
1077  *
1078  * When a struct/union is to be delivered as an argument, the caller copies it
1079  * to the local variable area and delivers the address of that area.
1080  *
1081  * Return Value:
1082  *
1083  * +-------------------------------+----------------------+
1084  * |Return Value Type              |Return Value Interface|
1085  * +-------------------------------+----------------------+
1086  * |void                           |None                  |
1087  * |[signed|unsigned] char         |GR8                   |
1088  * |[signed|unsigned] short int    |GR8                   |
1089  * |[signed|unsigned] int          |GR8                   |
1090  * |[signed|unsigned] long int     |GR8                   |
1091  * |pointer                        |GR8                   |
1092  * |[signed|unsigned] long long int|GR8 & GR9             |
1093  * |float                          |GR8                   |
1094  * |double                         |GR8 & GR9             |
1095  * |long double                    |GR8 & GR9             |
1096  * |struct/union                   |(*1)                  |
1097  * +-------------------------------+----------------------+
1098  *
1099  * When a struct/union is used as the return value, the caller function stores
1100  * the start address of the return value storage area into GR3 and then passes
1101  * it to the callee function.  The callee function interprets GR3 as the start
1102  * address of the return value storage area.  When this address needs to be
1103  * saved in memory, the callee function secures the hidden parameter save area
1104  * and saves the address in that area.
1105  */
1106
1107 frv_stack_t *
1108 frv_stack_info (void)
1109 {
1110   static frv_stack_t info, zero_info;
1111   frv_stack_t *info_ptr = &info;
1112   tree fndecl           = current_function_decl;
1113   int varargs_p         = 0;
1114   tree cur_arg;
1115   tree next_arg;
1116   int range;
1117   int alignment;
1118   int offset;
1119
1120   /* If we've already calculated the values and reload is complete,
1121      just return now.  */
1122   if (frv_stack_cache)
1123     return frv_stack_cache;
1124
1125   /* Zero all fields.  */
1126   info = zero_info;
1127
1128   /* Set up the register range information.  */
1129   info_ptr->regs[STACK_REGS_GPR].name         = "gpr";
1130   info_ptr->regs[STACK_REGS_GPR].first        = LAST_ARG_REGNUM + 1;
1131   info_ptr->regs[STACK_REGS_GPR].last         = GPR_LAST;
1132   info_ptr->regs[STACK_REGS_GPR].dword_p      = TRUE;
1133
1134   info_ptr->regs[STACK_REGS_FPR].name         = "fpr";
1135   info_ptr->regs[STACK_REGS_FPR].first        = FPR_FIRST;
1136   info_ptr->regs[STACK_REGS_FPR].last         = FPR_LAST;
1137   info_ptr->regs[STACK_REGS_FPR].dword_p      = TRUE;
1138
1139   info_ptr->regs[STACK_REGS_LR].name          = "lr";
1140   info_ptr->regs[STACK_REGS_LR].first         = LR_REGNO;
1141   info_ptr->regs[STACK_REGS_LR].last          = LR_REGNO;
1142   info_ptr->regs[STACK_REGS_LR].special_p     = 1;
1143
1144   info_ptr->regs[STACK_REGS_CC].name          = "cc";
1145   info_ptr->regs[STACK_REGS_CC].first         = CC_FIRST;
1146   info_ptr->regs[STACK_REGS_CC].last          = CC_LAST;
1147   info_ptr->regs[STACK_REGS_CC].field_p       = TRUE;
1148
1149   info_ptr->regs[STACK_REGS_LCR].name         = "lcr";
1150   info_ptr->regs[STACK_REGS_LCR].first        = LCR_REGNO;
1151   info_ptr->regs[STACK_REGS_LCR].last         = LCR_REGNO;
1152
1153   info_ptr->regs[STACK_REGS_STDARG].name      = "stdarg";
1154   info_ptr->regs[STACK_REGS_STDARG].first     = FIRST_ARG_REGNUM;
1155   info_ptr->regs[STACK_REGS_STDARG].last      = LAST_ARG_REGNUM;
1156   info_ptr->regs[STACK_REGS_STDARG].dword_p   = 1;
1157   info_ptr->regs[STACK_REGS_STDARG].special_p = 1;
1158
1159   info_ptr->regs[STACK_REGS_STRUCT].name      = "struct";
1160   info_ptr->regs[STACK_REGS_STRUCT].first     = FRV_STRUCT_VALUE_REGNUM;
1161   info_ptr->regs[STACK_REGS_STRUCT].last      = FRV_STRUCT_VALUE_REGNUM;
1162   info_ptr->regs[STACK_REGS_STRUCT].special_p = 1;
1163
1164   info_ptr->regs[STACK_REGS_FP].name          = "fp";
1165   info_ptr->regs[STACK_REGS_FP].first         = FRAME_POINTER_REGNUM;
1166   info_ptr->regs[STACK_REGS_FP].last          = FRAME_POINTER_REGNUM;
1167   info_ptr->regs[STACK_REGS_FP].special_p     = 1;
1168
1169   /* Determine if this is a stdarg function.  If so, allocate space to store
1170      the 6 arguments.  */
1171   if (cfun->stdarg)
1172     varargs_p = 1;
1173
1174   else
1175     {
1176       /* Find the last argument, and see if it is __builtin_va_alist.  */
1177       for (cur_arg = DECL_ARGUMENTS (fndecl); cur_arg != (tree)0; cur_arg = next_arg)
1178         {
1179           next_arg = DECL_CHAIN (cur_arg);
1180           if (next_arg == (tree)0)
1181             {
1182               if (DECL_NAME (cur_arg)
1183                   && !strcmp (IDENTIFIER_POINTER (DECL_NAME (cur_arg)), "__builtin_va_alist"))
1184                 varargs_p = 1;
1185
1186               break;
1187             }
1188         }
1189     }
1190
1191   /* Iterate over all of the register ranges.  */
1192   for (range = 0; range < STACK_REGS_MAX; range++)
1193     {
1194       frv_stack_regs_t *reg_ptr = &(info_ptr->regs[range]);
1195       int first = reg_ptr->first;
1196       int last = reg_ptr->last;
1197       int size_1word = 0;
1198       int size_2words = 0;
1199       int regno;
1200
1201       /* Calculate which registers need to be saved & save area size.  */
1202       switch (range)
1203         {
1204         default:
1205           for (regno = first; regno <= last; regno++)
1206             {
1207               if ((df_regs_ever_live_p (regno) && !call_used_regs[regno])
1208                   || (crtl->calls_eh_return
1209                       && (regno >= FIRST_EH_REGNUM && regno <= LAST_EH_REGNUM))
1210                   || (!TARGET_FDPIC && flag_pic
1211                       && crtl->uses_pic_offset_table && regno == PIC_REGNO))
1212                 {
1213                   info_ptr->save_p[regno] = REG_SAVE_1WORD;
1214                   size_1word += UNITS_PER_WORD;
1215                 }
1216             }
1217           break;
1218
1219           /* Calculate whether we need to create a frame after everything else
1220              has been processed.  */
1221         case STACK_REGS_FP:
1222           break;
1223
1224         case STACK_REGS_LR:
1225           if (df_regs_ever_live_p (LR_REGNO)
1226               || profile_flag
1227               /* This is set for __builtin_return_address, etc.  */
1228               || cfun->machine->frame_needed
1229               || (TARGET_LINKED_FP && frame_pointer_needed)
1230               || (!TARGET_FDPIC && flag_pic
1231                   && crtl->uses_pic_offset_table))
1232             {
1233               info_ptr->save_p[LR_REGNO] = REG_SAVE_1WORD;
1234               size_1word += UNITS_PER_WORD;
1235             }
1236           break;
1237
1238         case STACK_REGS_STDARG:
1239           if (varargs_p)
1240             {
1241               /* If this is a stdarg function with a non varardic
1242                  argument split between registers and the stack,
1243                  adjust the saved registers downward.  */
1244               last -= (ADDR_ALIGN (crtl->args.pretend_args_size, UNITS_PER_WORD)
1245                        / UNITS_PER_WORD);
1246
1247               for (regno = first; regno <= last; regno++)
1248                 {
1249                   info_ptr->save_p[regno] = REG_SAVE_1WORD;
1250                   size_1word += UNITS_PER_WORD;
1251                 }
1252
1253               info_ptr->stdarg_size = size_1word;
1254             }
1255           break;
1256
1257         case STACK_REGS_STRUCT:
1258           if (cfun->returns_struct)
1259             {
1260               info_ptr->save_p[FRV_STRUCT_VALUE_REGNUM] = REG_SAVE_1WORD;
1261               size_1word += UNITS_PER_WORD;
1262             }
1263           break;
1264         }
1265
1266
1267       if (size_1word)
1268         {
1269           /* If this is a field, it only takes one word.  */
1270           if (reg_ptr->field_p)
1271             size_1word = UNITS_PER_WORD;
1272
1273           /* Determine which register pairs can be saved together.  */
1274           else if (reg_ptr->dword_p && TARGET_DWORD)
1275             {
1276               for (regno = first; regno < last; regno += 2)
1277                 {
1278                   if (info_ptr->save_p[regno] && info_ptr->save_p[regno+1])
1279                     {
1280                       size_2words += 2 * UNITS_PER_WORD;
1281                       size_1word -= 2 * UNITS_PER_WORD;
1282                       info_ptr->save_p[regno] = REG_SAVE_2WORDS;
1283                       info_ptr->save_p[regno+1] = REG_SAVE_NO_SAVE;
1284                     }
1285                 }
1286             }
1287
1288           reg_ptr->size_1word = size_1word;
1289           reg_ptr->size_2words = size_2words;
1290
1291           if (! reg_ptr->special_p)
1292             {
1293               info_ptr->regs_size_1word += size_1word;
1294               info_ptr->regs_size_2words += size_2words;
1295             }
1296         }
1297     }
1298
1299   /* Set up the sizes of each each field in the frame body, making the sizes
1300      of each be divisible by the size of a dword if dword operations might
1301      be used, or the size of a word otherwise.  */
1302   alignment = (TARGET_DWORD? 2 * UNITS_PER_WORD : UNITS_PER_WORD);
1303
1304   info_ptr->parameter_size = ADDR_ALIGN (crtl->outgoing_args_size, alignment);
1305   info_ptr->regs_size = ADDR_ALIGN (info_ptr->regs_size_2words
1306                                     + info_ptr->regs_size_1word,
1307                                     alignment);
1308   info_ptr->vars_size = ADDR_ALIGN (get_frame_size (), alignment);
1309
1310   info_ptr->pretend_size = crtl->args.pretend_args_size;
1311
1312   /* Work out the size of the frame, excluding the header.  Both the frame
1313      body and register parameter area will be dword-aligned.  */
1314   info_ptr->total_size
1315     = (ADDR_ALIGN (info_ptr->parameter_size
1316                    + info_ptr->regs_size
1317                    + info_ptr->vars_size,
1318                    2 * UNITS_PER_WORD)
1319        + ADDR_ALIGN (info_ptr->pretend_size
1320                      + info_ptr->stdarg_size,
1321                      2 * UNITS_PER_WORD));
1322
1323   /* See if we need to create a frame at all, if so add header area.  */
1324   if (info_ptr->total_size  > 0
1325       || frame_pointer_needed
1326       || info_ptr->regs[STACK_REGS_LR].size_1word > 0
1327       || info_ptr->regs[STACK_REGS_STRUCT].size_1word > 0)
1328     {
1329       offset = info_ptr->parameter_size;
1330       info_ptr->header_size = 4 * UNITS_PER_WORD;
1331       info_ptr->total_size += 4 * UNITS_PER_WORD;
1332
1333       /* Calculate the offsets to save normal register pairs.  */
1334       for (range = 0; range < STACK_REGS_MAX; range++)
1335         {
1336           frv_stack_regs_t *reg_ptr = &(info_ptr->regs[range]);
1337           if (! reg_ptr->special_p)
1338             {
1339               int first = reg_ptr->first;
1340               int last = reg_ptr->last;
1341               int regno;
1342
1343               for (regno = first; regno <= last; regno++)
1344                 if (info_ptr->save_p[regno] == REG_SAVE_2WORDS
1345                     && regno != FRAME_POINTER_REGNUM
1346                     && (regno < FIRST_ARG_REGNUM
1347                         || regno > LAST_ARG_REGNUM))
1348                   {
1349                     info_ptr->reg_offset[regno] = offset;
1350                     offset += 2 * UNITS_PER_WORD;
1351                   }
1352             }
1353         }
1354
1355       /* Calculate the offsets to save normal single registers.  */
1356       for (range = 0; range < STACK_REGS_MAX; range++)
1357         {
1358           frv_stack_regs_t *reg_ptr = &(info_ptr->regs[range]);
1359           if (! reg_ptr->special_p)
1360             {
1361               int first = reg_ptr->first;
1362               int last = reg_ptr->last;
1363               int regno;
1364
1365               for (regno = first; regno <= last; regno++)
1366                 if (info_ptr->save_p[regno] == REG_SAVE_1WORD
1367                     && regno != FRAME_POINTER_REGNUM
1368                     && (regno < FIRST_ARG_REGNUM
1369                         || regno > LAST_ARG_REGNUM))
1370                   {
1371                     info_ptr->reg_offset[regno] = offset;
1372                     offset += UNITS_PER_WORD;
1373                   }
1374             }
1375         }
1376
1377       /* Calculate the offset to save the local variables at.  */
1378       offset = ADDR_ALIGN (offset, alignment);
1379       if (info_ptr->vars_size)
1380         {
1381           info_ptr->vars_offset = offset;
1382           offset += info_ptr->vars_size;
1383         }
1384
1385       /* Align header to a dword-boundary.  */
1386       offset = ADDR_ALIGN (offset, 2 * UNITS_PER_WORD);
1387
1388       /* Calculate the offsets in the fixed frame.  */
1389       info_ptr->save_p[FRAME_POINTER_REGNUM] = REG_SAVE_1WORD;
1390       info_ptr->reg_offset[FRAME_POINTER_REGNUM] = offset;
1391       info_ptr->regs[STACK_REGS_FP].size_1word = UNITS_PER_WORD;
1392
1393       info_ptr->save_p[LR_REGNO] = REG_SAVE_1WORD;
1394       info_ptr->reg_offset[LR_REGNO] = offset + 2*UNITS_PER_WORD;
1395       info_ptr->regs[STACK_REGS_LR].size_1word = UNITS_PER_WORD;
1396
1397       if (cfun->returns_struct)
1398         {
1399           info_ptr->save_p[FRV_STRUCT_VALUE_REGNUM] = REG_SAVE_1WORD;
1400           info_ptr->reg_offset[FRV_STRUCT_VALUE_REGNUM] = offset + UNITS_PER_WORD;
1401           info_ptr->regs[STACK_REGS_STRUCT].size_1word = UNITS_PER_WORD;
1402         }
1403
1404       /* Calculate the offsets to store the arguments passed in registers
1405          for stdarg functions.  The register pairs are first and the single
1406          register if any is last.  The register save area starts on a
1407          dword-boundary.  */
1408       if (info_ptr->stdarg_size)
1409         {
1410           int first = info_ptr->regs[STACK_REGS_STDARG].first;
1411           int last  = info_ptr->regs[STACK_REGS_STDARG].last;
1412           int regno;
1413
1414           /* Skip the header.  */
1415           offset += 4 * UNITS_PER_WORD;
1416           for (regno = first; regno <= last; regno++)
1417             {
1418               if (info_ptr->save_p[regno] == REG_SAVE_2WORDS)
1419                 {
1420                   info_ptr->reg_offset[regno] = offset;
1421                   offset += 2 * UNITS_PER_WORD;
1422                 }
1423               else if (info_ptr->save_p[regno] == REG_SAVE_1WORD)
1424                 {
1425                   info_ptr->reg_offset[regno] = offset;
1426                   offset += UNITS_PER_WORD;
1427                 }
1428             }
1429         }
1430     }
1431
1432   if (reload_completed)
1433     frv_stack_cache = info_ptr;
1434
1435   return info_ptr;
1436 }
1437
1438 \f
1439 /* Print the information about the frv stack offsets, etc. when debugging.  */
1440
1441 void
1442 frv_debug_stack (frv_stack_t *info)
1443 {
1444   int range;
1445
1446   if (!info)
1447     info = frv_stack_info ();
1448
1449   fprintf (stderr, "\nStack information for function %s:\n",
1450            ((current_function_decl && DECL_NAME (current_function_decl))
1451             ? IDENTIFIER_POINTER (DECL_NAME (current_function_decl))
1452             : "<unknown>"));
1453
1454   fprintf (stderr, "\ttotal_size\t= %6d\n", info->total_size);
1455   fprintf (stderr, "\tvars_size\t= %6d\n", info->vars_size);
1456   fprintf (stderr, "\tparam_size\t= %6d\n", info->parameter_size);
1457   fprintf (stderr, "\tregs_size\t= %6d, 1w = %3d, 2w = %3d\n",
1458            info->regs_size, info->regs_size_1word, info->regs_size_2words);
1459
1460   fprintf (stderr, "\theader_size\t= %6d\n", info->header_size);
1461   fprintf (stderr, "\tpretend_size\t= %6d\n", info->pretend_size);
1462   fprintf (stderr, "\tvars_offset\t= %6d\n", info->vars_offset);
1463   fprintf (stderr, "\tregs_offset\t= %6d\n", info->regs_offset);
1464
1465   for (range = 0; range < STACK_REGS_MAX; range++)
1466     {
1467       frv_stack_regs_t *regs = &(info->regs[range]);
1468       if ((regs->size_1word + regs->size_2words) > 0)
1469         {
1470           int first = regs->first;
1471           int last  = regs->last;
1472           int regno;
1473
1474           fprintf (stderr, "\t%s\tsize\t= %6d, 1w = %3d, 2w = %3d, save =",
1475                    regs->name, regs->size_1word + regs->size_2words,
1476                    regs->size_1word, regs->size_2words);
1477
1478           for (regno = first; regno <= last; regno++)
1479             {
1480               if (info->save_p[regno] == REG_SAVE_1WORD)
1481                 fprintf (stderr, " %s (%d)", reg_names[regno],
1482                          info->reg_offset[regno]);
1483
1484               else if (info->save_p[regno] == REG_SAVE_2WORDS)
1485                 fprintf (stderr, " %s-%s (%d)", reg_names[regno],
1486                          reg_names[regno+1], info->reg_offset[regno]);
1487             }
1488
1489           fputc ('\n', stderr);
1490         }
1491     }
1492
1493   fflush (stderr);
1494 }
1495
1496
1497 \f
1498
1499 /* Used during final to control the packing of insns.  The value is
1500    1 if the current instruction should be packed with the next one,
1501    0 if it shouldn't or -1 if packing is disabled altogether.  */
1502
1503 static int frv_insn_packing_flag;
1504
1505 /* True if the current function contains a far jump.  */
1506
1507 static int
1508 frv_function_contains_far_jump (void)
1509 {
1510   rtx insn = get_insns ();
1511   while (insn != NULL
1512          && !(GET_CODE (insn) == JUMP_INSN
1513               /* Ignore tablejump patterns.  */
1514               && GET_CODE (PATTERN (insn)) != ADDR_VEC
1515               && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
1516               && get_attr_far_jump (insn) == FAR_JUMP_YES))
1517     insn = NEXT_INSN (insn);
1518   return (insn != NULL);
1519 }
1520
1521 /* For the FRV, this function makes sure that a function with far jumps
1522    will return correctly.  It also does the VLIW packing.  */
1523
1524 static void
1525 frv_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
1526 {
1527   /* If no frame was created, check whether the function uses a call
1528      instruction to implement a far jump.  If so, save the link in gr3 and
1529      replace all returns to LR with returns to GR3.  GR3 is used because it
1530      is call-clobbered, because is not available to the register allocator,
1531      and because all functions that take a hidden argument pointer will have
1532      a stack frame.  */
1533   if (frv_stack_info ()->total_size == 0 && frv_function_contains_far_jump ())
1534     {
1535       rtx insn;
1536
1537       /* Just to check that the above comment is true.  */
1538       gcc_assert (!df_regs_ever_live_p (GPR_FIRST + 3));
1539
1540       /* Generate the instruction that saves the link register.  */
1541       fprintf (file, "\tmovsg lr,gr3\n");
1542
1543       /* Replace the LR with GR3 in *return_internal patterns.  The insn
1544          will now return using jmpl @(gr3,0) rather than bralr.  We cannot
1545          simply emit a different assembly directive because bralr and jmpl
1546          execute in different units.  */
1547       for (insn = get_insns(); insn != NULL; insn = NEXT_INSN (insn))
1548         if (GET_CODE (insn) == JUMP_INSN)
1549           {
1550             rtx pattern = PATTERN (insn);
1551             if (GET_CODE (pattern) == PARALLEL
1552                 && XVECLEN (pattern, 0) >= 2
1553                 && GET_CODE (XVECEXP (pattern, 0, 0)) == RETURN
1554                 && GET_CODE (XVECEXP (pattern, 0, 1)) == USE)
1555               {
1556                 rtx address = XEXP (XVECEXP (pattern, 0, 1), 0);
1557                 if (GET_CODE (address) == REG && REGNO (address) == LR_REGNO)
1558                   SET_REGNO (address, GPR_FIRST + 3);
1559               }
1560           }
1561     }
1562
1563   frv_pack_insns ();
1564
1565   /* Allow the garbage collector to free the nops created by frv_reorg.  */
1566   memset (frv_nops, 0, sizeof (frv_nops));
1567 }
1568
1569 \f
1570 /* Return the next available temporary register in a given class.  */
1571
1572 static rtx
1573 frv_alloc_temp_reg (
1574      frv_tmp_reg_t *info,       /* which registers are available */
1575      enum reg_class rclass,     /* register class desired */
1576      enum machine_mode mode,    /* mode to allocate register with */
1577      int mark_as_used,          /* register not available after allocation */
1578      int no_abort)              /* return NULL instead of aborting */
1579 {
1580   int regno = info->next_reg[ (int)rclass ];
1581   int orig_regno = regno;
1582   HARD_REG_SET *reg_in_class = &reg_class_contents[ (int)rclass ];
1583   int i, nr;
1584
1585   for (;;)
1586     {
1587       if (TEST_HARD_REG_BIT (*reg_in_class, regno)
1588           && TEST_HARD_REG_BIT (info->regs, regno))
1589           break;
1590
1591       if (++regno >= FIRST_PSEUDO_REGISTER)
1592         regno = 0;
1593       if (regno == orig_regno)
1594         {
1595           gcc_assert (no_abort);
1596           return NULL_RTX;
1597         }
1598     }
1599
1600   nr = HARD_REGNO_NREGS (regno, mode);
1601   info->next_reg[ (int)rclass ] = regno + nr;
1602
1603   if (mark_as_used)
1604     for (i = 0; i < nr; i++)
1605       CLEAR_HARD_REG_BIT (info->regs, regno+i);
1606
1607   return gen_rtx_REG (mode, regno);
1608 }
1609
1610 \f
1611 /* Return an rtx with the value OFFSET, which will either be a register or a
1612    signed 12-bit integer.  It can be used as the second operand in an "add"
1613    instruction, or as the index in a load or store.
1614
1615    The function returns a constant rtx if OFFSET is small enough, otherwise
1616    it loads the constant into register OFFSET_REGNO and returns that.  */
1617 static rtx
1618 frv_frame_offset_rtx (int offset)
1619 {
1620   rtx offset_rtx = GEN_INT (offset);
1621   if (IN_RANGE_P (offset, -2048, 2047))
1622     return offset_rtx;
1623   else
1624     {
1625       rtx reg_rtx = gen_rtx_REG (SImode, OFFSET_REGNO);
1626       if (IN_RANGE_P (offset, -32768, 32767))
1627         emit_insn (gen_movsi (reg_rtx, offset_rtx));
1628       else
1629         {
1630           emit_insn (gen_movsi_high (reg_rtx, offset_rtx));
1631           emit_insn (gen_movsi_lo_sum (reg_rtx, offset_rtx));
1632         }
1633       return reg_rtx;
1634     }
1635 }
1636
1637 /* Generate (mem:MODE (plus:Pmode BASE (frv_frame_offset OFFSET)))).  The
1638    prologue and epilogue uses such expressions to access the stack.  */
1639 static rtx
1640 frv_frame_mem (enum machine_mode mode, rtx base, int offset)
1641 {
1642   return gen_rtx_MEM (mode, gen_rtx_PLUS (Pmode,
1643                                           base,
1644                                           frv_frame_offset_rtx (offset)));
1645 }
1646
1647 /* Generate a frame-related expression:
1648
1649         (set REG (mem (plus (sp) (const_int OFFSET)))).
1650
1651    Such expressions are used in FRAME_RELATED_EXPR notes for more complex
1652    instructions.  Marking the expressions as frame-related is superfluous if
1653    the note contains just a single set.  But if the note contains a PARALLEL
1654    or SEQUENCE that has several sets, each set must be individually marked
1655    as frame-related.  */
1656 static rtx
1657 frv_dwarf_store (rtx reg, int offset)
1658 {
1659   rtx set = gen_rtx_SET (VOIDmode,
1660                          gen_rtx_MEM (GET_MODE (reg),
1661                                       plus_constant (stack_pointer_rtx,
1662                                                      offset)),
1663                          reg);
1664   RTX_FRAME_RELATED_P (set) = 1;
1665   return set;
1666 }
1667
1668 /* Emit a frame-related instruction whose pattern is PATTERN.  The
1669    instruction is the last in a sequence that cumulatively performs the
1670    operation described by DWARF_PATTERN.  The instruction is marked as
1671    frame-related and has a REG_FRAME_RELATED_EXPR note containing
1672    DWARF_PATTERN.  */
1673 static void
1674 frv_frame_insn (rtx pattern, rtx dwarf_pattern)
1675 {
1676   rtx insn = emit_insn (pattern);
1677   RTX_FRAME_RELATED_P (insn) = 1;
1678   REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
1679                                       dwarf_pattern,
1680                                       REG_NOTES (insn));
1681 }
1682
1683 /* Emit instructions that transfer REG to or from the memory location (sp +
1684    STACK_OFFSET).  The register is stored in memory if ACCESSOR->OP is
1685    FRV_STORE and loaded if it is FRV_LOAD.  Only the prologue uses this
1686    function to store registers and only the epilogue uses it to load them.
1687
1688    The caller sets up ACCESSOR so that BASE is equal to (sp + BASE_OFFSET).
1689    The generated instruction will use BASE as its base register.  BASE may
1690    simply be the stack pointer, but if several accesses are being made to a
1691    region far away from the stack pointer, it may be more efficient to set
1692    up a temporary instead.
1693
1694    Store instructions will be frame-related and will be annotated with the
1695    overall effect of the store.  Load instructions will be followed by a
1696    (use) to prevent later optimizations from zapping them.
1697
1698    The function takes care of the moves to and from SPRs, using TEMP_REGNO
1699    as a temporary in such cases.  */
1700 static void
1701 frv_frame_access (frv_frame_accessor_t *accessor, rtx reg, int stack_offset)
1702 {
1703   enum machine_mode mode = GET_MODE (reg);
1704   rtx mem = frv_frame_mem (mode,
1705                            accessor->base,
1706                            stack_offset - accessor->base_offset);
1707
1708   if (accessor->op == FRV_LOAD)
1709     {
1710       if (SPR_P (REGNO (reg)))
1711         {
1712           rtx temp = gen_rtx_REG (mode, TEMP_REGNO);
1713           emit_insn (gen_rtx_SET (VOIDmode, temp, mem));
1714           emit_insn (gen_rtx_SET (VOIDmode, reg, temp));
1715         }
1716       else
1717         {
1718           /* We cannot use reg+reg addressing for DImode access.  */
1719           if (mode == DImode
1720               && GET_CODE (XEXP (mem, 0)) == PLUS
1721               && GET_CODE (XEXP (XEXP (mem, 0), 0)) == REG
1722               && GET_CODE (XEXP (XEXP (mem, 0), 1)) == REG)
1723             {
1724               rtx temp = gen_rtx_REG (SImode, TEMP_REGNO);
1725
1726               emit_move_insn (temp,
1727                               gen_rtx_PLUS (SImode, XEXP (XEXP (mem, 0), 0),
1728                                             XEXP (XEXP (mem, 0), 1)));
1729               mem = gen_rtx_MEM (DImode, temp);
1730             }
1731           emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
1732         }
1733       emit_use (reg);
1734     }
1735   else
1736     {
1737       if (SPR_P (REGNO (reg)))
1738         {
1739           rtx temp = gen_rtx_REG (mode, TEMP_REGNO);
1740           emit_insn (gen_rtx_SET (VOIDmode, temp, reg));
1741           frv_frame_insn (gen_rtx_SET (Pmode, mem, temp),
1742                           frv_dwarf_store (reg, stack_offset));
1743         }
1744       else if (mode == DImode)
1745         {
1746           /* For DImode saves, the dwarf2 version needs to be a SEQUENCE
1747              with a separate save for each register.  */
1748           rtx reg1 = gen_rtx_REG (SImode, REGNO (reg));
1749           rtx reg2 = gen_rtx_REG (SImode, REGNO (reg) + 1);
1750           rtx set1 = frv_dwarf_store (reg1, stack_offset);
1751           rtx set2 = frv_dwarf_store (reg2, stack_offset + 4);
1752
1753           /* Also we cannot use reg+reg addressing.  */
1754           if (GET_CODE (XEXP (mem, 0)) == PLUS
1755               && GET_CODE (XEXP (XEXP (mem, 0), 0)) == REG
1756               && GET_CODE (XEXP (XEXP (mem, 0), 1)) == REG)
1757             {
1758               rtx temp = gen_rtx_REG (SImode, TEMP_REGNO);
1759               emit_move_insn (temp,
1760                               gen_rtx_PLUS (SImode, XEXP (XEXP (mem, 0), 0),
1761                                             XEXP (XEXP (mem, 0), 1)));
1762               mem = gen_rtx_MEM (DImode, temp);
1763             }
1764
1765           frv_frame_insn (gen_rtx_SET (Pmode, mem, reg),
1766                           gen_rtx_PARALLEL (VOIDmode,
1767                                             gen_rtvec (2, set1, set2)));
1768         }
1769       else
1770         frv_frame_insn (gen_rtx_SET (Pmode, mem, reg),
1771                         frv_dwarf_store (reg, stack_offset));
1772     }
1773 }
1774
1775 /* A function that uses frv_frame_access to transfer a group of registers to
1776    or from the stack.  ACCESSOR is passed directly to frv_frame_access, INFO
1777    is the stack information generated by frv_stack_info, and REG_SET is the
1778    number of the register set to transfer.  */
1779 static void
1780 frv_frame_access_multi (frv_frame_accessor_t *accessor,
1781                         frv_stack_t *info,
1782                         int reg_set)
1783 {
1784   frv_stack_regs_t *regs_info;
1785   int regno;
1786
1787   regs_info = &info->regs[reg_set];
1788   for (regno = regs_info->first; regno <= regs_info->last; regno++)
1789     if (info->save_p[regno])
1790       frv_frame_access (accessor,
1791                         info->save_p[regno] == REG_SAVE_2WORDS
1792                         ? gen_rtx_REG (DImode, regno)
1793                         : gen_rtx_REG (SImode, regno),
1794                         info->reg_offset[regno]);
1795 }
1796
1797 /* Save or restore callee-saved registers that are kept outside the frame
1798    header.  The function saves the registers if OP is FRV_STORE and restores
1799    them if OP is FRV_LOAD.  INFO is the stack information generated by
1800    frv_stack_info.  */
1801 static void
1802 frv_frame_access_standard_regs (enum frv_stack_op op, frv_stack_t *info)
1803 {
1804   frv_frame_accessor_t accessor;
1805
1806   accessor.op = op;
1807   accessor.base = stack_pointer_rtx;
1808   accessor.base_offset = 0;
1809   frv_frame_access_multi (&accessor, info, STACK_REGS_GPR);
1810   frv_frame_access_multi (&accessor, info, STACK_REGS_FPR);
1811   frv_frame_access_multi (&accessor, info, STACK_REGS_LCR);
1812 }
1813
1814
1815 /* Called after register allocation to add any instructions needed for the
1816    prologue.  Using a prologue insn is favored compared to putting all of the
1817    instructions in the TARGET_ASM_FUNCTION_PROLOGUE target hook, since
1818    it allows the scheduler to intermix instructions with the saves of
1819    the caller saved registers.  In some cases, it might be necessary
1820    to emit a barrier instruction as the last insn to prevent such
1821    scheduling.
1822
1823    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
1824    so that the debug info generation code can handle them properly.  */
1825 void
1826 frv_expand_prologue (void)
1827 {
1828   frv_stack_t *info = frv_stack_info ();
1829   rtx sp = stack_pointer_rtx;
1830   rtx fp = frame_pointer_rtx;
1831   frv_frame_accessor_t accessor;
1832
1833   if (TARGET_DEBUG_STACK)
1834     frv_debug_stack (info);
1835
1836   if (info->total_size == 0)
1837     return;
1838
1839   /* We're interested in three areas of the frame here:
1840
1841          A: the register save area
1842          B: the old FP
1843          C: the header after B
1844
1845      If the frame pointer isn't used, we'll have to set up A, B and C
1846      using the stack pointer.  If the frame pointer is used, we'll access
1847      them as follows:
1848
1849          A: set up using sp
1850          B: set up using sp or a temporary (see below)
1851          C: set up using fp
1852
1853      We set up B using the stack pointer if the frame is small enough.
1854      Otherwise, it's more efficient to copy the old stack pointer into a
1855      temporary and use that.
1856
1857      Note that it's important to make sure the prologue and epilogue use the
1858      same registers to access A and C, since doing otherwise will confuse
1859      the aliasing code.  */
1860
1861   /* Set up ACCESSOR for accessing region B above.  If the frame pointer
1862      isn't used, the same method will serve for C.  */
1863   accessor.op = FRV_STORE;
1864   if (frame_pointer_needed && info->total_size > 2048)
1865     {
1866       accessor.base = gen_rtx_REG (Pmode, OLD_SP_REGNO);
1867       accessor.base_offset = info->total_size;
1868       emit_insn (gen_movsi (accessor.base, sp));
1869     }
1870   else
1871     {
1872       accessor.base = stack_pointer_rtx;
1873       accessor.base_offset = 0;
1874     }
1875
1876   /* Allocate the stack space.  */
1877   {
1878     rtx asm_offset = frv_frame_offset_rtx (-info->total_size);
1879     rtx dwarf_offset = GEN_INT (-info->total_size);
1880
1881     frv_frame_insn (gen_stack_adjust (sp, sp, asm_offset),
1882                     gen_rtx_SET (Pmode,
1883                                  sp,
1884                                  gen_rtx_PLUS (Pmode, sp, dwarf_offset)));
1885   }
1886
1887   /* If the frame pointer is needed, store the old one at (sp + FP_OFFSET)
1888      and point the new one to that location.  */
1889   if (frame_pointer_needed)
1890     {
1891       int fp_offset = info->reg_offset[FRAME_POINTER_REGNUM];
1892
1893       /* ASM_SRC and DWARF_SRC both point to the frame header.  ASM_SRC is
1894          based on ACCESSOR.BASE but DWARF_SRC is always based on the stack
1895          pointer.  */
1896       rtx asm_src = plus_constant (accessor.base,
1897                                    fp_offset - accessor.base_offset);
1898       rtx dwarf_src = plus_constant (sp, fp_offset);
1899
1900       /* Store the old frame pointer at (sp + FP_OFFSET).  */
1901       frv_frame_access (&accessor, fp, fp_offset);
1902
1903       /* Set up the new frame pointer.  */
1904       frv_frame_insn (gen_rtx_SET (VOIDmode, fp, asm_src),
1905                       gen_rtx_SET (VOIDmode, fp, dwarf_src));
1906
1907       /* Access region C from the frame pointer.  */
1908       accessor.base = fp;
1909       accessor.base_offset = fp_offset;
1910     }
1911
1912   /* Set up region C.  */
1913   frv_frame_access_multi (&accessor, info, STACK_REGS_STRUCT);
1914   frv_frame_access_multi (&accessor, info, STACK_REGS_LR);
1915   frv_frame_access_multi (&accessor, info, STACK_REGS_STDARG);
1916
1917   /* Set up region A.  */
1918   frv_frame_access_standard_regs (FRV_STORE, info);
1919
1920   /* If this is a varargs/stdarg function, issue a blockage to prevent the
1921      scheduler from moving loads before the stores saving the registers.  */
1922   if (info->stdarg_size > 0)
1923     emit_insn (gen_blockage ());
1924
1925   /* Set up pic register/small data register for this function.  */
1926   if (!TARGET_FDPIC && flag_pic && crtl->uses_pic_offset_table)
1927     emit_insn (gen_pic_prologue (gen_rtx_REG (Pmode, PIC_REGNO),
1928                                  gen_rtx_REG (Pmode, LR_REGNO),
1929                                  gen_rtx_REG (SImode, OFFSET_REGNO)));
1930 }
1931
1932 \f
1933 /* Under frv, all of the work is done via frv_expand_epilogue, but
1934    this function provides a convenient place to do cleanup.  */
1935
1936 static void
1937 frv_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
1938                        HOST_WIDE_INT size ATTRIBUTE_UNUSED)
1939 {
1940   frv_stack_cache = (frv_stack_t *)0;
1941
1942   /* Zap last used registers for conditional execution.  */
1943   memset (&frv_ifcvt.tmp_reg, 0, sizeof (frv_ifcvt.tmp_reg));
1944
1945   /* Release the bitmap of created insns.  */
1946   BITMAP_FREE (frv_ifcvt.scratch_insns_bitmap);
1947 }
1948
1949 \f
1950 /* Called after register allocation to add any instructions needed for the
1951    epilogue.  Using an epilogue insn is favored compared to putting all of the
1952    instructions in the TARGET_ASM_FUNCTION_PROLOGUE target hook, since
1953    it allows the scheduler to intermix instructions with the saves of
1954    the caller saved registers.  In some cases, it might be necessary
1955    to emit a barrier instruction as the last insn to prevent such
1956    scheduling.  */
1957
1958 void
1959 frv_expand_epilogue (bool emit_return)
1960 {
1961   frv_stack_t *info = frv_stack_info ();
1962   rtx fp = frame_pointer_rtx;
1963   rtx sp = stack_pointer_rtx;
1964   rtx return_addr;
1965   int fp_offset;
1966
1967   fp_offset = info->reg_offset[FRAME_POINTER_REGNUM];
1968
1969   /* Restore the stack pointer to its original value if alloca or the like
1970      is used.  */
1971   if (! current_function_sp_is_unchanging)
1972     emit_insn (gen_addsi3 (sp, fp, frv_frame_offset_rtx (-fp_offset)));
1973
1974   /* Restore the callee-saved registers that were used in this function.  */
1975   frv_frame_access_standard_regs (FRV_LOAD, info);
1976
1977   /* Set RETURN_ADDR to the address we should return to.  Set it to NULL if
1978      no return instruction should be emitted.  */
1979   if (info->save_p[LR_REGNO])
1980     {
1981       int lr_offset;
1982       rtx mem;
1983
1984       /* Use the same method to access the link register's slot as we did in
1985          the prologue.  In other words, use the frame pointer if available,
1986          otherwise use the stack pointer.
1987
1988          LR_OFFSET is the offset of the link register's slot from the start
1989          of the frame and MEM is a memory rtx for it.  */
1990       lr_offset = info->reg_offset[LR_REGNO];
1991       if (frame_pointer_needed)
1992         mem = frv_frame_mem (Pmode, fp, lr_offset - fp_offset);
1993       else
1994         mem = frv_frame_mem (Pmode, sp, lr_offset);
1995
1996       /* Load the old link register into a GPR.  */
1997       return_addr = gen_rtx_REG (Pmode, TEMP_REGNO);
1998       emit_insn (gen_rtx_SET (VOIDmode, return_addr, mem));
1999     }
2000   else
2001     return_addr = gen_rtx_REG (Pmode, LR_REGNO);
2002
2003   /* Restore the old frame pointer.  Emit a USE afterwards to make sure
2004      the load is preserved.  */
2005   if (frame_pointer_needed)
2006     {
2007       emit_insn (gen_rtx_SET (VOIDmode, fp, gen_rtx_MEM (Pmode, fp)));
2008       emit_use (fp);
2009     }
2010
2011   /* Deallocate the stack frame.  */
2012   if (info->total_size != 0)
2013     {
2014       rtx offset = frv_frame_offset_rtx (info->total_size);
2015       emit_insn (gen_stack_adjust (sp, sp, offset));
2016     }
2017
2018   /* If this function uses eh_return, add the final stack adjustment now.  */
2019   if (crtl->calls_eh_return)
2020     emit_insn (gen_stack_adjust (sp, sp, EH_RETURN_STACKADJ_RTX));
2021
2022   if (emit_return)
2023     emit_jump_insn (gen_epilogue_return (return_addr));
2024   else
2025     {
2026       rtx lr = return_addr;
2027
2028       if (REGNO (return_addr) != LR_REGNO)
2029         {
2030           lr = gen_rtx_REG (Pmode, LR_REGNO);
2031           emit_move_insn (lr, return_addr);
2032         }
2033
2034       emit_use (lr);
2035     }
2036 }
2037
2038 \f
2039 /* Worker function for TARGET_ASM_OUTPUT_MI_THUNK.  */
2040
2041 static void
2042 frv_asm_output_mi_thunk (FILE *file,
2043                          tree thunk_fndecl ATTRIBUTE_UNUSED,
2044                          HOST_WIDE_INT delta,
2045                          HOST_WIDE_INT vcall_offset ATTRIBUTE_UNUSED,
2046                          tree function)
2047 {
2048   const char *name_func = XSTR (XEXP (DECL_RTL (function), 0), 0);
2049   const char *name_arg0 = reg_names[FIRST_ARG_REGNUM];
2050   const char *name_jmp = reg_names[JUMP_REGNO];
2051   const char *parallel = (frv_issue_rate () > 1 ? ".p" : "");
2052
2053   /* Do the add using an addi if possible.  */
2054   if (IN_RANGE_P (delta, -2048, 2047))
2055     fprintf (file, "\taddi %s,#%d,%s\n", name_arg0, (int) delta, name_arg0);
2056   else
2057     {
2058       const char *const name_add = reg_names[TEMP_REGNO];
2059       fprintf (file, "\tsethi%s #hi(" HOST_WIDE_INT_PRINT_DEC "),%s\n",
2060                parallel, delta, name_add);
2061       fprintf (file, "\tsetlo #lo(" HOST_WIDE_INT_PRINT_DEC "),%s\n",
2062                delta, name_add);
2063       fprintf (file, "\tadd %s,%s,%s\n", name_add, name_arg0, name_arg0);
2064     }
2065
2066   if (TARGET_FDPIC)
2067     {
2068       const char *name_pic = reg_names[FDPIC_REGNO];
2069       name_jmp = reg_names[FDPIC_FPTR_REGNO];
2070
2071       if (flag_pic != 1)
2072         {
2073           fprintf (file, "\tsethi%s #gotofffuncdeschi(", parallel);
2074           assemble_name (file, name_func);
2075           fprintf (file, "),%s\n", name_jmp);
2076
2077           fprintf (file, "\tsetlo #gotofffuncdesclo(");
2078           assemble_name (file, name_func);
2079           fprintf (file, "),%s\n", name_jmp);
2080
2081           fprintf (file, "\tldd @(%s,%s), %s\n", name_jmp, name_pic, name_jmp);
2082         }
2083       else
2084         {
2085           fprintf (file, "\tlddo @(%s,#gotofffuncdesc12(", name_pic);
2086           assemble_name (file, name_func);
2087           fprintf (file, "\t)), %s\n", name_jmp);
2088         }
2089     }
2090   else if (!flag_pic)
2091     {
2092       fprintf (file, "\tsethi%s #hi(", parallel);
2093       assemble_name (file, name_func);
2094       fprintf (file, "),%s\n", name_jmp);
2095
2096       fprintf (file, "\tsetlo #lo(");
2097       assemble_name (file, name_func);
2098       fprintf (file, "),%s\n", name_jmp);
2099     }
2100   else
2101     {
2102       /* Use JUMP_REGNO as a temporary PIC register.  */
2103       const char *name_lr = reg_names[LR_REGNO];
2104       const char *name_gppic = name_jmp;
2105       const char *name_tmp = reg_names[TEMP_REGNO];
2106
2107       fprintf (file, "\tmovsg %s,%s\n", name_lr, name_tmp);
2108       fprintf (file, "\tcall 1f\n");
2109       fprintf (file, "1:\tmovsg %s,%s\n", name_lr, name_gppic);
2110       fprintf (file, "\tmovgs %s,%s\n", name_tmp, name_lr);
2111       fprintf (file, "\tsethi%s #gprelhi(1b),%s\n", parallel, name_tmp);
2112       fprintf (file, "\tsetlo #gprello(1b),%s\n", name_tmp);
2113       fprintf (file, "\tsub %s,%s,%s\n", name_gppic, name_tmp, name_gppic);
2114
2115       fprintf (file, "\tsethi%s #gprelhi(", parallel);
2116       assemble_name (file, name_func);
2117       fprintf (file, "),%s\n", name_tmp);
2118
2119       fprintf (file, "\tsetlo #gprello(");
2120       assemble_name (file, name_func);
2121       fprintf (file, "),%s\n", name_tmp);
2122
2123       fprintf (file, "\tadd %s,%s,%s\n", name_gppic, name_tmp, name_jmp);
2124     }
2125
2126   /* Jump to the function address.  */
2127   fprintf (file, "\tjmpl @(%s,%s)\n", name_jmp, reg_names[GPR_FIRST+0]);
2128 }
2129
2130 \f
2131
2132 /* On frv, create a frame whenever we need to create stack.  */
2133
2134 static bool
2135 frv_frame_pointer_required (void)
2136 {
2137   /* If we forgoing the usual linkage requirements, we only need
2138      a frame pointer if the stack pointer might change.  */
2139   if (!TARGET_LINKED_FP)
2140     return !current_function_sp_is_unchanging;
2141
2142   if (! current_function_is_leaf)
2143     return true;
2144
2145   if (get_frame_size () != 0)
2146     return true;
2147
2148   if (cfun->stdarg)
2149     return true;
2150
2151   if (!current_function_sp_is_unchanging)
2152     return true;
2153
2154   if (!TARGET_FDPIC && flag_pic && crtl->uses_pic_offset_table)
2155     return true;
2156
2157   if (profile_flag)
2158     return true;
2159
2160   if (cfun->machine->frame_needed)
2161     return true;
2162
2163   return false;
2164 }
2165
2166 \f
2167 /* Worker function for TARGET_CAN_ELIMINATE.  */
2168
2169 bool
2170 frv_can_eliminate (const int from, const int to)
2171 {
2172   return (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM
2173           ? ! frame_pointer_needed
2174           : true);
2175 }
2176
2177 /* This macro is similar to `INITIAL_FRAME_POINTER_OFFSET'.  It specifies the
2178    initial difference between the specified pair of registers.  This macro must
2179    be defined if `ELIMINABLE_REGS' is defined.  */
2180
2181 /* See frv_stack_info for more details on the frv stack frame.  */
2182
2183 int
2184 frv_initial_elimination_offset (int from, int to)
2185 {
2186   frv_stack_t *info = frv_stack_info ();
2187   int ret = 0;
2188
2189   if (to == STACK_POINTER_REGNUM && from == ARG_POINTER_REGNUM)
2190     ret = info->total_size - info->pretend_size;
2191
2192   else if (to == STACK_POINTER_REGNUM && from == FRAME_POINTER_REGNUM)
2193     ret = info->reg_offset[FRAME_POINTER_REGNUM];
2194
2195   else if (to == FRAME_POINTER_REGNUM && from == ARG_POINTER_REGNUM)
2196     ret = (info->total_size
2197            - info->reg_offset[FRAME_POINTER_REGNUM]
2198            - info->pretend_size);
2199
2200   else
2201     gcc_unreachable ();
2202
2203   if (TARGET_DEBUG_STACK)
2204     fprintf (stderr, "Eliminate %s to %s by adding %d\n",
2205              reg_names [from], reg_names[to], ret);
2206
2207   return ret;
2208 }
2209
2210 \f
2211 /* Worker function for TARGET_SETUP_INCOMING_VARARGS.  */
2212
2213 static void
2214 frv_setup_incoming_varargs (CUMULATIVE_ARGS *cum,
2215                             enum machine_mode mode,
2216                             tree type ATTRIBUTE_UNUSED,
2217                             int *pretend_size,
2218                             int second_time)
2219 {
2220   if (TARGET_DEBUG_ARG)
2221     fprintf (stderr,
2222              "setup_vararg: words = %2d, mode = %4s, pretend_size = %d, second_time = %d\n",
2223              *cum, GET_MODE_NAME (mode), *pretend_size, second_time);
2224 }
2225
2226 \f
2227 /* Worker function for TARGET_EXPAND_BUILTIN_SAVEREGS.  */
2228
2229 static rtx
2230 frv_expand_builtin_saveregs (void)
2231 {
2232   int offset = UNITS_PER_WORD * FRV_NUM_ARG_REGS;
2233
2234   if (TARGET_DEBUG_ARG)
2235     fprintf (stderr, "expand_builtin_saveregs: offset from ap = %d\n",
2236              offset);
2237
2238   return gen_rtx_PLUS (Pmode, virtual_incoming_args_rtx, GEN_INT (- offset));
2239 }
2240
2241 \f
2242 /* Expand __builtin_va_start to do the va_start macro.  */
2243
2244 static void
2245 frv_expand_builtin_va_start (tree valist, rtx nextarg)
2246 {
2247   tree t;
2248   int num = crtl->args.info - FIRST_ARG_REGNUM - FRV_NUM_ARG_REGS;
2249
2250   nextarg = gen_rtx_PLUS (Pmode, virtual_incoming_args_rtx,
2251                           GEN_INT (UNITS_PER_WORD * num));
2252
2253   if (TARGET_DEBUG_ARG)
2254     {
2255       fprintf (stderr, "va_start: args_info = %d, num = %d\n",
2256                crtl->args.info, num);
2257
2258       debug_rtx (nextarg);
2259     }
2260
2261   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist,
2262               fold_convert (TREE_TYPE (valist),
2263                             make_tree (sizetype, nextarg)));
2264   TREE_SIDE_EFFECTS (t) = 1;
2265
2266   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
2267 }
2268
2269 \f
2270 /* Expand a block move operation, and return 1 if successful.  Return 0
2271    if we should let the compiler generate normal code.
2272
2273    operands[0] is the destination
2274    operands[1] is the source
2275    operands[2] is the length
2276    operands[3] is the alignment */
2277
2278 /* Maximum number of loads to do before doing the stores */
2279 #ifndef MAX_MOVE_REG
2280 #define MAX_MOVE_REG 4
2281 #endif
2282
2283 /* Maximum number of total loads to do.  */
2284 #ifndef TOTAL_MOVE_REG
2285 #define TOTAL_MOVE_REG 8
2286 #endif
2287
2288 int
2289 frv_expand_block_move (rtx operands[])
2290 {
2291   rtx orig_dest = operands[0];
2292   rtx orig_src  = operands[1];
2293   rtx bytes_rtx = operands[2];
2294   rtx align_rtx = operands[3];
2295   int constp    = (GET_CODE (bytes_rtx) == CONST_INT);
2296   int align;
2297   int bytes;
2298   int offset;
2299   int num_reg;
2300   int i;
2301   rtx src_reg;
2302   rtx dest_reg;
2303   rtx src_addr;
2304   rtx dest_addr;
2305   rtx src_mem;
2306   rtx dest_mem;
2307   rtx tmp_reg;
2308   rtx stores[MAX_MOVE_REG];
2309   int move_bytes;
2310   enum machine_mode mode;
2311
2312   /* If this is not a fixed size move, just call memcpy.  */
2313   if (! constp)
2314     return FALSE;
2315
2316   /* This should be a fixed size alignment.  */
2317   gcc_assert (GET_CODE (align_rtx) == CONST_INT);
2318
2319   align = INTVAL (align_rtx);
2320
2321   /* Anything to move? */
2322   bytes = INTVAL (bytes_rtx);
2323   if (bytes <= 0)
2324     return TRUE;
2325
2326   /* Don't support real large moves.  */
2327   if (bytes > TOTAL_MOVE_REG*align)
2328     return FALSE;
2329
2330   /* Move the address into scratch registers.  */
2331   dest_reg = copy_addr_to_reg (XEXP (orig_dest, 0));
2332   src_reg  = copy_addr_to_reg (XEXP (orig_src,  0));
2333
2334   num_reg = offset = 0;
2335   for ( ; bytes > 0; (bytes -= move_bytes), (offset += move_bytes))
2336     {
2337       /* Calculate the correct offset for src/dest.  */
2338       if (offset == 0)
2339         {
2340           src_addr  = src_reg;
2341           dest_addr = dest_reg;
2342         }
2343       else
2344         {
2345           src_addr = plus_constant (src_reg, offset);
2346           dest_addr = plus_constant (dest_reg, offset);
2347         }
2348
2349       /* Generate the appropriate load and store, saving the stores
2350          for later.  */
2351       if (bytes >= 4 && align >= 4)
2352         mode = SImode;
2353       else if (bytes >= 2 && align >= 2)
2354         mode = HImode;
2355       else
2356         mode = QImode;
2357
2358       move_bytes = GET_MODE_SIZE (mode);
2359       tmp_reg = gen_reg_rtx (mode);
2360       src_mem = change_address (orig_src, mode, src_addr);
2361       dest_mem = change_address (orig_dest, mode, dest_addr);
2362       emit_insn (gen_rtx_SET (VOIDmode, tmp_reg, src_mem));
2363       stores[num_reg++] = gen_rtx_SET (VOIDmode, dest_mem, tmp_reg);
2364
2365       if (num_reg >= MAX_MOVE_REG)
2366         {
2367           for (i = 0; i < num_reg; i++)
2368             emit_insn (stores[i]);
2369           num_reg = 0;
2370         }
2371     }
2372
2373   for (i = 0; i < num_reg; i++)
2374     emit_insn (stores[i]);
2375
2376   return TRUE;
2377 }
2378
2379 \f
2380 /* Expand a block clear operation, and return 1 if successful.  Return 0
2381    if we should let the compiler generate normal code.
2382
2383    operands[0] is the destination
2384    operands[1] is the length
2385    operands[3] is the alignment */
2386
2387 int
2388 frv_expand_block_clear (rtx operands[])
2389 {
2390   rtx orig_dest = operands[0];
2391   rtx bytes_rtx = operands[1];
2392   rtx align_rtx = operands[3];
2393   int constp    = (GET_CODE (bytes_rtx) == CONST_INT);
2394   int align;
2395   int bytes;
2396   int offset;
2397   rtx dest_reg;
2398   rtx dest_addr;
2399   rtx dest_mem;
2400   int clear_bytes;
2401   enum machine_mode mode;
2402
2403   /* If this is not a fixed size move, just call memcpy.  */
2404   if (! constp)
2405     return FALSE;
2406
2407   /* This should be a fixed size alignment.  */
2408   gcc_assert (GET_CODE (align_rtx) == CONST_INT);
2409
2410   align = INTVAL (align_rtx);
2411
2412   /* Anything to move? */
2413   bytes = INTVAL (bytes_rtx);
2414   if (bytes <= 0)
2415     return TRUE;
2416
2417   /* Don't support real large clears.  */
2418   if (bytes > TOTAL_MOVE_REG*align)
2419     return FALSE;
2420
2421   /* Move the address into a scratch register.  */
2422   dest_reg = copy_addr_to_reg (XEXP (orig_dest, 0));
2423
2424   offset = 0;
2425   for ( ; bytes > 0; (bytes -= clear_bytes), (offset += clear_bytes))
2426     {
2427       /* Calculate the correct offset for src/dest.  */
2428       dest_addr = ((offset == 0)
2429                    ? dest_reg
2430                    : plus_constant (dest_reg, offset));
2431
2432       /* Generate the appropriate store of gr0.  */
2433       if (bytes >= 4 && align >= 4)
2434         mode = SImode;
2435       else if (bytes >= 2 && align >= 2)
2436         mode = HImode;
2437       else
2438         mode = QImode;
2439
2440       clear_bytes = GET_MODE_SIZE (mode);
2441       dest_mem = change_address (orig_dest, mode, dest_addr);
2442       emit_insn (gen_rtx_SET (VOIDmode, dest_mem, const0_rtx));
2443     }
2444
2445   return TRUE;
2446 }
2447
2448 \f
2449 /* The following variable is used to output modifiers of assembler
2450    code of the current output insn.  */
2451
2452 static rtx *frv_insn_operands;
2453
2454 /* The following function is used to add assembler insn code suffix .p
2455    if it is necessary.  */
2456
2457 const char *
2458 frv_asm_output_opcode (FILE *f, const char *ptr)
2459 {
2460   int c;
2461
2462   if (frv_insn_packing_flag <= 0)
2463     return ptr;
2464
2465   for (; *ptr && *ptr != ' ' && *ptr != '\t';)
2466     {
2467       c = *ptr++;
2468       if (c == '%' && ((*ptr >= 'a' && *ptr <= 'z')
2469                        || (*ptr >= 'A' && *ptr <= 'Z')))
2470         {
2471           int letter = *ptr++;
2472
2473           c = atoi (ptr);
2474           frv_print_operand (f, frv_insn_operands [c], letter);
2475           while ((c = *ptr) >= '0' && c <= '9')
2476             ptr++;
2477         }
2478       else
2479         fputc (c, f);
2480     }
2481
2482   fprintf (f, ".p");
2483
2484   return ptr;
2485 }
2486
2487 /* Set up the packing bit for the current output insn.  Note that this
2488    function is not called for asm insns.  */
2489
2490 void
2491 frv_final_prescan_insn (rtx insn, rtx *opvec,
2492                         int noperands ATTRIBUTE_UNUSED)
2493 {
2494   if (INSN_P (insn))
2495     {
2496       if (frv_insn_packing_flag >= 0)
2497         {
2498           frv_insn_operands = opvec;
2499           frv_insn_packing_flag = PACKING_FLAG_P (insn);
2500         }
2501       else if (recog_memoized (insn) >= 0
2502                && get_attr_acc_group (insn) == ACC_GROUP_ODD)
2503         /* Packing optimizations have been disabled, but INSN can only
2504            be issued in M1.  Insert an mnop in M0.  */
2505         fprintf (asm_out_file, "\tmnop.p\n");
2506     }
2507 }
2508
2509
2510 \f
2511 /* A C expression whose value is RTL representing the address in a stack frame
2512    where the pointer to the caller's frame is stored.  Assume that FRAMEADDR is
2513    an RTL expression for the address of the stack frame itself.
2514
2515    If you don't define this macro, the default is to return the value of
2516    FRAMEADDR--that is, the stack frame address is also the address of the stack
2517    word that points to the previous frame.  */
2518
2519 /* The default is correct, but we need to make sure the frame gets created.  */
2520 rtx
2521 frv_dynamic_chain_address (rtx frame)
2522 {
2523   cfun->machine->frame_needed = 1;
2524   return frame;
2525 }
2526
2527
2528 /* A C expression whose value is RTL representing the value of the return
2529    address for the frame COUNT steps up from the current frame, after the
2530    prologue.  FRAMEADDR is the frame pointer of the COUNT frame, or the frame
2531    pointer of the COUNT - 1 frame if `RETURN_ADDR_IN_PREVIOUS_FRAME' is
2532    defined.
2533
2534    The value of the expression must always be the correct address when COUNT is
2535    zero, but may be `NULL_RTX' if there is not way to determine the return
2536    address of other frames.  */
2537
2538 rtx
2539 frv_return_addr_rtx (int count, rtx frame)
2540 {
2541   if (count != 0)
2542     return const0_rtx;
2543   cfun->machine->frame_needed = 1;
2544   return gen_rtx_MEM (Pmode, plus_constant (frame, 8));
2545 }
2546
2547 /* Given a memory reference MEMREF, interpret the referenced memory as
2548    an array of MODE values, and return a reference to the element
2549    specified by INDEX.  Assume that any pre-modification implicit in
2550    MEMREF has already happened.
2551
2552    MEMREF must be a legitimate operand for modes larger than SImode.
2553    frv_legitimate_address_p forbids register+register addresses, which
2554    this function cannot handle.  */
2555 rtx
2556 frv_index_memory (rtx memref, enum machine_mode mode, int index)
2557 {
2558   rtx base = XEXP (memref, 0);
2559   if (GET_CODE (base) == PRE_MODIFY)
2560     base = XEXP (base, 0);
2561   return change_address (memref, mode,
2562                          plus_constant (base, index * GET_MODE_SIZE (mode)));
2563 }
2564
2565 \f
2566 /* Print a memory address as an operand to reference that memory location.  */
2567 static void
2568 frv_print_operand_address (FILE * stream, rtx x)
2569 {
2570   if (GET_CODE (x) == MEM)
2571     x = XEXP (x, 0);
2572
2573   switch (GET_CODE (x))
2574     {
2575     case REG:
2576       fputs (reg_names [ REGNO (x)], stream);
2577       return;
2578
2579     case CONST_INT:
2580       fprintf (stream, "%ld", (long) INTVAL (x));
2581       return;
2582
2583     case SYMBOL_REF:
2584       assemble_name (stream, XSTR (x, 0));
2585       return;
2586
2587     case LABEL_REF:
2588     case CONST:
2589       output_addr_const (stream, x);
2590       return;
2591
2592     case PLUS:
2593       /* Poorly constructed asm statements can trigger this alternative.
2594          See gcc/testsuite/gcc.dg/asm-4.c for an example.  */
2595       frv_print_operand_memory_reference (stream, x, 0);
2596       return;
2597       
2598     default:
2599       break;
2600     }
2601
2602   fatal_insn ("bad insn to frv_print_operand_address:", x);
2603 }
2604
2605 \f
2606 static void
2607 frv_print_operand_memory_reference_reg (FILE * stream, rtx x)
2608 {
2609   int regno = true_regnum (x);
2610   if (GPR_P (regno))
2611     fputs (reg_names[regno], stream);
2612   else
2613     fatal_insn ("bad register to frv_print_operand_memory_reference_reg:", x);
2614 }
2615
2616 /* Print a memory reference suitable for the ld/st instructions.  */
2617
2618 static void
2619 frv_print_operand_memory_reference (FILE * stream, rtx x, int addr_offset)
2620 {
2621   struct frv_unspec unspec;
2622   rtx x0 = NULL_RTX;
2623   rtx x1 = NULL_RTX;
2624
2625   switch (GET_CODE (x))
2626     {
2627     case SUBREG:
2628     case REG:
2629       x0 = x;
2630       break;
2631
2632     case PRE_MODIFY:            /* (pre_modify (reg) (plus (reg) (reg))) */
2633       x0 = XEXP (x, 0);
2634       x1 = XEXP (XEXP (x, 1), 1);
2635       break;
2636
2637     case CONST_INT:
2638       x1 = x;
2639       break;
2640
2641     case PLUS:
2642       x0 = XEXP (x, 0);
2643       x1 = XEXP (x, 1);
2644       if (GET_CODE (x0) == CONST_INT)
2645         {
2646           x0 = XEXP (x, 1);
2647           x1 = XEXP (x, 0);
2648         }
2649       break;
2650
2651     default:
2652       fatal_insn ("bad insn to frv_print_operand_memory_reference:", x);
2653       break;
2654
2655     }
2656
2657   if (addr_offset)
2658     {
2659       if (!x1)
2660         x1 = const0_rtx;
2661       else if (GET_CODE (x1) != CONST_INT)
2662         fatal_insn ("bad insn to frv_print_operand_memory_reference:", x);
2663     }
2664
2665   fputs ("@(", stream);
2666   if (!x0)
2667     fputs (reg_names[GPR_R0], stream);
2668   else if (GET_CODE (x0) == REG || GET_CODE (x0) == SUBREG)
2669     frv_print_operand_memory_reference_reg (stream, x0);
2670   else
2671     fatal_insn ("bad insn to frv_print_operand_memory_reference:", x);
2672
2673   fputs (",", stream);
2674   if (!x1)
2675     fputs (reg_names [GPR_R0], stream);
2676
2677   else
2678     {
2679       switch (GET_CODE (x1))
2680         {
2681         case SUBREG:
2682         case REG:
2683           frv_print_operand_memory_reference_reg (stream, x1);
2684           break;
2685
2686         case CONST_INT:
2687           fprintf (stream, "%ld", (long) (INTVAL (x1) + addr_offset));
2688           break;
2689
2690         case CONST:
2691           if (!frv_const_unspec_p (x1, &unspec))
2692             fatal_insn ("bad insn to frv_print_operand_memory_reference:", x1);
2693           frv_output_const_unspec (stream, &unspec);
2694           break;
2695
2696         default:
2697           fatal_insn ("bad insn to frv_print_operand_memory_reference:", x);
2698         }
2699     }
2700
2701   fputs (")", stream);
2702 }
2703
2704 \f
2705 /* Return 2 for likely branches and 0 for non-likely branches  */
2706
2707 #define FRV_JUMP_LIKELY 2
2708 #define FRV_JUMP_NOT_LIKELY 0
2709
2710 static int
2711 frv_print_operand_jump_hint (rtx insn)
2712 {
2713   rtx note;
2714   rtx labelref;
2715   int ret;
2716   HOST_WIDE_INT prob = -1;
2717   enum { UNKNOWN, BACKWARD, FORWARD } jump_type = UNKNOWN;
2718
2719   gcc_assert (GET_CODE (insn) == JUMP_INSN);
2720
2721   /* Assume any non-conditional jump is likely.  */
2722   if (! any_condjump_p (insn))
2723     ret = FRV_JUMP_LIKELY;
2724
2725   else
2726     {
2727       labelref = condjump_label (insn);
2728       if (labelref)
2729         {
2730           rtx label = XEXP (labelref, 0);
2731           jump_type = (insn_current_address > INSN_ADDRESSES (INSN_UID (label))
2732                        ? BACKWARD
2733                        : FORWARD);
2734         }
2735
2736       note = find_reg_note (insn, REG_BR_PROB, 0);
2737       if (!note)
2738         ret = ((jump_type == BACKWARD) ? FRV_JUMP_LIKELY : FRV_JUMP_NOT_LIKELY);
2739
2740       else
2741         {
2742           prob = INTVAL (XEXP (note, 0));
2743           ret = ((prob >= (REG_BR_PROB_BASE / 2))
2744                  ? FRV_JUMP_LIKELY
2745                  : FRV_JUMP_NOT_LIKELY);
2746         }
2747     }
2748
2749 #if 0
2750   if (TARGET_DEBUG)
2751     {
2752       char *direction;
2753
2754       switch (jump_type)
2755         {
2756         default:
2757         case UNKNOWN:   direction = "unknown jump direction";   break;
2758         case BACKWARD:  direction = "jump backward";            break;
2759         case FORWARD:   direction = "jump forward";             break;
2760         }
2761
2762       fprintf (stderr,
2763                "%s: uid %ld, %s, probability = %ld, max prob. = %ld, hint = %d\n",
2764                IDENTIFIER_POINTER (DECL_NAME (current_function_decl)),
2765                (long)INSN_UID (insn), direction, (long)prob,
2766                (long)REG_BR_PROB_BASE, ret);
2767     }
2768 #endif
2769
2770   return ret;
2771 }
2772
2773 \f
2774 /* Return the comparison operator to use for CODE given that the ICC
2775    register is OP0.  */
2776
2777 static const char *
2778 comparison_string (enum rtx_code code, rtx op0)
2779 {
2780   bool is_nz_p = GET_MODE (op0) == CC_NZmode;
2781   switch (code)
2782     {
2783     default:  output_operand_lossage ("bad condition code");
2784     case EQ:  return "eq";
2785     case NE:  return "ne";
2786     case LT:  return is_nz_p ? "n" : "lt";
2787     case LE:  return "le";
2788     case GT:  return "gt";
2789     case GE:  return is_nz_p ? "p" : "ge";
2790     case LTU: return is_nz_p ? "no" : "c";
2791     case LEU: return is_nz_p ? "eq" : "ls";
2792     case GTU: return is_nz_p ? "ne" : "hi";
2793     case GEU: return is_nz_p ? "ra" : "nc";
2794     }
2795 }
2796
2797 /* Print an operand to an assembler instruction.
2798
2799    `%' followed by a letter and a digit says to output an operand in an
2800    alternate fashion.  Four letters have standard, built-in meanings
2801    described below.  The hook `TARGET_PRINT_OPERAND' can define
2802    additional letters with nonstandard meanings.
2803
2804    `%cDIGIT' can be used to substitute an operand that is a constant value
2805    without the syntax that normally indicates an immediate operand.
2806
2807    `%nDIGIT' is like `%cDIGIT' except that the value of the constant is negated
2808    before printing.
2809
2810    `%aDIGIT' can be used to substitute an operand as if it were a memory
2811    reference, with the actual operand treated as the address.  This may be
2812    useful when outputting a "load address" instruction, because often the
2813    assembler syntax for such an instruction requires you to write the operand
2814    as if it were a memory reference.
2815
2816    `%lDIGIT' is used to substitute a `label_ref' into a jump instruction.
2817
2818    `%=' outputs a number which is unique to each instruction in the entire
2819    compilation.  This is useful for making local labels to be referred to more
2820    than once in a single template that generates multiple assembler
2821    instructions.
2822
2823    `%' followed by a punctuation character specifies a substitution that
2824    does not use an operand.  Only one case is standard: `%%' outputs a
2825    `%' into the assembler code.  Other nonstandard cases can be defined
2826    in the `TARGET_PRINT_OPERAND' hook.  You must also define which
2827    punctuation characters are valid with the
2828    `TARGET_PRINT_OPERAND_PUNCT_VALID_P' hook.  */
2829
2830 static void
2831 frv_print_operand (FILE * file, rtx x, int code)
2832 {
2833   struct frv_unspec unspec;
2834   HOST_WIDE_INT value;
2835   int offset;
2836
2837   if (code != 0 && !ISALPHA (code))
2838     value = 0;
2839
2840   else if (GET_CODE (x) == CONST_INT)
2841     value = INTVAL (x);
2842
2843   else if (GET_CODE (x) == CONST_DOUBLE)
2844     {
2845       if (GET_MODE (x) == SFmode)
2846         {
2847           REAL_VALUE_TYPE rv;
2848           long l;
2849
2850           REAL_VALUE_FROM_CONST_DOUBLE (rv, x);
2851           REAL_VALUE_TO_TARGET_SINGLE (rv, l);
2852           value = l;
2853         }
2854
2855       else if (GET_MODE (x) == VOIDmode)
2856         value = CONST_DOUBLE_LOW (x);
2857
2858       else
2859         fatal_insn ("bad insn in frv_print_operand, bad const_double", x);
2860     }
2861
2862   else
2863     value = 0;
2864
2865   switch (code)
2866     {
2867
2868     case '.':
2869       /* Output r0.  */
2870       fputs (reg_names[GPR_R0], file);
2871       break;
2872
2873     case '#':
2874       fprintf (file, "%d", frv_print_operand_jump_hint (current_output_insn));
2875       break;
2876
2877     case '@':
2878       /* Output small data area base register (gr16).  */
2879       fputs (reg_names[SDA_BASE_REG], file);
2880       break;
2881
2882     case '~':
2883       /* Output pic register (gr17).  */
2884       fputs (reg_names[PIC_REGNO], file);
2885       break;
2886
2887     case '*':
2888       /* Output the temporary integer CCR register.  */
2889       fputs (reg_names[ICR_TEMP], file);
2890       break;
2891
2892     case '&':
2893       /* Output the temporary integer CC register.  */
2894       fputs (reg_names[ICC_TEMP], file);
2895       break;
2896
2897     /* case 'a': print an address.  */
2898
2899     case 'C':
2900       /* Print appropriate test for integer branch false operation.  */
2901       fputs (comparison_string (reverse_condition (GET_CODE (x)),
2902                                 XEXP (x, 0)), file);
2903       break;
2904
2905     case 'c':
2906       /* Print appropriate test for integer branch true operation.  */
2907       fputs (comparison_string (GET_CODE (x), XEXP (x, 0)), file);
2908       break;
2909
2910     case 'e':
2911       /* Print 1 for a NE and 0 for an EQ to give the final argument
2912          for a conditional instruction.  */
2913       if (GET_CODE (x) == NE)
2914         fputs ("1", file);
2915
2916       else if (GET_CODE (x) == EQ)
2917         fputs ("0", file);
2918
2919       else
2920         fatal_insn ("bad insn to frv_print_operand, 'e' modifier:", x);
2921       break;
2922
2923     case 'F':
2924       /* Print appropriate test for floating point branch false operation.  */
2925       switch (GET_CODE (x))
2926         {
2927         default:
2928           fatal_insn ("bad insn to frv_print_operand, 'F' modifier:", x);
2929
2930         case EQ:  fputs ("ne",  file); break;
2931         case NE:  fputs ("eq",  file); break;
2932         case LT:  fputs ("uge", file); break;
2933         case LE:  fputs ("ug",  file); break;
2934         case GT:  fputs ("ule", file); break;
2935         case GE:  fputs ("ul",  file); break;
2936         }
2937       break;
2938
2939     case 'f':
2940       /* Print appropriate test for floating point branch true operation.  */
2941       switch (GET_CODE (x))
2942         {
2943         default:
2944           fatal_insn ("bad insn to frv_print_operand, 'f' modifier:", x);
2945
2946         case EQ:  fputs ("eq",  file); break;
2947         case NE:  fputs ("ne",  file); break;
2948         case LT:  fputs ("lt",  file); break;
2949         case LE:  fputs ("le",  file); break;
2950         case GT:  fputs ("gt",  file); break;
2951         case GE:  fputs ("ge",  file); break;
2952         }
2953       break;
2954
2955     case 'g':
2956       /* Print appropriate GOT function.  */
2957       if (GET_CODE (x) != CONST_INT)
2958         fatal_insn ("bad insn to frv_print_operand, 'g' modifier:", x);
2959       fputs (unspec_got_name (INTVAL (x)), file);
2960       break;
2961
2962     case 'I':
2963       /* Print 'i' if the operand is a constant, or is a memory reference that
2964          adds a constant.  */
2965       if (GET_CODE (x) == MEM)
2966         x = ((GET_CODE (XEXP (x, 0)) == PLUS)
2967              ? XEXP (XEXP (x, 0), 1)
2968              : XEXP (x, 0));
2969       else if (GET_CODE (x) == PLUS)
2970         x = XEXP (x, 1);
2971
2972       switch (GET_CODE (x))
2973         {
2974         default:
2975           break;
2976
2977         case CONST_INT:
2978         case SYMBOL_REF:
2979         case CONST:
2980           fputs ("i", file);
2981           break;
2982         }
2983       break;
2984
2985     case 'i':
2986       /* For jump instructions, print 'i' if the operand is a constant or
2987          is an expression that adds a constant.  */
2988       if (GET_CODE (x) == CONST_INT)
2989         fputs ("i", file);
2990
2991       else
2992         {
2993           if (GET_CODE (x) == CONST_INT
2994               || (GET_CODE (x) == PLUS
2995                   && (GET_CODE (XEXP (x, 1)) == CONST_INT
2996                       || GET_CODE (XEXP (x, 0)) == CONST_INT)))
2997             fputs ("i", file);
2998         }
2999       break;
3000
3001     case 'L':
3002       /* Print the lower register of a double word register pair */
3003       if (GET_CODE (x) == REG)
3004         fputs (reg_names[ REGNO (x)+1 ], file);
3005       else
3006         fatal_insn ("bad insn to frv_print_operand, 'L' modifier:", x);
3007       break;
3008
3009     /* case 'l': print a LABEL_REF.  */
3010
3011     case 'M':
3012     case 'N':
3013       /* Print a memory reference for ld/st/jmp, %N prints a memory reference
3014          for the second word of double memory operations.  */
3015       offset = (code == 'M') ? 0 : UNITS_PER_WORD;
3016       switch (GET_CODE (x))
3017         {
3018         default:
3019           fatal_insn ("bad insn to frv_print_operand, 'M/N' modifier:", x);
3020
3021         case MEM:
3022           frv_print_operand_memory_reference (file, XEXP (x, 0), offset);
3023           break;
3024
3025         case REG:
3026         case SUBREG:
3027         case CONST_INT:
3028         case PLUS:
3029         case SYMBOL_REF:
3030           frv_print_operand_memory_reference (file, x, offset);
3031           break;
3032         }
3033       break;
3034
3035     case 'O':
3036       /* Print the opcode of a command.  */
3037       switch (GET_CODE (x))
3038         {
3039         default:
3040           fatal_insn ("bad insn to frv_print_operand, 'O' modifier:", x);
3041
3042         case PLUS:     fputs ("add", file); break;
3043         case MINUS:    fputs ("sub", file); break;
3044         case AND:      fputs ("and", file); break;
3045         case IOR:      fputs ("or",  file); break;
3046         case XOR:      fputs ("xor", file); break;
3047         case ASHIFT:   fputs ("sll", file); break;
3048         case ASHIFTRT: fputs ("sra", file); break;
3049         case LSHIFTRT: fputs ("srl", file); break;
3050         }
3051       break;
3052
3053     /* case 'n': negate and print a constant int.  */
3054
3055     case 'P':
3056       /* Print PIC label using operand as the number.  */
3057       if (GET_CODE (x) != CONST_INT)
3058         fatal_insn ("bad insn to frv_print_operand, P modifier:", x);
3059
3060       fprintf (file, ".LCF%ld", (long)INTVAL (x));
3061       break;
3062
3063     case 'U':
3064       /* Print 'u' if the operand is a update load/store.  */
3065       if (GET_CODE (x) == MEM && GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
3066         fputs ("u", file);
3067       break;
3068
3069     case 'z':
3070       /* If value is 0, print gr0, otherwise it must be a register.  */
3071       if (GET_CODE (x) == CONST_INT && INTVAL (x) == 0)
3072         fputs (reg_names[GPR_R0], file);
3073
3074       else if (GET_CODE (x) == REG)
3075         fputs (reg_names [REGNO (x)], file);
3076
3077       else
3078         fatal_insn ("bad insn in frv_print_operand, z case", x);
3079       break;
3080
3081     case 'x':
3082       /* Print constant in hex.  */
3083       if (GET_CODE (x) == CONST_INT || GET_CODE (x) == CONST_DOUBLE)
3084         {
3085           fprintf (file, "%s0x%.4lx", IMMEDIATE_PREFIX, (long) value);
3086           break;
3087         }
3088
3089       /* Fall through.  */
3090
3091     case '\0':
3092       if (GET_CODE (x) == REG)
3093         fputs (reg_names [REGNO (x)], file);
3094
3095       else if (GET_CODE (x) == CONST_INT
3096               || GET_CODE (x) == CONST_DOUBLE)
3097         fprintf (file, "%s%ld", IMMEDIATE_PREFIX, (long) value);
3098
3099       else if (frv_const_unspec_p (x, &unspec))
3100         frv_output_const_unspec (file, &unspec);
3101
3102       else if (GET_CODE (x) == MEM)
3103         frv_print_operand_address (file, XEXP (x, 0));
3104
3105       else if (CONSTANT_ADDRESS_P (x))
3106         frv_print_operand_address (file, x);
3107
3108       else
3109         fatal_insn ("bad insn in frv_print_operand, 0 case", x);
3110
3111       break;
3112
3113     default:
3114       fatal_insn ("frv_print_operand: unknown code", x);
3115       break;
3116     }
3117
3118   return;
3119 }
3120
3121 static bool
3122 frv_print_operand_punct_valid_p (unsigned char code)
3123 {
3124   return (code == '.' || code == '#' || code == '@' || code == '~'
3125           || code == '*' || code == '&');
3126 }
3127
3128 \f
3129 /* A C statement (sans semicolon) for initializing the variable CUM for the
3130    state at the beginning of the argument list.  The variable has type
3131    `CUMULATIVE_ARGS'.  The value of FNTYPE is the tree node for the data type
3132    of the function which will receive the args, or 0 if the args are to a
3133    compiler support library function.  The value of INDIRECT is nonzero when
3134    processing an indirect call, for example a call through a function pointer.
3135    The value of INDIRECT is zero for a call to an explicitly named function, a
3136    library function call, or when `INIT_CUMULATIVE_ARGS' is used to find
3137    arguments for the function being compiled.
3138
3139    When processing a call to a compiler support library function, LIBNAME
3140    identifies which one.  It is a `symbol_ref' rtx which contains the name of
3141    the function, as a string.  LIBNAME is 0 when an ordinary C function call is
3142    being processed.  Thus, each time this macro is called, either LIBNAME or
3143    FNTYPE is nonzero, but never both of them at once.  */
3144
3145 void
3146 frv_init_cumulative_args (CUMULATIVE_ARGS *cum,
3147                           tree fntype,
3148                           rtx libname,
3149                           tree fndecl,
3150                           int incoming)
3151 {
3152   *cum = FIRST_ARG_REGNUM;
3153
3154   if (TARGET_DEBUG_ARG)
3155     {
3156       fprintf (stderr, "\ninit_cumulative_args:");
3157       if (!fndecl && fntype)
3158         fputs (" indirect", stderr);
3159
3160       if (incoming)
3161         fputs (" incoming", stderr);
3162
3163       if (fntype)
3164         {
3165           tree ret_type = TREE_TYPE (fntype);
3166           fprintf (stderr, " return=%s,",
3167                    tree_code_name[ (int)TREE_CODE (ret_type) ]);
3168         }
3169
3170       if (libname && GET_CODE (libname) == SYMBOL_REF)
3171         fprintf (stderr, " libname=%s", XSTR (libname, 0));
3172
3173       if (cfun->returns_struct)
3174         fprintf (stderr, " return-struct");
3175
3176       putc ('\n', stderr);
3177     }
3178 }
3179
3180 \f
3181 /* Return true if we should pass an argument on the stack rather than
3182    in registers.  */
3183
3184 static bool
3185 frv_must_pass_in_stack (enum machine_mode mode, const_tree type)
3186 {
3187   if (mode == BLKmode)
3188     return true;
3189   if (type == NULL)
3190     return false;
3191   return AGGREGATE_TYPE_P (type);
3192 }
3193
3194 /* If defined, a C expression that gives the alignment boundary, in bits, of an
3195    argument with the specified mode and type.  If it is not defined,
3196    `PARM_BOUNDARY' is used for all arguments.  */
3197
3198 int
3199 frv_function_arg_boundary (enum machine_mode mode ATTRIBUTE_UNUSED,
3200                            tree type ATTRIBUTE_UNUSED)
3201 {
3202   return BITS_PER_WORD;
3203 }
3204
3205 static rtx
3206 frv_function_arg_1 (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
3207                     const_tree type ATTRIBUTE_UNUSED, bool named,
3208                     bool incoming ATTRIBUTE_UNUSED)
3209 {
3210   enum machine_mode xmode = (mode == BLKmode) ? SImode : mode;
3211   int arg_num = *cum;
3212   rtx ret;
3213   const char *debstr;
3214
3215   /* Return a marker for use in the call instruction.  */
3216   if (xmode == VOIDmode)
3217     {
3218       ret = const0_rtx;
3219       debstr = "<0>";
3220     }
3221
3222   else if (arg_num <= LAST_ARG_REGNUM)
3223     {
3224       ret = gen_rtx_REG (xmode, arg_num);
3225       debstr = reg_names[arg_num];
3226     }
3227
3228   else
3229     {
3230       ret = NULL_RTX;
3231       debstr = "memory";
3232     }
3233
3234   if (TARGET_DEBUG_ARG)
3235     fprintf (stderr,
3236              "function_arg: words = %2d, mode = %4s, named = %d, size = %3d, arg = %s\n",
3237              arg_num, GET_MODE_NAME (mode), named, GET_MODE_SIZE (mode), debstr);
3238
3239   return ret;
3240 }
3241
3242 static rtx
3243 frv_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3244                   const_tree type, bool named)
3245 {
3246   return frv_function_arg_1 (cum, mode, type, named, false);
3247 }
3248
3249 static rtx
3250 frv_function_incoming_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3251                            const_tree type, bool named)
3252 {
3253   return frv_function_arg_1 (cum, mode, type, named, true);
3254 }
3255
3256 \f
3257 /* A C statement (sans semicolon) to update the summarizer variable CUM to
3258    advance past an argument in the argument list.  The values MODE, TYPE and
3259    NAMED describe that argument.  Once this is done, the variable CUM is
3260    suitable for analyzing the *following* argument with `FUNCTION_ARG', etc.
3261
3262    This macro need not do anything if the argument in question was passed on
3263    the stack.  The compiler knows how to track the amount of stack space used
3264    for arguments without any special help.  */
3265
3266 static void
3267 frv_function_arg_advance (CUMULATIVE_ARGS *cum,
3268                           enum machine_mode mode,
3269                           const_tree type ATTRIBUTE_UNUSED,
3270                           bool named)
3271 {
3272   enum machine_mode xmode = (mode == BLKmode) ? SImode : mode;
3273   int bytes = GET_MODE_SIZE (xmode);
3274   int words = (bytes + UNITS_PER_WORD  - 1) / UNITS_PER_WORD;
3275   int arg_num = *cum;
3276
3277   *cum = arg_num + words;
3278
3279   if (TARGET_DEBUG_ARG)
3280     fprintf (stderr,
3281              "function_adv: words = %2d, mode = %4s, named = %d, size = %3d\n",
3282              arg_num, GET_MODE_NAME (mode), named, words * UNITS_PER_WORD);
3283 }
3284
3285 \f
3286 /* A C expression for the number of words, at the beginning of an argument,
3287    must be put in registers.  The value must be zero for arguments that are
3288    passed entirely in registers or that are entirely pushed on the stack.
3289
3290    On some machines, certain arguments must be passed partially in registers
3291    and partially in memory.  On these machines, typically the first N words of
3292    arguments are passed in registers, and the rest on the stack.  If a
3293    multi-word argument (a `double' or a structure) crosses that boundary, its
3294    first few words must be passed in registers and the rest must be pushed.
3295    This macro tells the compiler when this occurs, and how many of the words
3296    should go in registers.
3297
3298    `FUNCTION_ARG' for these arguments should return the first register to be
3299    used by the caller for this argument; likewise `FUNCTION_INCOMING_ARG', for
3300    the called function.  */
3301
3302 static int
3303 frv_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3304                        tree type ATTRIBUTE_UNUSED, bool named ATTRIBUTE_UNUSED)
3305 {
3306   enum machine_mode xmode = (mode == BLKmode) ? SImode : mode;
3307   int bytes = GET_MODE_SIZE (xmode);
3308   int words = (bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
3309   int arg_num = *cum;
3310   int ret;
3311
3312   ret = ((arg_num <= LAST_ARG_REGNUM && arg_num + words > LAST_ARG_REGNUM+1)
3313          ? LAST_ARG_REGNUM - arg_num + 1
3314          : 0);
3315   ret *= UNITS_PER_WORD;
3316
3317   if (TARGET_DEBUG_ARG && ret)
3318     fprintf (stderr, "frv_arg_partial_bytes: %d\n", ret);
3319
3320   return ret;
3321 }
3322
3323 \f
3324 /* Implements TARGET_FUNCTION_VALUE.  */
3325
3326 static rtx
3327 frv_function_value (const_tree valtype,
3328                     const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
3329                     bool outgoing ATTRIBUTE_UNUSED)
3330 {
3331   return gen_rtx_REG (TYPE_MODE (valtype), RETURN_VALUE_REGNUM);
3332 }
3333
3334 \f
3335 /* Implements TARGET_LIBCALL_VALUE.  */
3336
3337 static rtx
3338 frv_libcall_value (enum machine_mode mode,
3339                    const_rtx fun ATTRIBUTE_UNUSED)
3340 {
3341   return gen_rtx_REG (mode, RETURN_VALUE_REGNUM);
3342 }
3343
3344 \f
3345 /* Implements FUNCTION_VALUE_REGNO_P.  */
3346
3347 bool
3348 frv_function_value_regno_p (const unsigned int regno)
3349 {
3350   return (regno == RETURN_VALUE_REGNUM);
3351 }
3352 \f
3353 /* Return true if a register is ok to use as a base or index register.  */
3354
3355 static FRV_INLINE int
3356 frv_regno_ok_for_base_p (int regno, int strict_p)
3357 {
3358   if (GPR_P (regno))
3359     return TRUE;
3360
3361   if (strict_p)
3362     return (reg_renumber[regno] >= 0 && GPR_P (reg_renumber[regno]));
3363
3364   if (regno == ARG_POINTER_REGNUM)
3365     return TRUE;
3366
3367   return (regno >= FIRST_PSEUDO_REGISTER);
3368 }
3369
3370 \f
3371 /* A C compound statement with a conditional `goto LABEL;' executed if X (an
3372    RTX) is a legitimate memory address on the target machine for a memory
3373    operand of mode MODE.
3374
3375    It usually pays to define several simpler macros to serve as subroutines for
3376    this one.  Otherwise it may be too complicated to understand.
3377
3378    This macro must exist in two variants: a strict variant and a non-strict
3379    one.  The strict variant is used in the reload pass.  It must be defined so
3380    that any pseudo-register that has not been allocated a hard register is
3381    considered a memory reference.  In contexts where some kind of register is
3382    required, a pseudo-register with no hard register must be rejected.
3383
3384    The non-strict variant is used in other passes.  It must be defined to
3385    accept all pseudo-registers in every context where some kind of register is
3386    required.
3387
3388    Compiler source files that want to use the strict variant of this macro
3389    define the macro `REG_OK_STRICT'.  You should use an `#ifdef REG_OK_STRICT'
3390    conditional to define the strict variant in that case and the non-strict
3391    variant otherwise.
3392
3393    Normally, constant addresses which are the sum of a `symbol_ref' and an
3394    integer are stored inside a `const' RTX to mark them as constant.
3395    Therefore, there is no need to recognize such sums specifically as
3396    legitimate addresses.  Normally you would simply recognize any `const' as
3397    legitimate.
3398
3399    Usually `TARGET_PRINT_OPERAND_ADDRESS' is not prepared to handle
3400    constant sums that are not marked with `const'.  It assumes that a
3401    naked `plus' indicates indexing.  If so, then you *must* reject such
3402    naked constant sums as illegitimate addresses, so that none of them
3403    will be given to `TARGET_PRINT_OPERAND_ADDRESS'.  */
3404
3405 int
3406 frv_legitimate_address_p_1 (enum machine_mode mode,
3407                             rtx x,
3408                             int strict_p,
3409                             int condexec_p,
3410                             int allow_double_reg_p)
3411 {
3412   rtx x0, x1;
3413   int ret = 0;
3414   HOST_WIDE_INT value;
3415   unsigned regno0;
3416
3417   if (FRV_SYMBOL_REF_TLS_P (x))
3418     return 0;
3419
3420   switch (GET_CODE (x))
3421     {
3422     default:
3423       break;
3424
3425     case SUBREG:
3426       x = SUBREG_REG (x);
3427       if (GET_CODE (x) != REG)
3428         break;
3429
3430       /* Fall through.  */
3431
3432     case REG:
3433       ret = frv_regno_ok_for_base_p (REGNO (x), strict_p);
3434       break;
3435
3436     case PRE_MODIFY:
3437       x0 = XEXP (x, 0);
3438       x1 = XEXP (x, 1);
3439       if (GET_CODE (x0) != REG
3440           || ! frv_regno_ok_for_base_p (REGNO (x0), strict_p)
3441           || GET_CODE (x1) != PLUS
3442           || ! rtx_equal_p (x0, XEXP (x1, 0))
3443           || GET_CODE (XEXP (x1, 1)) != REG
3444           || ! frv_regno_ok_for_base_p (REGNO (XEXP (x1, 1)), strict_p))
3445         break;
3446
3447       ret = 1;
3448       break;
3449
3450     case CONST_INT:
3451       /* 12-bit immediate */
3452       if (condexec_p)
3453         ret = FALSE;
3454       else
3455         {
3456           ret = IN_RANGE_P (INTVAL (x), -2048, 2047);
3457
3458           /* If we can't use load/store double operations, make sure we can
3459              address the second word.  */
3460           if (ret && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
3461             ret = IN_RANGE_P (INTVAL (x) + GET_MODE_SIZE (mode) - 1,
3462                               -2048, 2047);
3463         }
3464       break;
3465
3466     case PLUS:
3467       x0 = XEXP (x, 0);
3468       x1 = XEXP (x, 1);
3469
3470       if (GET_CODE (x0) == SUBREG)
3471         x0 = SUBREG_REG (x0);
3472
3473       if (GET_CODE (x0) != REG)
3474         break;
3475
3476       regno0 = REGNO (x0);
3477       if (!frv_regno_ok_for_base_p (regno0, strict_p))
3478         break;
3479
3480       switch (GET_CODE (x1))
3481         {
3482         default:
3483           break;
3484
3485         case SUBREG:
3486           x1 = SUBREG_REG (x1);
3487           if (GET_CODE (x1) != REG)
3488             break;
3489
3490           /* Fall through.  */
3491
3492         case REG:
3493           /* Do not allow reg+reg addressing for modes > 1 word if we
3494              can't depend on having move double instructions.  */
3495           if (!allow_double_reg_p && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
3496             ret = FALSE;
3497           else
3498             ret = frv_regno_ok_for_base_p (REGNO (x1), strict_p);
3499           break;
3500
3501         case CONST_INT:
3502           /* 12-bit immediate */
3503           if (condexec_p)
3504             ret = FALSE;
3505           else
3506             {
3507               value = INTVAL (x1);
3508               ret = IN_RANGE_P (value, -2048, 2047);
3509
3510               /* If we can't use load/store double operations, make sure we can
3511                  address the second word.  */
3512               if (ret && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
3513                 ret = IN_RANGE_P (value + GET_MODE_SIZE (mode) - 1, -2048, 2047);
3514             }
3515           break;
3516
3517         case CONST:
3518           if (!condexec_p && got12_operand (x1, VOIDmode))
3519             ret = TRUE;
3520           break;
3521
3522         }
3523       break;
3524     }
3525
3526   if (TARGET_DEBUG_ADDR)
3527     {
3528       fprintf (stderr, "\n========== legitimate_address_p, mode = %s, result = %d, addresses are %sstrict%s\n",
3529                GET_MODE_NAME (mode), ret, (strict_p) ? "" : "not ",
3530                (condexec_p) ? ", inside conditional code" : "");
3531       debug_rtx (x);
3532     }
3533
3534   return ret;
3535 }
3536
3537 bool
3538 frv_legitimate_address_p (enum machine_mode mode, rtx x, bool strict_p)
3539 {
3540   return frv_legitimate_address_p_1 (mode, x, strict_p, FALSE, FALSE);
3541 }
3542
3543 /* Given an ADDR, generate code to inline the PLT.  */
3544 static rtx
3545 gen_inlined_tls_plt (rtx addr)
3546 {
3547   rtx retval, dest;
3548   rtx picreg = get_hard_reg_initial_val (Pmode, FDPIC_REG);
3549
3550
3551   dest = gen_reg_rtx (DImode);
3552
3553   if (flag_pic == 1)
3554     {
3555       /*
3556         -fpic version:
3557
3558         lddi.p  @(gr15, #gottlsdesc12(ADDR)), gr8
3559         calll    #gettlsoff(ADDR)@(gr8, gr0)
3560       */
3561       emit_insn (gen_tls_lddi (dest, addr, picreg));
3562     }
3563   else
3564     {
3565       /*
3566         -fPIC version:
3567
3568         sethi.p #gottlsdeschi(ADDR), gr8
3569         setlo   #gottlsdesclo(ADDR), gr8
3570         ldd     #tlsdesc(ADDR)@(gr15, gr8), gr8
3571         calll   #gettlsoff(ADDR)@(gr8, gr0)
3572       */
3573       rtx reguse = gen_reg_rtx (Pmode);
3574       emit_insn (gen_tlsoff_hilo (reguse, addr, GEN_INT (R_FRV_GOTTLSDESCHI)));
3575       emit_insn (gen_tls_tlsdesc_ldd (dest, picreg, reguse, addr));
3576     }
3577
3578   retval = gen_reg_rtx (Pmode);
3579   emit_insn (gen_tls_indirect_call (retval, addr, dest, picreg));
3580   return retval;
3581 }
3582
3583 /* Emit a TLSMOFF or TLSMOFF12 offset, depending on -mTLS.  Returns
3584    the destination address.  */
3585 static rtx
3586 gen_tlsmoff (rtx addr, rtx reg)
3587 {
3588   rtx dest = gen_reg_rtx (Pmode);
3589
3590   if (TARGET_BIG_TLS)
3591     {
3592       /* sethi.p #tlsmoffhi(x), grA
3593          setlo   #tlsmofflo(x), grA
3594       */
3595       dest = gen_reg_rtx (Pmode);
3596       emit_insn (gen_tlsoff_hilo (dest, addr,
3597                                   GEN_INT (R_FRV_TLSMOFFHI)));
3598       dest = gen_rtx_PLUS (Pmode, dest, reg);
3599     }
3600   else
3601     {
3602       /* addi grB, #tlsmoff12(x), grC
3603            -or-
3604          ld/st @(grB, #tlsmoff12(x)), grC
3605       */
3606       dest = gen_reg_rtx (Pmode);
3607       emit_insn (gen_symGOTOFF2reg_i (dest, addr, reg,
3608                                       GEN_INT (R_FRV_TLSMOFF12)));
3609     }
3610   return dest;
3611 }
3612
3613 /* Generate code for a TLS address.  */
3614 static rtx
3615 frv_legitimize_tls_address (rtx addr, enum tls_model model)
3616 {
3617   rtx dest, tp = gen_rtx_REG (Pmode, 29);
3618   rtx picreg = get_hard_reg_initial_val (Pmode, 15);
3619
3620   switch (model)
3621     {
3622     case TLS_MODEL_INITIAL_EXEC:
3623       if (flag_pic == 1)
3624         {
3625           /* -fpic version.
3626              ldi @(gr15, #gottlsoff12(x)), gr5
3627            */
3628           dest = gen_reg_rtx (Pmode);
3629           emit_insn (gen_tls_load_gottlsoff12 (dest, addr, picreg));
3630           dest = gen_rtx_PLUS (Pmode, tp, dest);
3631         }
3632       else
3633         {
3634           /* -fPIC or anything else.
3635
3636             sethi.p #gottlsoffhi(x), gr14
3637             setlo   #gottlsofflo(x), gr14
3638             ld      #tlsoff(x)@(gr15, gr14), gr9
3639           */
3640           rtx tmp = gen_reg_rtx (Pmode);
3641           dest = gen_reg_rtx (Pmode);
3642           emit_insn (gen_tlsoff_hilo (tmp, addr,
3643                                       GEN_INT (R_FRV_GOTTLSOFF_HI)));
3644
3645           emit_insn (gen_tls_tlsoff_ld (dest, picreg, tmp, addr));
3646           dest = gen_rtx_PLUS (Pmode, tp, dest);
3647         }
3648       break;
3649     case TLS_MODEL_LOCAL_DYNAMIC:
3650       {
3651         rtx reg, retval;
3652
3653         if (TARGET_INLINE_PLT)
3654           retval = gen_inlined_tls_plt (GEN_INT (0));
3655         else
3656           {
3657             /* call #gettlsoff(0) */
3658             retval = gen_reg_rtx (Pmode);
3659             emit_insn (gen_call_gettlsoff (retval, GEN_INT (0), picreg));
3660           }
3661
3662         reg = gen_reg_rtx (Pmode);
3663         emit_insn (gen_rtx_SET (VOIDmode, reg,
3664                                 gen_rtx_PLUS (Pmode,
3665                                               retval, tp)));
3666
3667         dest = gen_tlsmoff (addr, reg);
3668
3669         /*
3670         dest = gen_reg_rtx (Pmode);
3671         emit_insn (gen_tlsoff_hilo (dest, addr,
3672                                     GEN_INT (R_FRV_TLSMOFFHI)));
3673         dest = gen_rtx_PLUS (Pmode, dest, reg);
3674         */
3675         break;
3676       }
3677     case TLS_MODEL_LOCAL_EXEC:
3678       dest = gen_tlsmoff (addr, gen_rtx_REG (Pmode, 29));
3679       break;
3680     case TLS_MODEL_GLOBAL_DYNAMIC:
3681       {
3682         rtx retval;
3683
3684         if (TARGET_INLINE_PLT)
3685           retval = gen_inlined_tls_plt (addr);
3686         else
3687           {
3688             /* call #gettlsoff(x) */
3689             retval = gen_reg_rtx (Pmode);
3690             emit_insn (gen_call_gettlsoff (retval, addr, picreg));
3691           }
3692         dest = gen_rtx_PLUS (Pmode, retval, tp);
3693         break;
3694       }
3695     default:
3696       gcc_unreachable ();
3697     }
3698
3699   return dest;
3700 }
3701
3702 rtx
3703 frv_legitimize_address (rtx x,
3704                         rtx oldx ATTRIBUTE_UNUSED,
3705                         enum machine_mode mode ATTRIBUTE_UNUSED)
3706 {
3707   if (GET_CODE (x) == SYMBOL_REF)
3708     {
3709       enum tls_model model = SYMBOL_REF_TLS_MODEL (x);
3710       if (model != 0)
3711         return frv_legitimize_tls_address (x, model);
3712     }
3713
3714   return x;
3715 }
3716 \f
3717 /* Test whether a local function descriptor is canonical, i.e.,
3718    whether we can use FUNCDESC_GOTOFF to compute the address of the
3719    function.  */
3720
3721 static bool
3722 frv_local_funcdesc_p (rtx fnx)
3723 {
3724   tree fn;
3725   enum symbol_visibility vis;
3726   bool ret;
3727
3728   if (! SYMBOL_REF_LOCAL_P (fnx))
3729     return FALSE;
3730
3731   fn = SYMBOL_REF_DECL (fnx);
3732
3733   if (! fn)
3734     return FALSE;
3735
3736   vis = DECL_VISIBILITY (fn);
3737
3738   if (vis == VISIBILITY_PROTECTED)
3739     /* Private function descriptors for protected functions are not
3740        canonical.  Temporarily change the visibility to global.  */
3741     vis = VISIBILITY_DEFAULT;
3742   else if (flag_shlib)
3743     /* If we're already compiling for a shared library (that, unlike
3744        executables, can't assume that the existence of a definition
3745        implies local binding), we can skip the re-testing.  */
3746     return TRUE;
3747
3748   ret = default_binds_local_p_1 (fn, flag_pic);
3749
3750   DECL_VISIBILITY (fn) = vis;
3751
3752   return ret;
3753 }
3754
3755 /* Load the _gp symbol into DEST.  SRC is supposed to be the FDPIC
3756    register.  */
3757
3758 rtx
3759 frv_gen_GPsym2reg (rtx dest, rtx src)
3760 {
3761   tree gp = get_identifier ("_gp");
3762   rtx gp_sym = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (gp));
3763
3764   return gen_symGOT2reg (dest, gp_sym, src, GEN_INT (R_FRV_GOT12));
3765 }
3766
3767 static const char *
3768 unspec_got_name (int i)
3769 {
3770   switch (i)
3771     {
3772     case R_FRV_GOT12: return "got12";
3773     case R_FRV_GOTHI: return "gothi";
3774     case R_FRV_GOTLO: return "gotlo";
3775     case R_FRV_FUNCDESC: return "funcdesc";
3776     case R_FRV_FUNCDESC_GOT12: return "gotfuncdesc12";
3777     case R_FRV_FUNCDESC_GOTHI: return "gotfuncdeschi";
3778     case R_FRV_FUNCDESC_GOTLO: return "gotfuncdesclo";
3779     case R_FRV_FUNCDESC_VALUE: return "funcdescvalue";
3780     case R_FRV_FUNCDESC_GOTOFF12: return "gotofffuncdesc12";
3781     case R_FRV_FUNCDESC_GOTOFFHI: return "gotofffuncdeschi";
3782     case R_FRV_FUNCDESC_GOTOFFLO: return "gotofffuncdesclo";
3783     case R_FRV_GOTOFF12: return "gotoff12";
3784     case R_FRV_GOTOFFHI: return "gotoffhi";
3785     case R_FRV_GOTOFFLO: return "gotofflo";
3786     case R_FRV_GPREL12: return "gprel12";
3787     case R_FRV_GPRELHI: return "gprelhi";
3788     case R_FRV_GPRELLO: return "gprello";
3789     case R_FRV_GOTTLSOFF_HI: return "gottlsoffhi";
3790     case R_FRV_GOTTLSOFF_LO: return "gottlsofflo";
3791     case R_FRV_TLSMOFFHI: return "tlsmoffhi";
3792     case R_FRV_TLSMOFFLO: return "tlsmofflo";
3793     case R_FRV_TLSMOFF12: return "tlsmoff12";
3794     case R_FRV_TLSDESCHI: return "tlsdeschi";
3795     case R_FRV_TLSDESCLO: return "tlsdesclo";
3796     case R_FRV_GOTTLSDESCHI: return "gottlsdeschi";
3797     case R_FRV_GOTTLSDESCLO: return "gottlsdesclo";
3798     default: gcc_unreachable ();
3799     }
3800 }
3801
3802 /* Write the assembler syntax for UNSPEC to STREAM.  Note that any offset
3803    is added inside the relocation operator.  */
3804
3805 static void
3806 frv_output_const_unspec (FILE *stream, const struct frv_unspec *unspec)
3807 {
3808   fprintf (stream, "#%s(", unspec_got_name (unspec->reloc));
3809   output_addr_const (stream, plus_constant (unspec->symbol, unspec->offset));
3810   fputs (")", stream);
3811 }
3812
3813 /* Implement FIND_BASE_TERM.  See whether ORIG_X represents #gprel12(foo)
3814    or #gotoff12(foo) for some small data symbol foo.  If so, return foo,
3815    otherwise return ORIG_X.  */
3816
3817 rtx
3818 frv_find_base_term (rtx x)
3819 {
3820   struct frv_unspec unspec;
3821
3822   if (frv_const_unspec_p (x, &unspec)
3823       && frv_small_data_reloc_p (unspec.symbol, unspec.reloc))
3824     return plus_constant (unspec.symbol, unspec.offset);
3825
3826   return x;
3827 }
3828
3829 /* Return 1 if operand is a valid FRV address.  CONDEXEC_P is true if
3830    the operand is used by a predicated instruction.  */
3831
3832 int
3833 frv_legitimate_memory_operand (rtx op, enum machine_mode mode, int condexec_p)
3834 {
3835   return ((GET_MODE (op) == mode || mode == VOIDmode)
3836           && GET_CODE (op) == MEM
3837           && frv_legitimate_address_p_1 (mode, XEXP (op, 0),
3838                                          reload_completed, condexec_p, FALSE));
3839 }
3840
3841 void
3842 frv_expand_fdpic_call (rtx *operands, bool ret_value, bool sibcall)
3843 {
3844   rtx lr = gen_rtx_REG (Pmode, LR_REGNO);
3845   rtx picreg = get_hard_reg_initial_val (SImode, FDPIC_REG);
3846   rtx c, rvrtx=0;
3847   rtx addr;
3848
3849   if (ret_value)
3850     {
3851       rvrtx = operands[0];
3852       operands ++;
3853     }
3854
3855   addr = XEXP (operands[0], 0);
3856
3857   /* Inline PLTs if we're optimizing for speed.  We'd like to inline
3858      any calls that would involve a PLT, but can't tell, since we
3859      don't know whether an extern function is going to be provided by
3860      a separate translation unit or imported from a separate module.
3861      When compiling for shared libraries, if the function has default
3862      visibility, we assume it's overridable, so we inline the PLT, but
3863      for executables, we don't really have a way to make a good
3864      decision: a function is as likely to be imported from a shared
3865      library as it is to be defined in the executable itself.  We
3866      assume executables will get global functions defined locally,
3867      whereas shared libraries will have them potentially overridden,
3868      so we only inline PLTs when compiling for shared libraries.
3869
3870      In order to mark a function as local to a shared library, any
3871      non-default visibility attribute suffices.  Unfortunately,
3872      there's no simple way to tag a function declaration as ``in a
3873      different module'', which we could then use to trigger PLT
3874      inlining on executables.  There's -minline-plt, but it affects
3875      all external functions, so one would have to also mark function
3876      declarations available in the same module with non-default
3877      visibility, which is advantageous in itself.  */
3878   if (GET_CODE (addr) == SYMBOL_REF
3879       && ((!SYMBOL_REF_LOCAL_P (addr) && TARGET_INLINE_PLT)
3880           || sibcall))
3881     {
3882       rtx x, dest;
3883       dest = gen_reg_rtx (SImode);
3884       if (flag_pic != 1)
3885         x = gen_symGOTOFF2reg_hilo (dest, addr, OUR_FDPIC_REG,
3886                                     GEN_INT (R_FRV_FUNCDESC_GOTOFF12));
3887       else
3888         x = gen_symGOTOFF2reg (dest, addr, OUR_FDPIC_REG,
3889                                GEN_INT (R_FRV_FUNCDESC_GOTOFF12));
3890       emit_insn (x);
3891       crtl->uses_pic_offset_table = TRUE;
3892       addr = dest;
3893     }
3894   else if (GET_CODE (addr) == SYMBOL_REF)
3895     {
3896       /* These are always either local, or handled through a local
3897          PLT.  */
3898       if (ret_value)
3899         c = gen_call_value_fdpicsi (rvrtx, addr, operands[1],
3900                                     operands[2], picreg, lr);
3901       else
3902         c = gen_call_fdpicsi (addr, operands[1], operands[2], picreg, lr);
3903       emit_call_insn (c);
3904       return;
3905     }
3906   else if (! ldd_address_operand (addr, Pmode))
3907     addr = force_reg (Pmode, addr);
3908
3909   picreg = gen_reg_rtx (DImode);
3910   emit_insn (gen_movdi_ldd (picreg, addr));
3911
3912   if (sibcall && ret_value)
3913     c = gen_sibcall_value_fdpicdi (rvrtx, picreg, const0_rtx);
3914   else if (sibcall)
3915     c = gen_sibcall_fdpicdi (picreg, const0_rtx);
3916   else if (ret_value)
3917     c = gen_call_value_fdpicdi (rvrtx, picreg, const0_rtx, lr);
3918   else
3919     c = gen_call_fdpicdi (picreg, const0_rtx, lr);
3920   emit_call_insn (c);
3921 }
3922 \f
3923 /* Look for a SYMBOL_REF of a function in an rtx.  We always want to
3924    process these separately from any offsets, such that we add any
3925    offsets to the function descriptor (the actual pointer), not to the
3926    function address.  */
3927
3928 static bool
3929 frv_function_symbol_referenced_p (rtx x)
3930 {
3931   const char *format;
3932   int length;
3933   int j;
3934
3935   if (GET_CODE (x) == SYMBOL_REF)
3936     return SYMBOL_REF_FUNCTION_P (x);
3937
3938   length = GET_RTX_LENGTH (GET_CODE (x));
3939   format = GET_RTX_FORMAT (GET_CODE (x));
3940
3941   for (j = 0; j < length; ++j)
3942     {
3943       switch (format[j])
3944         {
3945         case 'e':
3946           if (frv_function_symbol_referenced_p (XEXP (x, j)))
3947             return TRUE;
3948           break;
3949
3950         case 'V':
3951         case 'E':
3952           if (XVEC (x, j) != 0)
3953             {
3954               int k;
3955               for (k = 0; k < XVECLEN (x, j); ++k)
3956                 if (frv_function_symbol_referenced_p (XVECEXP (x, j, k)))
3957                   return TRUE;
3958             }
3959           break;
3960
3961         default:
3962           /* Nothing to do.  */
3963           break;
3964         }
3965     }
3966
3967   return FALSE;
3968 }
3969
3970 /* Return true if the memory operand is one that can be conditionally
3971    executed.  */
3972
3973 int
3974 condexec_memory_operand (rtx op, enum machine_mode mode)
3975 {
3976   enum machine_mode op_mode = GET_MODE (op);
3977   rtx addr;
3978
3979   if (mode != VOIDmode && op_mode != mode)
3980     return FALSE;
3981
3982   switch (op_mode)
3983     {
3984     default:
3985       return FALSE;
3986
3987     case QImode:
3988     case HImode:
3989     case SImode:
3990     case SFmode:
3991       break;
3992     }
3993
3994   if (GET_CODE (op) != MEM)
3995     return FALSE;
3996
3997   addr = XEXP (op, 0);
3998   return frv_legitimate_address_p_1 (mode, addr, reload_completed, TRUE, FALSE);
3999 }
4000 \f
4001 /* Return true if the bare return instruction can be used outside of the
4002    epilog code.  For frv, we only do it if there was no stack allocation.  */
4003
4004 int
4005 direct_return_p (void)
4006 {
4007   frv_stack_t *info;
4008
4009   if (!reload_completed)
4010     return FALSE;
4011
4012   info = frv_stack_info ();
4013   return (info->total_size == 0);
4014 }
4015
4016 \f
4017 void
4018 frv_emit_move (enum machine_mode mode, rtx dest, rtx src)
4019 {
4020   if (GET_CODE (src) == SYMBOL_REF)
4021     {
4022       enum tls_model model = SYMBOL_REF_TLS_MODEL (src);
4023       if (model != 0)
4024         src = frv_legitimize_tls_address (src, model);
4025     }
4026
4027   switch (mode)
4028     {
4029     case SImode:
4030       if (frv_emit_movsi (dest, src))
4031         return;
4032       break;
4033
4034     case QImode:
4035     case HImode:
4036     case DImode:
4037     case SFmode:
4038     case DFmode:
4039       if (!reload_in_progress
4040           && !reload_completed
4041           && !register_operand (dest, mode)
4042           && !reg_or_0_operand (src, mode))
4043         src = copy_to_mode_reg (mode, src);
4044       break;
4045
4046     default:
4047       gcc_unreachable ();
4048     }
4049
4050   emit_insn (gen_rtx_SET (VOIDmode, dest, src));
4051 }
4052
4053 /* Emit code to handle a MOVSI, adding in the small data register or pic
4054    register if needed to load up addresses.  Return TRUE if the appropriate
4055    instructions are emitted.  */
4056
4057 int
4058 frv_emit_movsi (rtx dest, rtx src)
4059 {
4060   int base_regno = -1;
4061   int unspec = 0;
4062   rtx sym = src;
4063   struct frv_unspec old_unspec;
4064
4065   if (!reload_in_progress
4066       && !reload_completed
4067       && !register_operand (dest, SImode)
4068       && (!reg_or_0_operand (src, SImode)
4069              /* Virtual registers will almost always be replaced by an
4070                 add instruction, so expose this to CSE by copying to
4071                 an intermediate register.  */
4072           || (GET_CODE (src) == REG
4073               && IN_RANGE_P (REGNO (src),
4074                              FIRST_VIRTUAL_REGISTER,
4075                              LAST_VIRTUAL_POINTER_REGISTER))))
4076     {
4077       emit_insn (gen_rtx_SET (VOIDmode, dest, copy_to_mode_reg (SImode, src)));
4078       return TRUE;
4079     }
4080
4081   /* Explicitly add in the PIC or small data register if needed.  */
4082   switch (GET_CODE (src))
4083     {
4084     default:
4085       break;
4086
4087     case LABEL_REF:
4088     handle_label:
4089       if (TARGET_FDPIC)
4090         {
4091           /* Using GPREL12, we use a single GOT entry for all symbols
4092              in read-only sections, but trade sequences such as:
4093
4094              sethi #gothi(label), gr#
4095              setlo #gotlo(label), gr#
4096              ld    @(gr15,gr#), gr#
4097
4098              for
4099
4100              ld    @(gr15,#got12(_gp)), gr#
4101              sethi #gprelhi(label), gr##
4102              setlo #gprello(label), gr##
4103              add   gr#, gr##, gr##
4104
4105              We may often be able to share gr# for multiple
4106              computations of GPREL addresses, and we may often fold
4107              the final add into the pair of registers of a load or
4108              store instruction, so it's often profitable.  Even when
4109              optimizing for size, we're trading a GOT entry for an
4110              additional instruction, which trades GOT space
4111              (read-write) for code size (read-only, shareable), as
4112              long as the symbol is not used in more than two different
4113              locations.
4114
4115              With -fpie/-fpic, we'd be trading a single load for a
4116              sequence of 4 instructions, because the offset of the
4117              label can't be assumed to be addressable with 12 bits, so
4118              we don't do this.  */
4119           if (TARGET_GPREL_RO)
4120             unspec = R_FRV_GPREL12;
4121           else
4122             unspec = R_FRV_GOT12;
4123         }
4124       else if (flag_pic)
4125         base_regno = PIC_REGNO;
4126
4127       break;
4128
4129     case CONST:
4130       if (frv_const_unspec_p (src, &old_unspec))
4131         break;
4132
4133       if (TARGET_FDPIC && frv_function_symbol_referenced_p (XEXP (src, 0)))
4134         {
4135         handle_whatever:
4136           src = force_reg (GET_MODE (XEXP (src, 0)), XEXP (src, 0));
4137           emit_move_insn (dest, src);
4138           return TRUE;
4139         }
4140       else
4141         {
4142           sym = XEXP (sym, 0);
4143           if (GET_CODE (sym) == PLUS
4144               && GET_CODE (XEXP (sym, 0)) == SYMBOL_REF
4145               && GET_CODE (XEXP (sym, 1)) == CONST_INT)
4146             sym = XEXP (sym, 0);
4147           if (GET_CODE (sym) == SYMBOL_REF)
4148             goto handle_sym;
4149           else if (GET_CODE (sym) == LABEL_REF)
4150             goto handle_label;
4151           else
4152             goto handle_whatever;
4153         }
4154       break;
4155
4156     case SYMBOL_REF:
4157     handle_sym:
4158       if (TARGET_FDPIC)
4159         {
4160           enum tls_model model = SYMBOL_REF_TLS_MODEL (sym);
4161
4162           if (model != 0)
4163             {
4164               src = frv_legitimize_tls_address (src, model);
4165               emit_move_insn (dest, src);
4166               return TRUE;
4167             }
4168
4169           if (SYMBOL_REF_FUNCTION_P (sym))
4170             {
4171               if (frv_local_funcdesc_p (sym))
4172                 unspec = R_FRV_FUNCDESC_GOTOFF12;
4173               else
4174                 unspec = R_FRV_FUNCDESC_GOT12;
4175             }
4176           else
4177             {
4178               if (CONSTANT_POOL_ADDRESS_P (sym))
4179                 switch (GET_CODE (get_pool_constant (sym)))
4180                   {
4181                   case CONST:
4182                   case SYMBOL_REF:
4183                   case LABEL_REF:
4184                     if (flag_pic)
4185                       {
4186                         unspec = R_FRV_GOTOFF12;
4187                         break;
4188                       }
4189                     /* Fall through.  */
4190                   default:
4191                     if (TARGET_GPREL_RO)
4192                       unspec = R_FRV_GPREL12;
4193                     else
4194                       unspec = R_FRV_GOT12;
4195                     break;
4196                   }
4197               else if (SYMBOL_REF_LOCAL_P (sym)
4198                        && !SYMBOL_REF_EXTERNAL_P (sym)
4199                        && SYMBOL_REF_DECL (sym)
4200                        && (!DECL_P (SYMBOL_REF_DECL (sym))
4201                            || !DECL_COMMON (SYMBOL_REF_DECL (sym))))
4202                 {
4203                   tree decl = SYMBOL_REF_DECL (sym);
4204                   tree init = TREE_CODE (decl) == VAR_DECL
4205                     ? DECL_INITIAL (decl)
4206                     : TREE_CODE (decl) == CONSTRUCTOR
4207                     ? decl : 0;
4208                   int reloc = 0;
4209                   bool named_section, readonly;
4210
4211                   if (init && init != error_mark_node)
4212                     reloc = compute_reloc_for_constant (init);
4213
4214                   named_section = TREE_CODE (decl) == VAR_DECL
4215                     && lookup_attribute ("section", DECL_ATTRIBUTES (decl));
4216                   readonly = decl_readonly_section (decl, reloc);
4217
4218                   if (named_section)
4219                     unspec = R_FRV_GOT12;
4220                   else if (!readonly)
4221                     unspec = R_FRV_GOTOFF12;
4222                   else if (readonly && TARGET_GPREL_RO)
4223                     unspec = R_FRV_GPREL12;
4224                   else
4225                     unspec = R_FRV_GOT12;
4226                 }
4227               else
4228                 unspec = R_FRV_GOT12;
4229             }
4230         }
4231
4232       else if (SYMBOL_REF_SMALL_P (sym))
4233         base_regno = SDA_BASE_REG;
4234
4235       else if (flag_pic)
4236         base_regno = PIC_REGNO;
4237
4238       break;
4239     }
4240
4241   if (base_regno >= 0)
4242     {
4243       if (GET_CODE (sym) == SYMBOL_REF && SYMBOL_REF_SMALL_P (sym))
4244         emit_insn (gen_symGOTOFF2reg (dest, src,
4245                                       gen_rtx_REG (Pmode, base_regno),
4246                                       GEN_INT (R_FRV_GPREL12)));
4247       else
4248         emit_insn (gen_symGOTOFF2reg_hilo (dest, src,
4249                                            gen_rtx_REG (Pmode, base_regno),
4250                                            GEN_INT (R_FRV_GPREL12)));
4251       if (base_regno == PIC_REGNO)
4252         crtl->uses_pic_offset_table = TRUE;
4253       return TRUE;
4254     }
4255
4256   if (unspec)
4257     {
4258       rtx x;
4259
4260       /* Since OUR_FDPIC_REG is a pseudo register, we can't safely introduce
4261          new uses of it once reload has begun.  */
4262       gcc_assert (!reload_in_progress && !reload_completed);
4263
4264       switch (unspec)
4265         {
4266         case R_FRV_GOTOFF12:
4267           if (!frv_small_data_reloc_p (sym, unspec))
4268             x = gen_symGOTOFF2reg_hilo (dest, src, OUR_FDPIC_REG,
4269                                         GEN_INT (unspec));
4270           else
4271             x = gen_symGOTOFF2reg (dest, src, OUR_FDPIC_REG, GEN_INT (unspec));
4272           break;
4273         case R_FRV_GPREL12:
4274           if (!frv_small_data_reloc_p (sym, unspec))
4275             x = gen_symGPREL2reg_hilo (dest, src, OUR_FDPIC_REG,
4276                                        GEN_INT (unspec));
4277           else
4278             x = gen_symGPREL2reg (dest, src, OUR_FDPIC_REG, GEN_INT (unspec));
4279           break;
4280         case R_FRV_FUNCDESC_GOTOFF12:
4281           if (flag_pic != 1)
4282             x = gen_symGOTOFF2reg_hilo (dest, src, OUR_FDPIC_REG,
4283                                         GEN_INT (unspec));
4284           else
4285             x = gen_symGOTOFF2reg (dest, src, OUR_FDPIC_REG, GEN_INT (unspec));
4286           break;
4287         default:
4288           if (flag_pic != 1)
4289             x = gen_symGOT2reg_hilo (dest, src, OUR_FDPIC_REG,
4290                                      GEN_INT (unspec));
4291           else
4292             x = gen_symGOT2reg (dest, src, OUR_FDPIC_REG, GEN_INT (unspec));
4293           break;
4294         }
4295       emit_insn (x);
4296       crtl->uses_pic_offset_table = TRUE;
4297       return TRUE;
4298     }
4299
4300
4301   return FALSE;
4302 }
4303
4304 \f
4305 /* Return a string to output a single word move.  */
4306
4307 const char *
4308 output_move_single (rtx operands[], rtx insn)
4309 {
4310   rtx dest = operands[0];
4311   rtx src  = operands[1];
4312
4313   if (GET_CODE (dest) == REG)
4314     {
4315       int dest_regno = REGNO (dest);
4316       enum machine_mode mode = GET_MODE (dest);
4317
4318       if (GPR_P (dest_regno))
4319         {
4320           if (GET_CODE (src) == REG)
4321             {
4322               /* gpr <- some sort of register */
4323               int src_regno = REGNO (src);
4324
4325               if (GPR_P (src_regno))
4326                 return "mov %1, %0";
4327
4328               else if (FPR_P (src_regno))
4329                 return "movfg %1, %0";
4330
4331               else if (SPR_P (src_regno))
4332                 return "movsg %1, %0";
4333             }
4334
4335           else if (GET_CODE (src) == MEM)
4336             {
4337               /* gpr <- memory */
4338               switch (mode)
4339                 {
4340                 default:
4341                   break;
4342
4343                 case QImode:
4344                   return "ldsb%I1%U1 %M1,%0";
4345
4346                 case HImode:
4347                   return "ldsh%I1%U1 %M1,%0";
4348
4349                 case SImode:
4350                 case SFmode:
4351                   return "ld%I1%U1 %M1, %0";
4352                 }
4353             }
4354
4355           else if (GET_CODE (src) == CONST_INT
4356                    || GET_CODE (src) == CONST_DOUBLE)
4357             {
4358               /* gpr <- integer/floating constant */
4359               HOST_WIDE_INT value;
4360
4361               if (GET_CODE (src) == CONST_INT)
4362                 value = INTVAL (src);
4363
4364               else if (mode == SFmode)
4365                 {
4366                   REAL_VALUE_TYPE rv;
4367                   long l;
4368
4369                   REAL_VALUE_FROM_CONST_DOUBLE (rv, src);
4370                   REAL_VALUE_TO_TARGET_SINGLE (rv, l);
4371                   value = l;
4372                 }
4373
4374               else
4375                 value = CONST_DOUBLE_LOW (src);
4376
4377               if (IN_RANGE_P (value, -32768, 32767))
4378                 return "setlos %1, %0";
4379
4380               return "#";
4381             }
4382
4383           else if (GET_CODE (src) == SYMBOL_REF
4384                    || GET_CODE (src) == LABEL_REF
4385                    || GET_CODE (src) == CONST)
4386             {
4387               return "#";
4388             }
4389         }
4390
4391       else if (FPR_P (dest_regno))
4392         {
4393           if (GET_CODE (src) == REG)
4394             {
4395               /* fpr <- some sort of register */
4396               int src_regno = REGNO (src);
4397
4398               if (GPR_P (src_regno))
4399                 return "movgf %1, %0";
4400
4401               else if (FPR_P (src_regno))
4402                 {
4403                   if (TARGET_HARD_FLOAT)
4404                     return "fmovs %1, %0";
4405                   else
4406                     return "mor %1, %1, %0";
4407                 }
4408             }
4409
4410           else if (GET_CODE (src) == MEM)
4411             {
4412               /* fpr <- memory */
4413               switch (mode)
4414                 {
4415                 default:
4416                   break;
4417
4418                 case QImode:
4419                   return "ldbf%I1%U1 %M1,%0";
4420
4421                 case HImode:
4422                   return "ldhf%I1%U1 %M1,%0";
4423
4424                 case SImode:
4425                 case SFmode:
4426                   return "ldf%I1%U1 %M1, %0";
4427                 }
4428             }
4429
4430           else if (ZERO_P (src))
4431             return "movgf %., %0";
4432         }
4433
4434       else if (SPR_P (dest_regno))
4435         {
4436           if (GET_CODE (src) == REG)
4437             {
4438               /* spr <- some sort of register */
4439               int src_regno = REGNO (src);
4440
4441               if (GPR_P (src_regno))
4442                 return "movgs %1, %0";
4443             }
4444           else if (ZERO_P (src))
4445             return "movgs %., %0";
4446         }
4447     }
4448
4449   else if (GET_CODE (dest) == MEM)
4450     {
4451       if (GET_CODE (src) == REG)
4452         {
4453           int src_regno = REGNO (src);
4454           enum machine_mode mode = GET_MODE (dest);
4455
4456           if (GPR_P (src_regno))
4457             {
4458               switch (mode)
4459                 {
4460                 default:
4461                   break;
4462
4463                 case QImode:
4464                   return "stb%I0%U0 %1, %M0";
4465
4466                 case HImode:
4467                   return "sth%I0%U0 %1, %M0";
4468
4469                 case SImode:
4470                 case SFmode:
4471                   return "st%I0%U0 %1, %M0";
4472                 }
4473             }
4474
4475           else if (FPR_P (src_regno))
4476             {
4477               switch (mode)
4478                 {
4479                 default:
4480                   break;
4481
4482                 case QImode:
4483                   return "stbf%I0%U0 %1, %M0";
4484
4485                 case HImode:
4486                   return "sthf%I0%U0 %1, %M0";
4487
4488                 case SImode:
4489                 case SFmode:
4490                   return "stf%I0%U0 %1, %M0";
4491                 }
4492             }
4493         }
4494
4495       else if (ZERO_P (src))
4496         {
4497           switch (GET_MODE (dest))
4498             {
4499             default:
4500               break;
4501
4502             case QImode:
4503               return "stb%I0%U0 %., %M0";
4504
4505             case HImode:
4506               return "sth%I0%U0 %., %M0";
4507
4508             case SImode:
4509             case SFmode:
4510               return "st%I0%U0 %., %M0";
4511             }
4512         }
4513     }
4514
4515   fatal_insn ("bad output_move_single operand", insn);
4516   return "";
4517 }
4518
4519 \f
4520 /* Return a string to output a double word move.  */
4521
4522 const char *
4523 output_move_double (rtx operands[], rtx insn)
4524 {
4525   rtx dest = operands[0];
4526   rtx src  = operands[1];
4527   enum machine_mode mode = GET_MODE (dest);
4528
4529   if (GET_CODE (dest) == REG)
4530     {
4531       int dest_regno = REGNO (dest);
4532
4533       if (GPR_P (dest_regno))
4534         {
4535           if (GET_CODE (src) == REG)
4536             {
4537               /* gpr <- some sort of register */
4538               int src_regno = REGNO (src);
4539
4540               if (GPR_P (src_regno))
4541                 return "#";
4542
4543               else if (FPR_P (src_regno))
4544                 {
4545                   if (((dest_regno - GPR_FIRST) & 1) == 0
4546                       && ((src_regno - FPR_FIRST) & 1) == 0)
4547                     return "movfgd %1, %0";
4548
4549                   return "#";
4550                 }
4551             }
4552
4553           else if (GET_CODE (src) == MEM)
4554             {
4555               /* gpr <- memory */
4556               if (dbl_memory_one_insn_operand (src, mode))
4557                 return "ldd%I1%U1 %M1, %0";
4558
4559               return "#";
4560             }
4561
4562           else if (GET_CODE (src) == CONST_INT
4563                    || GET_CODE (src) == CONST_DOUBLE)
4564             return "#";
4565         }
4566
4567       else if (FPR_P (dest_regno))
4568         {
4569           if (GET_CODE (src) == REG)
4570             {
4571               /* fpr <- some sort of register */
4572               int src_regno = REGNO (src);
4573
4574               if (GPR_P (src_regno))
4575                 {
4576                   if (((dest_regno - FPR_FIRST) & 1) == 0
4577                       && ((src_regno - GPR_FIRST) & 1) == 0)
4578                     return "movgfd %1, %0";
4579
4580                   return "#";
4581                 }
4582
4583               else if (FPR_P (src_regno))
4584                 {
4585                   if (TARGET_DOUBLE
4586                       && ((dest_regno - FPR_FIRST) & 1) == 0
4587                       && ((src_regno - FPR_FIRST) & 1) == 0)
4588                     return "fmovd %1, %0";
4589
4590                   return "#";
4591                 }
4592             }
4593
4594           else if (GET_CODE (src) == MEM)
4595             {
4596               /* fpr <- memory */
4597               if (dbl_memory_one_insn_operand (src, mode))
4598                 return "lddf%I1%U1 %M1, %0";
4599
4600               return "#";
4601             }
4602
4603           else if (ZERO_P (src))
4604             return "#";
4605         }
4606     }
4607
4608   else if (GET_CODE (dest) == MEM)
4609     {
4610       if (GET_CODE (src) == REG)
4611         {
4612           int src_regno = REGNO (src);
4613
4614           if (GPR_P (src_regno))
4615             {
4616               if (((src_regno - GPR_FIRST) & 1) == 0
4617                   && dbl_memory_one_insn_operand (dest, mode))
4618                 return "std%I0%U0 %1, %M0";
4619
4620               return "#";
4621             }
4622
4623           if (FPR_P (src_regno))
4624             {
4625               if (((src_regno - FPR_FIRST) & 1) == 0
4626                   && dbl_memory_one_insn_operand (dest, mode))
4627                 return "stdf%I0%U0 %1, %M0";
4628
4629               return "#";
4630             }
4631         }
4632
4633       else if (ZERO_P (src))
4634         {
4635           if (dbl_memory_one_insn_operand (dest, mode))
4636             return "std%I0%U0 %., %M0";
4637
4638           return "#";
4639         }
4640     }
4641
4642   fatal_insn ("bad output_move_double operand", insn);
4643   return "";
4644 }
4645
4646 \f
4647 /* Return a string to output a single word conditional move.
4648    Operand0 -- EQ/NE of ccr register and 0
4649    Operand1 -- CCR register
4650    Operand2 -- destination
4651    Operand3 -- source  */
4652
4653 const char *
4654 output_condmove_single (rtx operands[], rtx insn)
4655 {
4656   rtx dest = operands[2];
4657   rtx src  = operands[3];
4658
4659   if (GET_CODE (dest) == REG)
4660     {
4661       int dest_regno = REGNO (dest);
4662       enum machine_mode mode = GET_MODE (dest);
4663
4664       if (GPR_P (dest_regno))
4665         {
4666           if (GET_CODE (src) == REG)
4667             {
4668               /* gpr <- some sort of register */
4669               int src_regno = REGNO (src);
4670
4671               if (GPR_P (src_regno))
4672                 return "cmov %z3, %2, %1, %e0";
4673
4674               else if (FPR_P (src_regno))
4675                 return "cmovfg %3, %2, %1, %e0";
4676             }
4677
4678           else if (GET_CODE (src) == MEM)
4679             {
4680               /* gpr <- memory */
4681               switch (mode)
4682                 {
4683                 default:
4684                   break;
4685
4686                 case QImode:
4687                   return "cldsb%I3%U3 %M3, %2, %1, %e0";
4688
4689                 case HImode:
4690                   return "cldsh%I3%U3 %M3, %2, %1, %e0";
4691
4692                 case SImode:
4693                 case SFmode:
4694                   return "cld%I3%U3 %M3, %2, %1, %e0";
4695                 }
4696             }
4697
4698           else if (ZERO_P (src))
4699             return "cmov %., %2, %1, %e0";
4700         }
4701
4702       else if (FPR_P (dest_regno))
4703         {
4704           if (GET_CODE (src) == REG)
4705             {
4706               /* fpr <- some sort of register */
4707               int src_regno = REGNO (src);
4708
4709               if (GPR_P (src_regno))
4710                 return "cmovgf %3, %2, %1, %e0";
4711
4712               else if (FPR_P (src_regno))
4713                 {
4714                   if (TARGET_HARD_FLOAT)
4715                     return "cfmovs %3,%2,%1,%e0";
4716                   else
4717                     return "cmor %3, %3, %2, %1, %e0";
4718                 }
4719             }
4720
4721           else if (GET_CODE (src) == MEM)
4722             {
4723               /* fpr <- memory */
4724               if (mode == SImode || mode == SFmode)
4725                 return "cldf%I3%U3 %M3, %2, %1, %e0";
4726             }
4727
4728           else if (ZERO_P (src))
4729             return "cmovgf %., %2, %1, %e0";
4730         }
4731     }
4732
4733   else if (GET_CODE (dest) == MEM)
4734     {
4735       if (GET_CODE (src) == REG)
4736         {
4737           int src_regno = REGNO (src);
4738           enum machine_mode mode = GET_MODE (dest);
4739
4740           if (GPR_P (src_regno))
4741             {
4742               switch (mode)
4743                 {
4744                 default:
4745                   break;
4746
4747                 case QImode:
4748                   return "cstb%I2%U2 %3, %M2, %1, %e0";
4749
4750                 case HImode:
4751                   return "csth%I2%U2 %3, %M2, %1, %e0";
4752
4753                 case SImode:
4754                 case SFmode:
4755                   return "cst%I2%U2 %3, %M2, %1, %e0";
4756                 }
4757             }
4758
4759           else if (FPR_P (src_regno) && (mode == SImode || mode == SFmode))
4760             return "cstf%I2%U2 %3, %M2, %1, %e0";
4761         }
4762
4763       else if (ZERO_P (src))
4764         {
4765           enum machine_mode mode = GET_MODE (dest);
4766           switch (mode)
4767             {
4768             default:
4769               break;
4770
4771             case QImode:
4772               return "cstb%I2%U2 %., %M2, %1, %e0";
4773
4774             case HImode:
4775               return "csth%I2%U2 %., %M2, %1, %e0";
4776
4777             case SImode:
4778             case SFmode:
4779               return "cst%I2%U2 %., %M2, %1, %e0";
4780             }
4781         }
4782     }
4783
4784   fatal_insn ("bad output_condmove_single operand", insn);
4785   return "";
4786 }
4787
4788 \f
4789 /* Emit the appropriate code to do a comparison, returning the register the
4790    comparison was done it.  */
4791
4792 static rtx
4793 frv_emit_comparison (enum rtx_code test, rtx op0, rtx op1)
4794 {
4795   enum machine_mode cc_mode;
4796   rtx cc_reg;
4797
4798   /* Floating point doesn't have comparison against a constant.  */
4799   if (GET_MODE (op0) == CC_FPmode && GET_CODE (op1) != REG)
4800     op1 = force_reg (GET_MODE (op0), op1);
4801
4802   /* Possibly disable using anything but a fixed register in order to work
4803      around cse moving comparisons past function calls.  */
4804   cc_mode = SELECT_CC_MODE (test, op0, op1);
4805   cc_reg = ((TARGET_ALLOC_CC)
4806             ? gen_reg_rtx (cc_mode)
4807             : gen_rtx_REG (cc_mode,
4808                            (cc_mode == CC_FPmode) ? FCC_FIRST : ICC_FIRST));
4809
4810   emit_insn (gen_rtx_SET (VOIDmode, cc_reg,
4811                           gen_rtx_COMPARE (cc_mode, op0, op1)));
4812
4813   return cc_reg;
4814 }
4815
4816 \f
4817 /* Emit code for a conditional branch.
4818    XXX: I originally wanted to add a clobber of a CCR register to use in
4819    conditional execution, but that confuses the rest of the compiler.  */
4820
4821 int
4822 frv_emit_cond_branch (rtx operands[])
4823 {
4824   rtx test_rtx;
4825   rtx label_ref;
4826   rtx if_else;
4827   enum rtx_code test = GET_CODE (operands[0]);
4828   rtx cc_reg = frv_emit_comparison (test, operands[1], operands[2]);
4829   enum machine_mode cc_mode = GET_MODE (cc_reg);
4830
4831   /* Branches generate:
4832         (set (pc)
4833              (if_then_else (<test>, <cc_reg>, (const_int 0))
4834                             (label_ref <branch_label>)
4835                             (pc))) */
4836   label_ref = gen_rtx_LABEL_REF (VOIDmode, operands[3]);
4837   test_rtx = gen_rtx_fmt_ee (test, cc_mode, cc_reg, const0_rtx);
4838   if_else = gen_rtx_IF_THEN_ELSE (cc_mode, test_rtx, label_ref, pc_rtx);
4839   emit_jump_insn (gen_rtx_SET (VOIDmode, pc_rtx, if_else));
4840   return TRUE;
4841 }
4842
4843 \f
4844 /* Emit code to set a gpr to 1/0 based on a comparison.  */
4845
4846 int
4847 frv_emit_scc (rtx operands[])
4848 {
4849   rtx set;
4850   rtx test_rtx;
4851   rtx clobber;
4852   rtx cr_reg;
4853   enum rtx_code test = GET_CODE (operands[1]);
4854   rtx cc_reg = frv_emit_comparison (test, operands[2], operands[3]);
4855
4856   /* SCC instructions generate:
4857         (parallel [(set <target> (<test>, <cc_reg>, (const_int 0))
4858                    (clobber (<ccr_reg>))])  */
4859   test_rtx = gen_rtx_fmt_ee (test, SImode, cc_reg, const0_rtx);
4860   set = gen_rtx_SET (VOIDmode, operands[0], test_rtx);
4861
4862   cr_reg = ((TARGET_ALLOC_CC)
4863             ? gen_reg_rtx (CC_CCRmode)
4864             : gen_rtx_REG (CC_CCRmode,
4865                            ((GET_MODE (cc_reg) == CC_FPmode)
4866                             ? FCR_FIRST
4867                             : ICR_FIRST)));
4868
4869   clobber = gen_rtx_CLOBBER (VOIDmode, cr_reg);
4870   emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber)));
4871   return TRUE;
4872 }
4873
4874 \f
4875 /* Split a SCC instruction into component parts, returning a SEQUENCE to hold
4876    the separate insns.  */
4877
4878 rtx
4879 frv_split_scc (rtx dest, rtx test, rtx cc_reg, rtx cr_reg, HOST_WIDE_INT value)
4880 {
4881   rtx ret;
4882
4883   start_sequence ();
4884
4885   /* Set the appropriate CCR bit.  */
4886   emit_insn (gen_rtx_SET (VOIDmode,
4887                           cr_reg,
4888                           gen_rtx_fmt_ee (GET_CODE (test),
4889                                           GET_MODE (cr_reg),
4890                                           cc_reg,
4891                                           const0_rtx)));
4892
4893   /* Move the value into the destination.  */
4894   emit_move_insn (dest, GEN_INT (value));
4895
4896   /* Move 0 into the destination if the test failed */
4897   emit_insn (gen_rtx_COND_EXEC (VOIDmode,
4898                                 gen_rtx_EQ (GET_MODE (cr_reg),
4899                                             cr_reg,
4900                                             const0_rtx),
4901                                 gen_rtx_SET (VOIDmode, dest, const0_rtx)));
4902
4903   /* Finish up, return sequence.  */
4904   ret = get_insns ();
4905   end_sequence ();
4906   return ret;
4907 }
4908
4909 \f
4910 /* Emit the code for a conditional move, return TRUE if we could do the
4911    move.  */
4912
4913 int
4914 frv_emit_cond_move (rtx dest, rtx test_rtx, rtx src1, rtx src2)
4915 {
4916   rtx set;
4917   rtx clobber_cc;
4918   rtx test2;
4919   rtx cr_reg;
4920   rtx if_rtx;
4921   enum rtx_code test = GET_CODE (test_rtx);
4922   rtx cc_reg = frv_emit_comparison (test,
4923                                     XEXP (test_rtx, 0), XEXP (test_rtx, 1));
4924   enum machine_mode cc_mode = GET_MODE (cc_reg);
4925
4926   /* Conditional move instructions generate:
4927         (parallel [(set <target>
4928                         (if_then_else (<test> <cc_reg> (const_int 0))
4929                                       <src1>
4930                                       <src2>))
4931                    (clobber (<ccr_reg>))])  */
4932
4933   /* Handle various cases of conditional move involving two constants.  */
4934   if (GET_CODE (src1) == CONST_INT && GET_CODE (src2) == CONST_INT)
4935     {
4936       HOST_WIDE_INT value1 = INTVAL (src1);
4937       HOST_WIDE_INT value2 = INTVAL (src2);
4938
4939       /* Having 0 as one of the constants can be done by loading the other
4940          constant, and optionally moving in gr0.  */
4941       if (value1 == 0 || value2 == 0)
4942         ;
4943
4944       /* If the first value is within an addi range and also the difference
4945          between the two fits in an addi's range, load up the difference, then
4946          conditionally move in 0, and then unconditionally add the first
4947          value.  */
4948       else if (IN_RANGE_P (value1, -2048, 2047)
4949                && IN_RANGE_P (value2 - value1, -2048, 2047))
4950         ;
4951
4952       /* If neither condition holds, just force the constant into a
4953          register.  */
4954       else
4955         {
4956           src1 = force_reg (GET_MODE (dest), src1);
4957           src2 = force_reg (GET_MODE (dest), src2);
4958         }
4959     }
4960
4961   /* If one value is a register, insure the other value is either 0 or a
4962      register.  */
4963   else
4964     {
4965       if (GET_CODE (src1) == CONST_INT && INTVAL (src1) != 0)
4966         src1 = force_reg (GET_MODE (dest), src1);
4967
4968       if (GET_CODE (src2) == CONST_INT && INTVAL (src2) != 0)
4969         src2 = force_reg (GET_MODE (dest), src2);
4970     }
4971
4972   test2 = gen_rtx_fmt_ee (test, cc_mode, cc_reg, const0_rtx);
4973   if_rtx = gen_rtx_IF_THEN_ELSE (GET_MODE (dest), test2, src1, src2);
4974
4975   set = gen_rtx_SET (VOIDmode, dest, if_rtx);
4976
4977   cr_reg = ((TARGET_ALLOC_CC)
4978             ? gen_reg_rtx (CC_CCRmode)
4979             : gen_rtx_REG (CC_CCRmode,
4980                            (cc_mode == CC_FPmode) ? FCR_FIRST : ICR_FIRST));
4981
4982   clobber_cc = gen_rtx_CLOBBER (VOIDmode, cr_reg);
4983   emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber_cc)));
4984   return TRUE;
4985 }
4986
4987 \f
4988 /* Split a conditional move into constituent parts, returning a SEQUENCE
4989    containing all of the insns.  */
4990
4991 rtx
4992 frv_split_cond_move (rtx operands[])
4993 {
4994   rtx dest      = operands[0];
4995   rtx test      = operands[1];
4996   rtx cc_reg    = operands[2];
4997   rtx src1      = operands[3];
4998   rtx src2      = operands[4];
4999   rtx cr_reg    = operands[5];
5000   rtx ret;
5001   enum machine_mode cr_mode = GET_MODE (cr_reg);
5002
5003   start_sequence ();
5004
5005   /* Set the appropriate CCR bit.  */
5006   emit_insn (gen_rtx_SET (VOIDmode,
5007                           cr_reg,
5008                           gen_rtx_fmt_ee (GET_CODE (test),
5009                                           GET_MODE (cr_reg),
5010                                           cc_reg,
5011                                           const0_rtx)));
5012
5013   /* Handle various cases of conditional move involving two constants.  */
5014   if (GET_CODE (src1) == CONST_INT && GET_CODE (src2) == CONST_INT)
5015     {
5016       HOST_WIDE_INT value1 = INTVAL (src1);
5017       HOST_WIDE_INT value2 = INTVAL (src2);
5018
5019       /* Having 0 as one of the constants can be done by loading the other
5020          constant, and optionally moving in gr0.  */
5021       if (value1 == 0)
5022         {
5023           emit_move_insn (dest, src2);
5024           emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5025                                         gen_rtx_NE (cr_mode, cr_reg,
5026                                                     const0_rtx),
5027                                         gen_rtx_SET (VOIDmode, dest, src1)));
5028         }
5029
5030       else if (value2 == 0)
5031         {
5032           emit_move_insn (dest, src1);
5033           emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5034                                         gen_rtx_EQ (cr_mode, cr_reg,
5035                                                     const0_rtx),
5036                                         gen_rtx_SET (VOIDmode, dest, src2)));
5037         }
5038
5039       /* If the first value is within an addi range and also the difference
5040          between the two fits in an addi's range, load up the difference, then
5041          conditionally move in 0, and then unconditionally add the first
5042          value.  */
5043       else if (IN_RANGE_P (value1, -2048, 2047)
5044                && IN_RANGE_P (value2 - value1, -2048, 2047))
5045         {
5046           rtx dest_si = ((GET_MODE (dest) == SImode)
5047                          ? dest
5048                          : gen_rtx_SUBREG (SImode, dest, 0));
5049
5050           emit_move_insn (dest_si, GEN_INT (value2 - value1));
5051           emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5052                                         gen_rtx_NE (cr_mode, cr_reg,
5053                                                     const0_rtx),
5054                                         gen_rtx_SET (VOIDmode, dest_si,
5055                                                      const0_rtx)));
5056           emit_insn (gen_addsi3 (dest_si, dest_si, src1));
5057         }
5058
5059       else
5060         gcc_unreachable ();
5061     }
5062   else
5063     {
5064       /* Emit the conditional move for the test being true if needed.  */
5065       if (! rtx_equal_p (dest, src1))
5066         emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5067                                       gen_rtx_NE (cr_mode, cr_reg, const0_rtx),
5068                                       gen_rtx_SET (VOIDmode, dest, src1)));
5069
5070       /* Emit the conditional move for the test being false if needed.  */
5071       if (! rtx_equal_p (dest, src2))
5072         emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5073                                       gen_rtx_EQ (cr_mode, cr_reg, const0_rtx),
5074                                       gen_rtx_SET (VOIDmode, dest, src2)));
5075     }
5076
5077   /* Finish up, return sequence.  */
5078   ret = get_insns ();
5079   end_sequence ();
5080   return ret;
5081 }
5082
5083 \f
5084 /* Split (set DEST SOURCE), where DEST is a double register and SOURCE is a
5085    memory location that is not known to be dword-aligned.  */
5086 void
5087 frv_split_double_load (rtx dest, rtx source)
5088 {
5089   int regno = REGNO (dest);
5090   rtx dest1 = gen_highpart (SImode, dest);
5091   rtx dest2 = gen_lowpart (SImode, dest);
5092   rtx address = XEXP (source, 0);
5093
5094   /* If the address is pre-modified, load the lower-numbered register
5095      first, then load the other register using an integer offset from
5096      the modified base register.  This order should always be safe,
5097      since the pre-modification cannot affect the same registers as the
5098      load does.
5099
5100      The situation for other loads is more complicated.  Loading one
5101      of the registers could affect the value of ADDRESS, so we must
5102      be careful which order we do them in.  */
5103   if (GET_CODE (address) == PRE_MODIFY
5104       || ! refers_to_regno_p (regno, regno + 1, address, NULL))
5105     {
5106       /* It is safe to load the lower-numbered register first.  */
5107       emit_move_insn (dest1, change_address (source, SImode, NULL));
5108       emit_move_insn (dest2, frv_index_memory (source, SImode, 1));
5109     }
5110   else
5111     {
5112       /* ADDRESS is not pre-modified and the address depends on the
5113          lower-numbered register.  Load the higher-numbered register
5114          first.  */
5115       emit_move_insn (dest2, frv_index_memory (source, SImode, 1));
5116       emit_move_insn (dest1, change_address (source, SImode, NULL));
5117     }
5118 }
5119
5120 /* Split (set DEST SOURCE), where DEST refers to a dword memory location
5121    and SOURCE is either a double register or the constant zero.  */
5122 void
5123 frv_split_double_store (rtx dest, rtx source)
5124 {
5125   rtx dest1 = change_address (dest, SImode, NULL);
5126   rtx dest2 = frv_index_memory (dest, SImode, 1);
5127   if (ZERO_P (source))
5128     {
5129       emit_move_insn (dest1, CONST0_RTX (SImode));
5130       emit_move_insn (dest2, CONST0_RTX (SImode));
5131     }
5132   else
5133     {
5134       emit_move_insn (dest1, gen_highpart (SImode, source));
5135       emit_move_insn (dest2, gen_lowpart (SImode, source));
5136     }
5137 }
5138
5139 \f
5140 /* Split a min/max operation returning a SEQUENCE containing all of the
5141    insns.  */
5142
5143 rtx
5144 frv_split_minmax (rtx operands[])
5145 {
5146   rtx dest      = operands[0];
5147   rtx minmax    = operands[1];
5148   rtx src1      = operands[2];
5149   rtx src2      = operands[3];
5150   rtx cc_reg    = operands[4];
5151   rtx cr_reg    = operands[5];
5152   rtx ret;
5153   enum rtx_code test_code;
5154   enum machine_mode cr_mode = GET_MODE (cr_reg);
5155
5156   start_sequence ();
5157
5158   /* Figure out which test to use.  */
5159   switch (GET_CODE (minmax))
5160     {
5161     default:
5162       gcc_unreachable ();
5163
5164     case SMIN: test_code = LT;  break;
5165     case SMAX: test_code = GT;  break;
5166     case UMIN: test_code = LTU; break;
5167     case UMAX: test_code = GTU; break;
5168     }
5169
5170   /* Issue the compare instruction.  */
5171   emit_insn (gen_rtx_SET (VOIDmode,
5172                           cc_reg,
5173                           gen_rtx_COMPARE (GET_MODE (cc_reg),
5174                                            src1, src2)));
5175
5176   /* Set the appropriate CCR bit.  */
5177   emit_insn (gen_rtx_SET (VOIDmode,
5178                           cr_reg,
5179                           gen_rtx_fmt_ee (test_code,
5180                                           GET_MODE (cr_reg),
5181                                           cc_reg,
5182                                           const0_rtx)));
5183
5184   /* If are taking the min/max of a nonzero constant, load that first, and
5185      then do a conditional move of the other value.  */
5186   if (GET_CODE (src2) == CONST_INT && INTVAL (src2) != 0)
5187     {
5188       gcc_assert (!rtx_equal_p (dest, src1));
5189
5190       emit_move_insn (dest, src2);
5191       emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5192                                     gen_rtx_NE (cr_mode, cr_reg, const0_rtx),
5193                                     gen_rtx_SET (VOIDmode, dest, src1)));
5194     }
5195
5196   /* Otherwise, do each half of the move.  */
5197   else
5198     {
5199       /* Emit the conditional move for the test being true if needed.  */
5200       if (! rtx_equal_p (dest, src1))
5201         emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5202                                       gen_rtx_NE (cr_mode, cr_reg, const0_rtx),
5203                                       gen_rtx_SET (VOIDmode, dest, src1)));
5204
5205       /* Emit the conditional move for the test being false if needed.  */
5206       if (! rtx_equal_p (dest, src2))
5207         emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5208                                       gen_rtx_EQ (cr_mode, cr_reg, const0_rtx),
5209                                       gen_rtx_SET (VOIDmode, dest, src2)));
5210     }
5211
5212   /* Finish up, return sequence.  */
5213   ret = get_insns ();
5214   end_sequence ();
5215   return ret;
5216 }
5217
5218 \f
5219 /* Split an integer abs operation returning a SEQUENCE containing all of the
5220    insns.  */
5221
5222 rtx
5223 frv_split_abs (rtx operands[])
5224 {
5225   rtx dest      = operands[0];
5226   rtx src       = operands[1];
5227   rtx cc_reg    = operands[2];
5228   rtx cr_reg    = operands[3];
5229   rtx ret;
5230
5231   start_sequence ();
5232
5233   /* Issue the compare < 0 instruction.  */
5234   emit_insn (gen_rtx_SET (VOIDmode,
5235                           cc_reg,
5236                           gen_rtx_COMPARE (CCmode, src, const0_rtx)));
5237
5238   /* Set the appropriate CCR bit.  */
5239   emit_insn (gen_rtx_SET (VOIDmode,
5240                           cr_reg,
5241                           gen_rtx_fmt_ee (LT, CC_CCRmode, cc_reg, const0_rtx)));
5242
5243   /* Emit the conditional negate if the value is negative.  */
5244   emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5245                                 gen_rtx_NE (CC_CCRmode, cr_reg, const0_rtx),
5246                                 gen_negsi2 (dest, src)));
5247
5248   /* Emit the conditional move for the test being false if needed.  */
5249   if (! rtx_equal_p (dest, src))
5250     emit_insn (gen_rtx_COND_EXEC (VOIDmode,
5251                                   gen_rtx_EQ (CC_CCRmode, cr_reg, const0_rtx),
5252                                   gen_rtx_SET (VOIDmode, dest, src)));
5253
5254   /* Finish up, return sequence.  */
5255   ret = get_insns ();
5256   end_sequence ();
5257   return ret;
5258 }
5259
5260 \f
5261 /* An internal function called by for_each_rtx to clear in a hard_reg set each
5262    register used in an insn.  */
5263
5264 static int
5265 frv_clear_registers_used (rtx *ptr, void *data)
5266 {
5267   if (GET_CODE (*ptr) == REG)
5268     {
5269       int regno = REGNO (*ptr);
5270       HARD_REG_SET *p_regs = (HARD_REG_SET *)data;
5271
5272       if (regno < FIRST_PSEUDO_REGISTER)
5273         {
5274           int reg_max = regno + HARD_REGNO_NREGS (regno, GET_MODE (*ptr));
5275
5276           while (regno < reg_max)
5277             {
5278               CLEAR_HARD_REG_BIT (*p_regs, regno);
5279               regno++;
5280             }
5281         }
5282     }
5283
5284   return 0;
5285 }
5286
5287 \f
5288 /* Initialize the extra fields provided by IFCVT_EXTRA_FIELDS.  */
5289
5290 /* On the FR-V, we don't have any extra fields per se, but it is useful hook to
5291    initialize the static storage.  */
5292 void
5293 frv_ifcvt_init_extra_fields (ce_if_block_t *ce_info ATTRIBUTE_UNUSED)
5294 {
5295   frv_ifcvt.added_insns_list = NULL_RTX;
5296   frv_ifcvt.cur_scratch_regs = 0;
5297   frv_ifcvt.num_nested_cond_exec = 0;
5298   frv_ifcvt.cr_reg = NULL_RTX;
5299   frv_ifcvt.nested_cc_reg = NULL_RTX;
5300   frv_ifcvt.extra_int_cr = NULL_RTX;
5301   frv_ifcvt.extra_fp_cr = NULL_RTX;
5302   frv_ifcvt.last_nested_if_cr = NULL_RTX;
5303 }
5304
5305 \f
5306 /* Internal function to add a potential insn to the list of insns to be inserted
5307    if the conditional execution conversion is successful.  */
5308
5309 static void
5310 frv_ifcvt_add_insn (rtx pattern, rtx insn, int before_p)
5311 {
5312   rtx link = alloc_EXPR_LIST (VOIDmode, pattern, insn);
5313
5314   link->jump = before_p;        /* Mark to add this before or after insn.  */
5315   frv_ifcvt.added_insns_list = alloc_EXPR_LIST (VOIDmode, link,
5316                                                 frv_ifcvt.added_insns_list);
5317
5318   if (TARGET_DEBUG_COND_EXEC)
5319     {
5320       fprintf (stderr,
5321                "\n:::::::::: frv_ifcvt_add_insn: add the following %s insn %d:\n",
5322                (before_p) ? "before" : "after",
5323                (int)INSN_UID (insn));
5324
5325       debug_rtx (pattern);
5326     }
5327 }
5328
5329 \f
5330 /* A C expression to modify the code described by the conditional if
5331    information CE_INFO, possibly updating the tests in TRUE_EXPR, and
5332    FALSE_EXPR for converting if-then and if-then-else code to conditional
5333    instructions.  Set either TRUE_EXPR or FALSE_EXPR to a null pointer if the
5334    tests cannot be converted.  */
5335
5336 void
5337 frv_ifcvt_modify_tests (ce_if_block_t *ce_info, rtx *p_true, rtx *p_false)
5338 {
5339   basic_block test_bb = ce_info->test_bb;       /* test basic block */
5340   basic_block then_bb = ce_info->then_bb;       /* THEN */
5341   basic_block else_bb = ce_info->else_bb;       /* ELSE or NULL */
5342   basic_block join_bb = ce_info->join_bb;       /* join block or NULL */
5343   rtx true_expr = *p_true;
5344   rtx cr;
5345   rtx cc;
5346   rtx nested_cc;
5347   enum machine_mode mode = GET_MODE (true_expr);
5348   int j;
5349   basic_block *bb;
5350   int num_bb;
5351   frv_tmp_reg_t *tmp_reg = &frv_ifcvt.tmp_reg;
5352   rtx check_insn;
5353   rtx sub_cond_exec_reg;
5354   enum rtx_code code;
5355   enum rtx_code code_true;
5356   enum rtx_code code_false;
5357   enum reg_class cc_class;
5358   enum reg_class cr_class;
5359   int cc_first;
5360   int cc_last;
5361   reg_set_iterator rsi;
5362
5363   /* Make sure we are only dealing with hard registers.  Also honor the
5364      -mno-cond-exec switch, and -mno-nested-cond-exec switches if
5365      applicable.  */
5366   if (!reload_completed || !TARGET_COND_EXEC
5367       || (!TARGET_NESTED_CE && ce_info->pass > 1))
5368     goto fail;
5369
5370   /* Figure out which registers we can allocate for our own purposes.  Only
5371      consider registers that are not preserved across function calls and are
5372      not fixed.  However, allow the ICC/ICR temporary registers to be allocated
5373      if we did not need to use them in reloading other registers.  */
5374   memset (&tmp_reg->regs, 0, sizeof (tmp_reg->regs));
5375   COPY_HARD_REG_SET (tmp_reg->regs, call_used_reg_set);
5376   AND_COMPL_HARD_REG_SET (tmp_reg->regs, fixed_reg_set);
5377   SET_HARD_REG_BIT (tmp_reg->regs, ICC_TEMP);
5378   SET_HARD_REG_BIT (tmp_reg->regs, ICR_TEMP);
5379
5380   /* If this is a nested IF, we need to discover whether the CC registers that
5381      are set/used inside of the block are used anywhere else.  If not, we can
5382      change them to be the CC register that is paired with the CR register that
5383      controls the outermost IF block.  */
5384   if (ce_info->pass > 1)
5385     {
5386       CLEAR_HARD_REG_SET (frv_ifcvt.nested_cc_ok_rewrite);
5387       for (j = CC_FIRST; j <= CC_LAST; j++)
5388         if (TEST_HARD_REG_BIT (tmp_reg->regs, j))
5389           {
5390             if (REGNO_REG_SET_P (df_get_live_in (then_bb), j))
5391               continue;
5392
5393             if (else_bb
5394                 && REGNO_REG_SET_P (df_get_live_in (else_bb), j))
5395               continue;
5396
5397             if (join_bb
5398                 && REGNO_REG_SET_P (df_get_live_in (join_bb), j))
5399               continue;
5400
5401             SET_HARD_REG_BIT (frv_ifcvt.nested_cc_ok_rewrite, j);
5402           }
5403     }
5404
5405   for (j = 0; j < frv_ifcvt.cur_scratch_regs; j++)
5406     frv_ifcvt.scratch_regs[j] = NULL_RTX;
5407
5408   frv_ifcvt.added_insns_list = NULL_RTX;
5409   frv_ifcvt.cur_scratch_regs = 0;
5410
5411   bb = (basic_block *) alloca ((2 + ce_info->num_multiple_test_blocks)
5412                                * sizeof (basic_block));
5413
5414   if (join_bb)
5415     {
5416       unsigned int regno;
5417
5418       /* Remove anything live at the beginning of the join block from being
5419          available for allocation.  */
5420       EXECUTE_IF_SET_IN_REG_SET (df_get_live_in (join_bb), 0, regno, rsi)
5421         {
5422           if (regno < FIRST_PSEUDO_REGISTER)
5423             CLEAR_HARD_REG_BIT (tmp_reg->regs, regno);
5424         }
5425     }
5426
5427   /* Add in all of the blocks in multiple &&/|| blocks to be scanned.  */
5428   num_bb = 0;
5429   if (ce_info->num_multiple_test_blocks)
5430     {
5431       basic_block multiple_test_bb = ce_info->last_test_bb;
5432
5433       while (multiple_test_bb != test_bb)
5434         {
5435           bb[num_bb++] = multiple_test_bb;
5436           multiple_test_bb = EDGE_PRED (multiple_test_bb, 0)->src;
5437         }
5438     }
5439
5440   /* Add in the THEN and ELSE blocks to be scanned.  */
5441   bb[num_bb++] = then_bb;
5442   if (else_bb)
5443     bb[num_bb++] = else_bb;
5444
5445   sub_cond_exec_reg = NULL_RTX;
5446   frv_ifcvt.num_nested_cond_exec = 0;
5447
5448   /* Scan all of the blocks for registers that must not be allocated.  */
5449   for (j = 0; j < num_bb; j++)
5450     {
5451       rtx last_insn = BB_END (bb[j]);
5452       rtx insn = BB_HEAD (bb[j]);
5453       unsigned int regno;
5454
5455       if (dump_file)
5456         fprintf (dump_file, "Scanning %s block %d, start %d, end %d\n",
5457                  (bb[j] == else_bb) ? "else" : ((bb[j] == then_bb) ? "then" : "test"),
5458                  (int) bb[j]->index,
5459                  (int) INSN_UID (BB_HEAD (bb[j])),
5460                  (int) INSN_UID (BB_END (bb[j])));
5461
5462       /* Anything live at the beginning of the block is obviously unavailable
5463          for allocation.  */
5464       EXECUTE_IF_SET_IN_REG_SET (df_get_live_in (bb[j]), 0, regno, rsi)
5465         {
5466           if (regno < FIRST_PSEUDO_REGISTER)
5467             CLEAR_HARD_REG_BIT (tmp_reg->regs, regno);
5468         }
5469
5470       /* Loop through the insns in the block.  */
5471       for (;;)
5472         {
5473           /* Mark any new registers that are created as being unavailable for
5474              allocation.  Also see if the CC register used in nested IFs can be
5475              reallocated.  */
5476           if (INSN_P (insn))
5477             {
5478               rtx pattern;
5479               rtx set;
5480               int skip_nested_if = FALSE;
5481
5482               for_each_rtx (&PATTERN (insn), frv_clear_registers_used,
5483                             (void *)&tmp_reg->regs);
5484
5485               pattern = PATTERN (insn);
5486               if (GET_CODE (pattern) == COND_EXEC)
5487                 {
5488                   rtx reg = XEXP (COND_EXEC_TEST (pattern), 0);
5489
5490                   if (reg != sub_cond_exec_reg)
5491                     {
5492                       sub_cond_exec_reg = reg;
5493                       frv_ifcvt.num_nested_cond_exec++;
5494                     }
5495                 }
5496
5497               set = single_set_pattern (pattern);
5498               if (set)
5499                 {
5500                   rtx dest = SET_DEST (set);
5501                   rtx src = SET_SRC (set);
5502
5503                   if (GET_CODE (dest) == REG)
5504                     {
5505                       int regno = REGNO (dest);
5506                       enum rtx_code src_code = GET_CODE (src);
5507
5508                       if (CC_P (regno) && src_code == COMPARE)
5509                         skip_nested_if = TRUE;
5510
5511                       else if (CR_P (regno)
5512                                && (src_code == IF_THEN_ELSE
5513                                    || COMPARISON_P (src)))
5514                         skip_nested_if = TRUE;
5515                     }
5516                 }
5517
5518               if (! skip_nested_if)
5519                 for_each_rtx (&PATTERN (insn), frv_clear_registers_used,
5520                               (void *)&frv_ifcvt.nested_cc_ok_rewrite);
5521             }
5522
5523           if (insn == last_insn)
5524             break;
5525
5526           insn = NEXT_INSN (insn);
5527         }
5528     }
5529
5530   /* If this is a nested if, rewrite the CC registers that are available to
5531      include the ones that can be rewritten, to increase the chance of being
5532      able to allocate a paired CC/CR register combination.  */
5533   if (ce_info->pass > 1)
5534     {
5535       for (j = CC_FIRST; j <= CC_LAST; j++)
5536         if (TEST_HARD_REG_BIT (frv_ifcvt.nested_cc_ok_rewrite, j))
5537           SET_HARD_REG_BIT (tmp_reg->regs, j);
5538         else
5539           CLEAR_HARD_REG_BIT (tmp_reg->regs, j);
5540     }
5541
5542   if (dump_file)
5543     {
5544       int num_gprs = 0;
5545       fprintf (dump_file, "Available GPRs: ");
5546
5547       for (j = GPR_FIRST; j <= GPR_LAST; j++)
5548         if (TEST_HARD_REG_BIT (tmp_reg->regs, j))
5549           {
5550             fprintf (dump_file, " %d [%s]", j, reg_names[j]);
5551             if (++num_gprs > GPR_TEMP_NUM+2)
5552               break;
5553           }
5554
5555       fprintf (dump_file, "%s\nAvailable CRs:  ",
5556                (num_gprs > GPR_TEMP_NUM+2) ? " ..." : "");
5557
5558       for (j = CR_FIRST; j <= CR_LAST; j++)
5559         if (TEST_HARD_REG_BIT (tmp_reg->regs, j))
5560           fprintf (dump_file, " %d [%s]", j, reg_names[j]);
5561
5562       fputs ("\n", dump_file);
5563
5564       if (ce_info->pass > 1)
5565         {
5566           fprintf (dump_file, "Modifiable CCs: ");
5567           for (j = CC_FIRST; j <= CC_LAST; j++)
5568             if (TEST_HARD_REG_BIT (tmp_reg->regs, j))
5569               fprintf (dump_file, " %d [%s]", j, reg_names[j]);
5570
5571           fprintf (dump_file, "\n%d nested COND_EXEC statements\n",
5572                    frv_ifcvt.num_nested_cond_exec);
5573         }
5574     }
5575
5576   /* Allocate the appropriate temporary condition code register.  Try to
5577      allocate the ICR/FCR register that corresponds to the ICC/FCC register so
5578      that conditional cmp's can be done.  */
5579   if (mode == CCmode || mode == CC_UNSmode || mode == CC_NZmode)
5580     {
5581       cr_class = ICR_REGS;
5582       cc_class = ICC_REGS;
5583       cc_first = ICC_FIRST;
5584       cc_last = ICC_LAST;
5585     }
5586   else if (mode == CC_FPmode)
5587     {
5588       cr_class = FCR_REGS;
5589       cc_class = FCC_REGS;
5590       cc_first = FCC_FIRST;
5591       cc_last = FCC_LAST;
5592     }
5593   else
5594     {
5595       cc_first = cc_last = 0;
5596       cr_class = cc_class = NO_REGS;
5597     }
5598
5599   cc = XEXP (true_expr, 0);
5600   nested_cc = cr = NULL_RTX;
5601   if (cc_class != NO_REGS)
5602     {
5603       /* For nested IFs and &&/||, see if we can find a CC and CR register pair
5604          so we can execute a csubcc/caddcc/cfcmps instruction.  */
5605       int cc_regno;
5606
5607       for (cc_regno = cc_first; cc_regno <= cc_last; cc_regno++)
5608         {
5609           int cr_regno = cc_regno - CC_FIRST + CR_FIRST;
5610
5611           if (TEST_HARD_REG_BIT (frv_ifcvt.tmp_reg.regs, cc_regno)
5612               && TEST_HARD_REG_BIT (frv_ifcvt.tmp_reg.regs, cr_regno))
5613             {
5614               frv_ifcvt.tmp_reg.next_reg[ (int)cr_class ] = cr_regno;
5615               cr = frv_alloc_temp_reg (tmp_reg, cr_class, CC_CCRmode, TRUE,
5616                                        TRUE);
5617
5618               frv_ifcvt.tmp_reg.next_reg[ (int)cc_class ] = cc_regno;
5619               nested_cc = frv_alloc_temp_reg (tmp_reg, cc_class, CCmode,
5620                                                   TRUE, TRUE);
5621               break;
5622             }
5623         }
5624     }
5625
5626   if (! cr)
5627     {
5628       if (dump_file)
5629         fprintf (dump_file, "Could not allocate a CR temporary register\n");
5630
5631       goto fail;
5632     }
5633
5634   if (dump_file)
5635     fprintf (dump_file,
5636              "Will use %s for conditional execution, %s for nested comparisons\n",
5637              reg_names[ REGNO (cr)],
5638              (nested_cc) ? reg_names[ REGNO (nested_cc) ] : "<none>");
5639
5640   /* Set the CCR bit.  Note for integer tests, we reverse the condition so that
5641      in an IF-THEN-ELSE sequence, we are testing the TRUE case against the CCR
5642      bit being true.  We don't do this for floating point, because of NaNs.  */
5643   code = GET_CODE (true_expr);
5644   if (GET_MODE (cc) != CC_FPmode)
5645     {
5646       code = reverse_condition (code);
5647       code_true = EQ;
5648       code_false = NE;
5649     }
5650   else
5651     {
5652       code_true = NE;
5653       code_false = EQ;
5654     }
5655
5656   check_insn = gen_rtx_SET (VOIDmode, cr,
5657                             gen_rtx_fmt_ee (code, CC_CCRmode, cc, const0_rtx));
5658
5659   /* Record the check insn to be inserted later.  */
5660   frv_ifcvt_add_insn (check_insn, BB_END (test_bb), TRUE);
5661
5662   /* Update the tests.  */
5663   frv_ifcvt.cr_reg = cr;
5664   frv_ifcvt.nested_cc_reg = nested_cc;
5665   *p_true = gen_rtx_fmt_ee (code_true, CC_CCRmode, cr, const0_rtx);
5666   *p_false = gen_rtx_fmt_ee (code_false, CC_CCRmode, cr, const0_rtx);
5667   return;
5668
5669   /* Fail, don't do this conditional execution.  */
5670  fail:
5671   *p_true = NULL_RTX;
5672   *p_false = NULL_RTX;
5673   if (dump_file)
5674     fprintf (dump_file, "Disabling this conditional execution.\n");
5675
5676   return;
5677 }
5678
5679 \f
5680 /* A C expression to modify the code described by the conditional if
5681    information CE_INFO, for the basic block BB, possibly updating the tests in
5682    TRUE_EXPR, and FALSE_EXPR for converting the && and || parts of if-then or
5683    if-then-else code to conditional instructions.  Set either TRUE_EXPR or
5684    FALSE_EXPR to a null pointer if the tests cannot be converted.  */
5685
5686 /* p_true and p_false are given expressions of the form:
5687
5688         (and (eq:CC_CCR (reg:CC_CCR)
5689                         (const_int 0))
5690              (eq:CC (reg:CC)
5691                     (const_int 0))) */
5692
5693 void
5694 frv_ifcvt_modify_multiple_tests (ce_if_block_t *ce_info,
5695                                  basic_block bb,
5696                                  rtx *p_true,
5697                                  rtx *p_false)
5698 {
5699   rtx old_true = XEXP (*p_true, 0);
5700   rtx old_false = XEXP (*p_false, 0);
5701   rtx true_expr = XEXP (*p_true, 1);
5702   rtx false_expr = XEXP (*p_false, 1);
5703   rtx test_expr;
5704   rtx old_test;
5705   rtx cr = XEXP (old_true, 0);
5706   rtx check_insn;
5707   rtx new_cr = NULL_RTX;
5708   rtx *p_new_cr = (rtx *)0;
5709   rtx if_else;
5710   rtx compare;
5711   rtx cc;
5712   enum reg_class cr_class;
5713   enum machine_mode mode = GET_MODE (true_expr);
5714   rtx (*logical_func)(rtx, rtx, rtx);
5715
5716   if (TARGET_DEBUG_COND_EXEC)
5717     {
5718       fprintf (stderr,
5719                "\n:::::::::: frv_ifcvt_modify_multiple_tests, before modification for %s\ntrue insn:\n",
5720                ce_info->and_and_p ? "&&" : "||");
5721
5722       debug_rtx (*p_true);
5723
5724       fputs ("\nfalse insn:\n", stderr);
5725       debug_rtx (*p_false);
5726     }
5727
5728   if (!TARGET_MULTI_CE)
5729     goto fail;
5730
5731   if (GET_CODE (cr) != REG)
5732     goto fail;
5733
5734   if (mode == CCmode || mode == CC_UNSmode || mode == CC_NZmode)
5735     {
5736       cr_class = ICR_REGS;
5737       p_new_cr = &frv_ifcvt.extra_int_cr;
5738     }
5739   else if (mode == CC_FPmode)
5740     {
5741       cr_class = FCR_REGS;
5742       p_new_cr = &frv_ifcvt.extra_fp_cr;
5743     }
5744   else
5745     goto fail;
5746
5747   /* Allocate a temp CR, reusing a previously allocated temp CR if we have 3 or
5748      more &&/|| tests.  */
5749   new_cr = *p_new_cr;
5750   if (! new_cr)
5751     {
5752       new_cr = *p_new_cr = frv_alloc_temp_reg (&frv_ifcvt.tmp_reg, cr_class,
5753                                                CC_CCRmode, TRUE, TRUE);
5754       if (! new_cr)
5755         goto fail;
5756     }
5757
5758   if (ce_info->and_and_p)
5759     {
5760       old_test = old_false;
5761       test_expr = true_expr;
5762       logical_func = (GET_CODE (old_true) == EQ) ? gen_andcr : gen_andncr;
5763       *p_true = gen_rtx_NE (CC_CCRmode, cr, const0_rtx);
5764       *p_false = gen_rtx_EQ (CC_CCRmode, cr, const0_rtx);
5765     }
5766   else
5767     {
5768       old_test = old_false;
5769       test_expr = false_expr;
5770       logical_func = (GET_CODE (old_false) == EQ) ? gen_orcr : gen_orncr;
5771       *p_true = gen_rtx_EQ (CC_CCRmode, cr, const0_rtx);
5772       *p_false = gen_rtx_NE (CC_CCRmode, cr, const0_rtx);
5773     }
5774
5775   /* First add the andcr/andncr/orcr/orncr, which will be added after the
5776      conditional check instruction, due to frv_ifcvt_add_insn being a LIFO
5777      stack.  */
5778   frv_ifcvt_add_insn ((*logical_func) (cr, cr, new_cr), BB_END (bb), TRUE);
5779
5780   /* Now add the conditional check insn.  */
5781   cc = XEXP (test_expr, 0);
5782   compare = gen_rtx_fmt_ee (GET_CODE (test_expr), CC_CCRmode, cc, const0_rtx);
5783   if_else = gen_rtx_IF_THEN_ELSE (CC_CCRmode, old_test, compare, const0_rtx);
5784
5785   check_insn = gen_rtx_SET (VOIDmode, new_cr, if_else);
5786
5787   /* Add the new check insn to the list of check insns that need to be
5788      inserted.  */
5789   frv_ifcvt_add_insn (check_insn, BB_END (bb), TRUE);
5790
5791   if (TARGET_DEBUG_COND_EXEC)
5792     {
5793       fputs ("\n:::::::::: frv_ifcvt_modify_multiple_tests, after modification\ntrue insn:\n",
5794              stderr);
5795
5796       debug_rtx (*p_true);
5797
5798       fputs ("\nfalse insn:\n", stderr);
5799       debug_rtx (*p_false);
5800     }
5801
5802   return;
5803
5804  fail:
5805   *p_true = *p_false = NULL_RTX;
5806
5807   /* If we allocated a CR register, release it.  */
5808   if (new_cr)
5809     {
5810       CLEAR_HARD_REG_BIT (frv_ifcvt.tmp_reg.regs, REGNO (new_cr));
5811       *p_new_cr = NULL_RTX;
5812     }
5813
5814   if (TARGET_DEBUG_COND_EXEC)
5815     fputs ("\n:::::::::: frv_ifcvt_modify_multiple_tests, failed.\n", stderr);
5816
5817   return;
5818 }
5819
5820 \f
5821 /* Return a register which will be loaded with a value if an IF block is
5822    converted to conditional execution.  This is used to rewrite instructions
5823    that use constants to ones that just use registers.  */
5824
5825 static rtx
5826 frv_ifcvt_load_value (rtx value, rtx insn ATTRIBUTE_UNUSED)
5827 {
5828   int num_alloc = frv_ifcvt.cur_scratch_regs;
5829   int i;
5830   rtx reg;
5831
5832   /* We know gr0 == 0, so replace any errant uses.  */
5833   if (value == const0_rtx)
5834     return gen_rtx_REG (SImode, GPR_FIRST);
5835
5836   /* First search all registers currently loaded to see if we have an
5837      applicable constant.  */
5838   if (CONSTANT_P (value)
5839       || (GET_CODE (value) == REG && REGNO (value) == LR_REGNO))
5840     {
5841       for (i = 0; i < num_alloc; i++)
5842         {
5843           if (rtx_equal_p (SET_SRC (frv_ifcvt.scratch_regs[i]), value))
5844             return SET_DEST (frv_ifcvt.scratch_regs[i]);
5845         }
5846     }
5847
5848   /* Have we exhausted the number of registers available?  */
5849   if (num_alloc >= GPR_TEMP_NUM)
5850     {
5851       if (dump_file)
5852         fprintf (dump_file, "Too many temporary registers allocated\n");
5853
5854       return NULL_RTX;
5855     }
5856
5857   /* Allocate the new register.  */
5858   reg = frv_alloc_temp_reg (&frv_ifcvt.tmp_reg, GPR_REGS, SImode, TRUE, TRUE);
5859   if (! reg)
5860     {
5861       if (dump_file)
5862         fputs ("Could not find a scratch register\n", dump_file);
5863
5864       return NULL_RTX;
5865     }
5866
5867   frv_ifcvt.cur_scratch_regs++;
5868   frv_ifcvt.scratch_regs[num_alloc] = gen_rtx_SET (VOIDmode, reg, value);
5869
5870   if (dump_file)
5871     {
5872       if (GET_CODE (value) == CONST_INT)
5873         fprintf (dump_file, "Register %s will hold %ld\n",
5874                  reg_names[ REGNO (reg)], (long)INTVAL (value));
5875
5876       else if (GET_CODE (value) == REG && REGNO (value) == LR_REGNO)
5877         fprintf (dump_file, "Register %s will hold LR\n",
5878                  reg_names[ REGNO (reg)]);
5879
5880       else
5881         fprintf (dump_file, "Register %s will hold a saved value\n",
5882                  reg_names[ REGNO (reg)]);
5883     }
5884
5885   return reg;
5886 }
5887
5888 \f
5889 /* Update a MEM used in conditional code that might contain an offset to put
5890    the offset into a scratch register, so that the conditional load/store
5891    operations can be used.  This function returns the original pointer if the
5892    MEM is valid to use in conditional code, NULL if we can't load up the offset
5893    into a temporary register, or the new MEM if we were successful.  */
5894
5895 static rtx
5896 frv_ifcvt_rewrite_mem (rtx mem, enum machine_mode mode, rtx insn)
5897 {
5898   rtx addr = XEXP (mem, 0);
5899
5900   if (!frv_legitimate_address_p_1 (mode, addr, reload_completed, TRUE, FALSE))
5901     {
5902       if (GET_CODE (addr) == PLUS)
5903         {
5904           rtx addr_op0 = XEXP (addr, 0);
5905           rtx addr_op1 = XEXP (addr, 1);
5906
5907           if (GET_CODE (addr_op0) == REG && CONSTANT_P (addr_op1))
5908             {
5909               rtx reg = frv_ifcvt_load_value (addr_op1, insn);
5910               if (!reg)
5911                 return NULL_RTX;
5912
5913               addr = gen_rtx_PLUS (Pmode, addr_op0, reg);
5914             }
5915
5916           else
5917             return NULL_RTX;
5918         }
5919
5920       else if (CONSTANT_P (addr))
5921         addr = frv_ifcvt_load_value (addr, insn);
5922
5923       else
5924         return NULL_RTX;
5925
5926       if (addr == NULL_RTX)
5927         return NULL_RTX;
5928
5929       else if (XEXP (mem, 0) != addr)
5930         return change_address (mem, mode, addr);
5931     }
5932
5933   return mem;
5934 }
5935
5936 \f
5937 /* Given a PATTERN, return a SET expression if this PATTERN has only a single
5938    SET, possibly conditionally executed.  It may also have CLOBBERs, USEs.  */
5939
5940 static rtx
5941 single_set_pattern (rtx pattern)
5942 {
5943   rtx set;
5944   int i;
5945
5946   if (GET_CODE (pattern) == COND_EXEC)
5947     pattern = COND_EXEC_CODE (pattern);
5948
5949   if (GET_CODE (pattern) == SET)
5950     return pattern;
5951
5952   else if (GET_CODE (pattern) == PARALLEL)
5953     {
5954       for (i = 0, set = 0; i < XVECLEN (pattern, 0); i++)
5955         {
5956           rtx sub = XVECEXP (pattern, 0, i);
5957
5958           switch (GET_CODE (sub))
5959             {
5960             case USE:
5961             case CLOBBER:
5962               break;
5963
5964             case SET:
5965               if (set)
5966                 return 0;
5967               else
5968                 set = sub;
5969               break;
5970
5971             default:
5972               return 0;
5973             }
5974         }
5975       return set;
5976     }
5977
5978   return 0;
5979 }
5980
5981 \f
5982 /* A C expression to modify the code described by the conditional if
5983    information CE_INFO with the new PATTERN in INSN.  If PATTERN is a null
5984    pointer after the IFCVT_MODIFY_INSN macro executes, it is assumed that that
5985    insn cannot be converted to be executed conditionally.  */
5986
5987 rtx
5988 frv_ifcvt_modify_insn (ce_if_block_t *ce_info,
5989                        rtx pattern,
5990                        rtx insn)
5991 {
5992   rtx orig_ce_pattern = pattern;
5993   rtx set;
5994   rtx op0;
5995   rtx op1;
5996   rtx test;
5997
5998   gcc_assert (GET_CODE (pattern) == COND_EXEC);
5999
6000   test = COND_EXEC_TEST (pattern);
6001   if (GET_CODE (test) == AND)
6002     {
6003       rtx cr = frv_ifcvt.cr_reg;
6004       rtx test_reg;
6005
6006       op0 = XEXP (test, 0);
6007       if (! rtx_equal_p (cr, XEXP (op0, 0)))
6008         goto fail;
6009
6010       op1 = XEXP (test, 1);
6011       test_reg = XEXP (op1, 0);
6012       if (GET_CODE (test_reg) != REG)
6013         goto fail;
6014
6015       /* Is this the first nested if block in this sequence?  If so, generate
6016          an andcr or andncr.  */
6017       if (! frv_ifcvt.last_nested_if_cr)
6018         {
6019           rtx and_op;
6020
6021           frv_ifcvt.last_nested_if_cr = test_reg;
6022           if (GET_CODE (op0) == NE)
6023             and_op = gen_andcr (test_reg, cr, test_reg);
6024           else
6025             and_op = gen_andncr (test_reg, cr, test_reg);
6026
6027           frv_ifcvt_add_insn (and_op, insn, TRUE);
6028         }
6029
6030       /* If this isn't the first statement in the nested if sequence, see if we
6031          are dealing with the same register.  */
6032       else if (! rtx_equal_p (test_reg, frv_ifcvt.last_nested_if_cr))
6033         goto fail;
6034
6035       COND_EXEC_TEST (pattern) = test = op1;
6036     }
6037
6038   /* If this isn't a nested if, reset state variables.  */
6039   else
6040     {
6041       frv_ifcvt.last_nested_if_cr = NULL_RTX;
6042     }
6043
6044   set = single_set_pattern (pattern);
6045   if (set)
6046     {
6047       rtx dest = SET_DEST (set);
6048       rtx src = SET_SRC (set);
6049       enum machine_mode mode = GET_MODE (dest);
6050
6051       /* Check for normal binary operators.  */
6052       if (mode == SImode && ARITHMETIC_P (src))
6053         {
6054           op0 = XEXP (src, 0);
6055           op1 = XEXP (src, 1);
6056
6057           if (integer_register_operand (op0, SImode) && CONSTANT_P (op1))
6058             {
6059               op1 = frv_ifcvt_load_value (op1, insn);
6060               if (op1)
6061                 COND_EXEC_CODE (pattern)
6062                   = gen_rtx_SET (VOIDmode, dest, gen_rtx_fmt_ee (GET_CODE (src),
6063                                                                  GET_MODE (src),
6064                                                                  op0, op1));
6065               else
6066                 goto fail;
6067             }
6068         }
6069
6070       /* For multiply by a constant, we need to handle the sign extending
6071          correctly.  Add a USE of the value after the multiply to prevent flow
6072          from cratering because only one register out of the two were used.  */
6073       else if (mode == DImode && GET_CODE (src) == MULT)
6074         {
6075           op0 = XEXP (src, 0);
6076           op1 = XEXP (src, 1);
6077           if (GET_CODE (op0) == SIGN_EXTEND && GET_CODE (op1) == CONST_INT)
6078             {
6079               op1 = frv_ifcvt_load_value (op1, insn);
6080               if (op1)
6081                 {
6082                   op1 = gen_rtx_SIGN_EXTEND (DImode, op1);
6083                   COND_EXEC_CODE (pattern)
6084                     = gen_rtx_SET (VOIDmode, dest,
6085                                    gen_rtx_MULT (DImode, op0, op1));
6086                 }
6087               else
6088                 goto fail;
6089             }
6090
6091           frv_ifcvt_add_insn (gen_use (dest), insn, FALSE);
6092         }
6093
6094       /* If we are just loading a constant created for a nested conditional
6095          execution statement, just load the constant without any conditional
6096          execution, since we know that the constant will not interfere with any
6097          other registers.  */
6098       else if (frv_ifcvt.scratch_insns_bitmap
6099                && bitmap_bit_p (frv_ifcvt.scratch_insns_bitmap,
6100                                 INSN_UID (insn))
6101                && REG_P (SET_DEST (set))
6102                /* We must not unconditionally set a scratch reg chosen
6103                   for a nested if-converted block if its incoming
6104                   value from the TEST block (or the result of the THEN
6105                   branch) could/should propagate to the JOIN block.
6106                   It suffices to test whether the register is live at
6107                   the JOIN point: if it's live there, we can infer
6108                   that we set it in the former JOIN block of the
6109                   nested if-converted block (otherwise it wouldn't
6110                   have been available as a scratch register), and it
6111                   is either propagated through or set in the other
6112                   conditional block.  It's probably not worth trying
6113                   to catch the latter case, and it could actually
6114                   limit scheduling of the combined block quite
6115                   severely.  */
6116                && ce_info->join_bb
6117                && ! (REGNO_REG_SET_P (df_get_live_in (ce_info->join_bb),
6118                                       REGNO (SET_DEST (set))))
6119                /* Similarly, we must not unconditionally set a reg
6120                   used as scratch in the THEN branch if the same reg
6121                   is live in the ELSE branch.  */
6122                && (! ce_info->else_bb
6123                    || BLOCK_FOR_INSN (insn) == ce_info->else_bb
6124                    || ! (REGNO_REG_SET_P (df_get_live_in (ce_info->else_bb),
6125                                           REGNO (SET_DEST (set))))))
6126         pattern = set;
6127
6128       else if (mode == QImode || mode == HImode || mode == SImode
6129                || mode == SFmode)
6130         {
6131           int changed_p = FALSE;
6132
6133           /* Check for just loading up a constant */
6134           if (CONSTANT_P (src) && integer_register_operand (dest, mode))
6135             {
6136               src = frv_ifcvt_load_value (src, insn);
6137               if (!src)
6138                 goto fail;
6139
6140               changed_p = TRUE;
6141             }
6142
6143           /* See if we need to fix up stores */
6144           if (GET_CODE (dest) == MEM)
6145             {
6146               rtx new_mem = frv_ifcvt_rewrite_mem (dest, mode, insn);
6147
6148               if (!new_mem)
6149                 goto fail;
6150
6151               else if (new_mem != dest)
6152                 {
6153                   changed_p = TRUE;
6154                   dest = new_mem;
6155                 }
6156             }
6157
6158           /* See if we need to fix up loads */
6159           if (GET_CODE (src) == MEM)
6160             {
6161               rtx new_mem = frv_ifcvt_rewrite_mem (src, mode, insn);
6162
6163               if (!new_mem)
6164                 goto fail;
6165
6166               else if (new_mem != src)
6167                 {
6168                   changed_p = TRUE;
6169                   src = new_mem;
6170                 }
6171             }
6172
6173           /* If either src or destination changed, redo SET.  */
6174           if (changed_p)
6175             COND_EXEC_CODE (pattern) = gen_rtx_SET (VOIDmode, dest, src);
6176         }
6177
6178       /* Rewrite a nested set cccr in terms of IF_THEN_ELSE.  Also deal with
6179          rewriting the CC register to be the same as the paired CC/CR register
6180          for nested ifs.  */
6181       else if (mode == CC_CCRmode && COMPARISON_P (src))
6182         {
6183           int regno = REGNO (XEXP (src, 0));
6184           rtx if_else;
6185
6186           if (ce_info->pass > 1
6187               && regno != (int)REGNO (frv_ifcvt.nested_cc_reg)
6188               && TEST_HARD_REG_BIT (frv_ifcvt.nested_cc_ok_rewrite, regno))
6189             {
6190               src = gen_rtx_fmt_ee (GET_CODE (src),
6191                                     CC_CCRmode,
6192                                     frv_ifcvt.nested_cc_reg,
6193                                     XEXP (src, 1));
6194             }
6195
6196           if_else = gen_rtx_IF_THEN_ELSE (CC_CCRmode, test, src, const0_rtx);
6197           pattern = gen_rtx_SET (VOIDmode, dest, if_else);
6198         }
6199
6200       /* Remap a nested compare instruction to use the paired CC/CR reg.  */
6201       else if (ce_info->pass > 1
6202                && GET_CODE (dest) == REG
6203                && CC_P (REGNO (dest))
6204                && REGNO (dest) != REGNO (frv_ifcvt.nested_cc_reg)
6205                && TEST_HARD_REG_BIT (frv_ifcvt.nested_cc_ok_rewrite,
6206                                      REGNO (dest))
6207                && GET_CODE (src) == COMPARE)
6208         {
6209           PUT_MODE (frv_ifcvt.nested_cc_reg, GET_MODE (dest));
6210           COND_EXEC_CODE (pattern)
6211             = gen_rtx_SET (VOIDmode, frv_ifcvt.nested_cc_reg, copy_rtx (src));
6212         }
6213     }
6214
6215   if (TARGET_DEBUG_COND_EXEC)
6216     {
6217       rtx orig_pattern = PATTERN (insn);
6218
6219       PATTERN (insn) = pattern;
6220       fprintf (stderr,
6221                "\n:::::::::: frv_ifcvt_modify_insn: pass = %d, insn after modification:\n",
6222                ce_info->pass);
6223
6224       debug_rtx (insn);
6225       PATTERN (insn) = orig_pattern;
6226     }
6227
6228   return pattern;
6229
6230  fail:
6231   if (TARGET_DEBUG_COND_EXEC)
6232     {
6233       rtx orig_pattern = PATTERN (insn);
6234
6235       PATTERN (insn) = orig_ce_pattern;
6236       fprintf (stderr,
6237                "\n:::::::::: frv_ifcvt_modify_insn: pass = %d, insn could not be modified:\n",
6238                ce_info->pass);
6239
6240       debug_rtx (insn);
6241       PATTERN (insn) = orig_pattern;
6242     }
6243
6244   return NULL_RTX;
6245 }
6246
6247 \f
6248 /* A C expression to perform any final machine dependent modifications in
6249    converting code to conditional execution in the code described by the
6250    conditional if information CE_INFO.  */
6251
6252 void
6253 frv_ifcvt_modify_final (ce_if_block_t *ce_info ATTRIBUTE_UNUSED)
6254 {
6255   rtx existing_insn;
6256   rtx check_insn;
6257   rtx p = frv_ifcvt.added_insns_list;
6258   int i;
6259
6260   /* Loop inserting the check insns.  The last check insn is the first test,
6261      and is the appropriate place to insert constants.  */
6262   gcc_assert (p);
6263
6264   do
6265     {
6266       rtx check_and_insert_insns = XEXP (p, 0);
6267       rtx old_p = p;
6268
6269       check_insn = XEXP (check_and_insert_insns, 0);
6270       existing_insn = XEXP (check_and_insert_insns, 1);
6271       p = XEXP (p, 1);
6272
6273       /* The jump bit is used to say that the new insn is to be inserted BEFORE
6274          the existing insn, otherwise it is to be inserted AFTER.  */
6275       if (check_and_insert_insns->jump)
6276         {
6277           emit_insn_before (check_insn, existing_insn);
6278           check_and_insert_insns->jump = 0;
6279         }
6280       else
6281         emit_insn_after (check_insn, existing_insn);
6282
6283       free_EXPR_LIST_node (check_and_insert_insns);
6284       free_EXPR_LIST_node (old_p);
6285     }
6286   while (p != NULL_RTX);
6287
6288   /* Load up any constants needed into temp gprs */
6289   for (i = 0; i < frv_ifcvt.cur_scratch_regs; i++)
6290     {
6291       rtx insn = emit_insn_before (frv_ifcvt.scratch_regs[i], existing_insn);
6292       if (! frv_ifcvt.scratch_insns_bitmap)
6293         frv_ifcvt.scratch_insns_bitmap = BITMAP_ALLOC (NULL);
6294       bitmap_set_bit (frv_ifcvt.scratch_insns_bitmap, INSN_UID (insn));
6295       frv_ifcvt.scratch_regs[i] = NULL_RTX;
6296     }
6297
6298   frv_ifcvt.added_insns_list = NULL_RTX;
6299   frv_ifcvt.cur_scratch_regs = 0;
6300 }
6301
6302 \f
6303 /* A C expression to cancel any machine dependent modifications in converting
6304    code to conditional execution in the code described by the conditional if
6305    information CE_INFO.  */
6306
6307 void
6308 frv_ifcvt_modify_cancel (ce_if_block_t *ce_info ATTRIBUTE_UNUSED)
6309 {
6310   int i;
6311   rtx p = frv_ifcvt.added_insns_list;
6312
6313   /* Loop freeing up the EXPR_LIST's allocated.  */
6314   while (p != NULL_RTX)
6315     {
6316       rtx check_and_jump = XEXP (p, 0);
6317       rtx old_p = p;
6318
6319       p = XEXP (p, 1);
6320       free_EXPR_LIST_node (check_and_jump);
6321       free_EXPR_LIST_node (old_p);
6322     }
6323
6324   /* Release any temporary gprs allocated.  */
6325   for (i = 0; i < frv_ifcvt.cur_scratch_regs; i++)
6326     frv_ifcvt.scratch_regs[i] = NULL_RTX;
6327
6328   frv_ifcvt.added_insns_list = NULL_RTX;
6329   frv_ifcvt.cur_scratch_regs = 0;
6330   return;
6331 }
6332 \f
6333 /* A C expression for the size in bytes of the trampoline, as an integer.
6334    The template is:
6335
6336         setlo #0, <jmp_reg>
6337         setlo #0, <static_chain>
6338         sethi #0, <jmp_reg>
6339         sethi #0, <static_chain>
6340         jmpl @(gr0,<jmp_reg>) */
6341
6342 int
6343 frv_trampoline_size (void)
6344 {
6345   if (TARGET_FDPIC)
6346     /* Allocate room for the function descriptor and the lddi
6347        instruction.  */
6348     return 8 + 6 * 4;
6349   return 5 /* instructions */ * 4 /* instruction size.  */;
6350 }
6351
6352 \f
6353 /* A C statement to initialize the variable parts of a trampoline.  ADDR is an
6354    RTX for the address of the trampoline; FNADDR is an RTX for the address of
6355    the nested function; STATIC_CHAIN is an RTX for the static chain value that
6356    should be passed to the function when it is called.
6357
6358    The template is:
6359
6360         setlo #0, <jmp_reg>
6361         setlo #0, <static_chain>
6362         sethi #0, <jmp_reg>
6363         sethi #0, <static_chain>
6364         jmpl @(gr0,<jmp_reg>) */
6365
6366 static void
6367 frv_trampoline_init (rtx m_tramp, tree fndecl, rtx static_chain)
6368 {
6369   rtx addr = XEXP (m_tramp, 0);
6370   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
6371   rtx sc_reg = force_reg (Pmode, static_chain);
6372
6373   emit_library_call (gen_rtx_SYMBOL_REF (SImode, "__trampoline_setup"),
6374                      LCT_NORMAL, VOIDmode, 4,
6375                      addr, Pmode,
6376                      GEN_INT (frv_trampoline_size ()), SImode,
6377                      fnaddr, Pmode,
6378                      sc_reg, Pmode);
6379 }
6380
6381 \f
6382 /* Many machines have some registers that cannot be copied directly to or from
6383    memory or even from other types of registers.  An example is the `MQ'
6384    register, which on most machines, can only be copied to or from general
6385    registers, but not memory.  Some machines allow copying all registers to and
6386    from memory, but require a scratch register for stores to some memory
6387    locations (e.g., those with symbolic address on the RT, and those with
6388    certain symbolic address on the SPARC when compiling PIC).  In some cases,
6389    both an intermediate and a scratch register are required.
6390
6391    You should define these macros to indicate to the reload phase that it may
6392    need to allocate at least one register for a reload in addition to the
6393    register to contain the data.  Specifically, if copying X to a register
6394    RCLASS in MODE requires an intermediate register, you should define
6395    `SECONDARY_INPUT_RELOAD_CLASS' to return the largest register class all of
6396    whose registers can be used as intermediate registers or scratch registers.
6397
6398    If copying a register RCLASS in MODE to X requires an intermediate or scratch
6399    register, `SECONDARY_OUTPUT_RELOAD_CLASS' should be defined to return the
6400    largest register class required.  If the requirements for input and output
6401    reloads are the same, the macro `SECONDARY_RELOAD_CLASS' should be used
6402    instead of defining both macros identically.
6403
6404    The values returned by these macros are often `GENERAL_REGS'.  Return
6405    `NO_REGS' if no spare register is needed; i.e., if X can be directly copied
6406    to or from a register of RCLASS in MODE without requiring a scratch register.
6407    Do not define this macro if it would always return `NO_REGS'.
6408
6409    If a scratch register is required (either with or without an intermediate
6410    register), you should define patterns for `reload_inM' or `reload_outM', as
6411    required..  These patterns, which will normally be implemented with a
6412    `define_expand', should be similar to the `movM' patterns, except that
6413    operand 2 is the scratch register.
6414
6415    Define constraints for the reload register and scratch register that contain
6416    a single register class.  If the original reload register (whose class is
6417    RCLASS) can meet the constraint given in the pattern, the value returned by
6418    these macros is used for the class of the scratch register.  Otherwise, two
6419    additional reload registers are required.  Their classes are obtained from
6420    the constraints in the insn pattern.
6421
6422    X might be a pseudo-register or a `subreg' of a pseudo-register, which could
6423    either be in a hard register or in memory.  Use `true_regnum' to find out;
6424    it will return -1 if the pseudo is in memory and the hard register number if
6425    it is in a register.
6426
6427    These macros should not be used in the case where a particular class of
6428    registers can only be copied to memory and not to another class of
6429    registers.  In that case, secondary reload registers are not needed and
6430    would not be helpful.  Instead, a stack location must be used to perform the
6431    copy and the `movM' pattern should use memory as an intermediate storage.
6432    This case often occurs between floating-point and general registers.  */
6433
6434 enum reg_class
6435 frv_secondary_reload_class (enum reg_class rclass,
6436                             enum machine_mode mode ATTRIBUTE_UNUSED,
6437                             rtx x)
6438 {
6439   enum reg_class ret;
6440
6441   switch (rclass)
6442     {
6443     default:
6444       ret = NO_REGS;
6445       break;
6446
6447       /* Accumulators/Accumulator guard registers need to go through floating
6448          point registers.  */
6449     case QUAD_REGS:
6450     case EVEN_REGS:
6451     case GPR_REGS:
6452       ret = NO_REGS;
6453       if (x && GET_CODE (x) == REG)
6454         {
6455           int regno = REGNO (x);
6456
6457           if (ACC_P (regno) || ACCG_P (regno))
6458             ret = FPR_REGS;
6459         }
6460       break;
6461
6462       /* Nonzero constants should be loaded into an FPR through a GPR.  */
6463     case QUAD_FPR_REGS:
6464     case FEVEN_REGS:
6465     case FPR_REGS:
6466       if (x && CONSTANT_P (x) && !ZERO_P (x))
6467         ret = GPR_REGS;
6468       else
6469         ret = NO_REGS;
6470       break;
6471
6472       /* All of these types need gpr registers.  */
6473     case ICC_REGS:
6474     case FCC_REGS:
6475     case CC_REGS:
6476     case ICR_REGS:
6477     case FCR_REGS:
6478     case CR_REGS:
6479     case LCR_REG:
6480     case LR_REG:
6481       ret = GPR_REGS;
6482       break;
6483
6484       /* The accumulators need fpr registers.  */
6485     case ACC_REGS:
6486     case EVEN_ACC_REGS:
6487     case QUAD_ACC_REGS:
6488     case ACCG_REGS:
6489       ret = FPR_REGS;
6490       break;
6491     }
6492
6493   return ret;
6494 }
6495
6496 /* This hook exists to catch the case where secondary_reload_class() is
6497    called from init_reg_autoinc() in regclass.c - before the reload optabs
6498    have been initialised.  */
6499    
6500 static reg_class_t
6501 frv_secondary_reload (bool in_p, rtx x, reg_class_t reload_class_i,
6502                       enum machine_mode reload_mode,
6503                       secondary_reload_info * sri)
6504 {
6505   enum reg_class rclass = NO_REGS;
6506   enum reg_class reload_class = (enum reg_class) reload_class_i;
6507
6508   if (sri->prev_sri && sri->prev_sri->t_icode != CODE_FOR_nothing)
6509     {
6510       sri->icode = sri->prev_sri->t_icode;
6511       return NO_REGS;
6512     }
6513
6514   rclass = frv_secondary_reload_class (reload_class, reload_mode, x);
6515
6516   if (rclass != NO_REGS)
6517     {
6518       enum insn_code icode
6519         = direct_optab_handler (in_p ? reload_in_optab : reload_out_optab,
6520                                 reload_mode);
6521       if (icode == 0)
6522         {
6523           /* This happens when then the reload_[in|out]_optabs have
6524              not been initialised.  */
6525           sri->t_icode = CODE_FOR_nothing;
6526           return rclass;
6527         }
6528     }
6529
6530   /* Fall back to the default secondary reload handler.  */
6531   return default_secondary_reload (in_p, x, reload_class, reload_mode, sri);
6532
6533 }
6534 \f
6535 /* Worker function for TARGET_CLASS_LIKELY_SPILLED_P.  */
6536
6537 static bool
6538 frv_class_likely_spilled_p (reg_class_t rclass)
6539 {
6540   switch (rclass)
6541     {
6542     default:
6543       break;
6544
6545     case GR8_REGS:
6546     case GR9_REGS:
6547     case GR89_REGS:
6548     case FDPIC_FPTR_REGS:
6549     case FDPIC_REGS:
6550     case ICC_REGS:
6551     case FCC_REGS:
6552     case CC_REGS:
6553     case ICR_REGS:
6554     case FCR_REGS:
6555     case CR_REGS:
6556     case LCR_REG:
6557     case LR_REG:
6558     case SPR_REGS:
6559     case QUAD_ACC_REGS:
6560     case EVEN_ACC_REGS:
6561     case ACC_REGS:
6562     case ACCG_REGS:
6563       return true;
6564     }
6565
6566   return false;
6567 }
6568
6569 \f
6570 /* An expression for the alignment of a structure field FIELD if the
6571    alignment computed in the usual way is COMPUTED.  GCC uses this
6572    value instead of the value in `BIGGEST_ALIGNMENT' or
6573    `BIGGEST_FIELD_ALIGNMENT', if defined, for structure fields only.  */
6574
6575 /* The definition type of the bit field data is either char, short, long or
6576    long long. The maximum bit size is the number of bits of its own type.
6577
6578    The bit field data is assigned to a storage unit that has an adequate size
6579    for bit field data retention and is located at the smallest address.
6580
6581    Consecutive bit field data are packed at consecutive bits having the same
6582    storage unit, with regard to the type, beginning with the MSB and continuing
6583    toward the LSB.
6584
6585    If a field to be assigned lies over a bit field type boundary, its
6586    assignment is completed by aligning it with a boundary suitable for the
6587    type.
6588
6589    When a bit field having a bit length of 0 is declared, it is forcibly
6590    assigned to the next storage unit.
6591
6592    e.g)
6593         struct {
6594                 int     a:2;
6595                 int     b:6;
6596                 char    c:4;
6597                 int     d:10;
6598                 int      :0;
6599                 int     f:2;
6600         } x;
6601
6602                 +0        +1        +2        +3
6603         &x      00000000  00000000  00000000  00000000
6604                 MLM----L
6605                 a    b
6606         &x+4    00000000  00000000  00000000  00000000
6607                 M--L
6608                 c
6609         &x+8    00000000  00000000  00000000  00000000
6610                 M----------L
6611                 d
6612         &x+12   00000000  00000000  00000000  00000000
6613                 ML
6614                 f
6615 */
6616
6617 int
6618 frv_adjust_field_align (tree field, int computed)
6619 {
6620   /* Make sure that the bitfield is not wider than the type.  */
6621   if (DECL_BIT_FIELD (field)
6622       && !DECL_ARTIFICIAL (field))
6623     {
6624       tree parent = DECL_CONTEXT (field);
6625       tree prev = NULL_TREE;
6626       tree cur;
6627
6628       for (cur = TYPE_FIELDS (parent); cur && cur != field; cur = DECL_CHAIN (cur))
6629         {
6630           if (TREE_CODE (cur) != FIELD_DECL)
6631             continue;
6632
6633           prev = cur;
6634         }
6635
6636       gcc_assert (cur);
6637
6638       /* If this isn't a :0 field and if the previous element is a bitfield
6639          also, see if the type is different, if so, we will need to align the
6640          bit-field to the next boundary.  */
6641       if (prev
6642           && ! DECL_PACKED (field)
6643           && ! integer_zerop (DECL_SIZE (field))
6644           && DECL_BIT_FIELD_TYPE (field) != DECL_BIT_FIELD_TYPE (prev))
6645         {
6646           int prev_align = TYPE_ALIGN (TREE_TYPE (prev));
6647           int cur_align  = TYPE_ALIGN (TREE_TYPE (field));
6648           computed = (prev_align > cur_align) ? prev_align : cur_align;
6649         }
6650     }
6651
6652   return computed;
6653 }
6654
6655 \f
6656 /* A C expression that is nonzero if it is permissible to store a value of mode
6657    MODE in hard register number REGNO (or in several registers starting with
6658    that one).  For a machine where all registers are equivalent, a suitable
6659    definition is
6660
6661         #define HARD_REGNO_MODE_OK(REGNO, MODE) 1
6662
6663    It is not necessary for this macro to check for the numbers of fixed
6664    registers, because the allocation mechanism considers them to be always
6665    occupied.
6666
6667    On some machines, double-precision values must be kept in even/odd register
6668    pairs.  The way to implement that is to define this macro to reject odd
6669    register numbers for such modes.
6670
6671    The minimum requirement for a mode to be OK in a register is that the
6672    `movMODE' instruction pattern support moves between the register and any
6673    other hard register for which the mode is OK; and that moving a value into
6674    the register and back out not alter it.
6675
6676    Since the same instruction used to move `SImode' will work for all narrower
6677    integer modes, it is not necessary on any machine for `HARD_REGNO_MODE_OK'
6678    to distinguish between these modes, provided you define patterns `movhi',
6679    etc., to take advantage of this.  This is useful because of the interaction
6680    between `HARD_REGNO_MODE_OK' and `MODES_TIEABLE_P'; it is very desirable for
6681    all integer modes to be tieable.
6682
6683    Many machines have special registers for floating point arithmetic.  Often
6684    people assume that floating point machine modes are allowed only in floating
6685    point registers.  This is not true.  Any registers that can hold integers
6686    can safely *hold* a floating point machine mode, whether or not floating
6687    arithmetic can be done on it in those registers.  Integer move instructions
6688    can be used to move the values.
6689
6690    On some machines, though, the converse is true: fixed-point machine modes
6691    may not go in floating registers.  This is true if the floating registers
6692    normalize any value stored in them, because storing a non-floating value
6693    there would garble it.  In this case, `HARD_REGNO_MODE_OK' should reject
6694    fixed-point machine modes in floating registers.  But if the floating
6695    registers do not automatically normalize, if you can store any bit pattern
6696    in one and retrieve it unchanged without a trap, then any machine mode may
6697    go in a floating register, so you can define this macro to say so.
6698
6699    The primary significance of special floating registers is rather that they
6700    are the registers acceptable in floating point arithmetic instructions.
6701    However, this is of no concern to `HARD_REGNO_MODE_OK'.  You handle it by
6702    writing the proper constraints for those instructions.
6703
6704    On some machines, the floating registers are especially slow to access, so
6705    that it is better to store a value in a stack frame than in such a register
6706    if floating point arithmetic is not being done.  As long as the floating
6707    registers are not in class `GENERAL_REGS', they will not be used unless some
6708    pattern's constraint asks for one.  */
6709
6710 int
6711 frv_hard_regno_mode_ok (int regno, enum machine_mode mode)
6712 {
6713   int base;
6714   int mask;
6715
6716   switch (mode)
6717     {
6718     case CCmode:
6719     case CC_UNSmode:
6720     case CC_NZmode:
6721       return ICC_P (regno) || GPR_P (regno);
6722
6723     case CC_CCRmode:
6724       return CR_P (regno) || GPR_P (regno);
6725
6726     case CC_FPmode:
6727       return FCC_P (regno) || GPR_P (regno);
6728
6729     default:
6730       break;
6731     }
6732
6733   /* Set BASE to the first register in REGNO's class.  Set MASK to the
6734      bits that must be clear in (REGNO - BASE) for the register to be
6735      well-aligned.  */
6736   if (INTEGRAL_MODE_P (mode) || FLOAT_MODE_P (mode) || VECTOR_MODE_P (mode))
6737     {
6738       if (ACCG_P (regno))
6739         {
6740           /* ACCGs store one byte.  Two-byte quantities must start in
6741              even-numbered registers, four-byte ones in registers whose
6742              numbers are divisible by four, and so on.  */
6743           base = ACCG_FIRST;
6744           mask = GET_MODE_SIZE (mode) - 1;
6745         }
6746       else
6747         {
6748            /* The other registers store one word.  */
6749           if (GPR_P (regno) || regno == AP_FIRST)
6750             base = GPR_FIRST;
6751
6752           else if (FPR_P (regno))
6753             base = FPR_FIRST;
6754
6755           else if (ACC_P (regno))
6756             base = ACC_FIRST;
6757
6758           else if (SPR_P (regno))
6759             return mode == SImode;
6760
6761           /* Fill in the table.  */
6762           else
6763             return 0;
6764
6765           /* Anything smaller than an SI is OK in any word-sized register.  */
6766           if (GET_MODE_SIZE (mode) < 4)
6767             return 1;
6768
6769           mask = (GET_MODE_SIZE (mode) / 4) - 1;
6770         }
6771       return (((regno - base) & mask) == 0);
6772     }
6773
6774   return 0;
6775 }
6776
6777 \f
6778 /* A C expression for the number of consecutive hard registers, starting at
6779    register number REGNO, required to hold a value of mode MODE.
6780
6781    On a machine where all registers are exactly one word, a suitable definition
6782    of this macro is
6783
6784         #define HARD_REGNO_NREGS(REGNO, MODE)            \
6785            ((GET_MODE_SIZE (MODE) + UNITS_PER_WORD - 1)  \
6786             / UNITS_PER_WORD))  */
6787
6788 /* On the FRV, make the CC_FP mode take 3 words in the integer registers, so
6789    that we can build the appropriate instructions to properly reload the
6790    values.  Also, make the byte-sized accumulator guards use one guard
6791    for each byte.  */
6792
6793 int
6794 frv_hard_regno_nregs (int regno, enum machine_mode mode)
6795 {
6796   if (ACCG_P (regno))
6797     return GET_MODE_SIZE (mode);
6798   else
6799     return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
6800 }
6801
6802 \f
6803 /* A C expression for the maximum number of consecutive registers of
6804    class RCLASS needed to hold a value of mode MODE.
6805
6806    This is closely related to the macro `HARD_REGNO_NREGS'.  In fact, the value
6807    of the macro `CLASS_MAX_NREGS (RCLASS, MODE)' should be the maximum value of
6808    `HARD_REGNO_NREGS (REGNO, MODE)' for all REGNO values in the class RCLASS.
6809
6810    This macro helps control the handling of multiple-word values in
6811    the reload pass.
6812
6813    This declaration is required.  */
6814
6815 int
6816 frv_class_max_nregs (enum reg_class rclass, enum machine_mode mode)
6817 {
6818   if (rclass == ACCG_REGS)
6819     /* An N-byte value requires N accumulator guards.  */
6820     return GET_MODE_SIZE (mode);
6821   else
6822     return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
6823 }
6824
6825 \f
6826 /* A C expression that is nonzero if X is a legitimate constant for an
6827    immediate operand on the target machine.  You can assume that X satisfies
6828    `CONSTANT_P', so you need not check this.  In fact, `1' is a suitable
6829    definition for this macro on machines where anything `CONSTANT_P' is valid.  */
6830
6831 int
6832 frv_legitimate_constant_p (rtx x)
6833 {
6834   enum machine_mode mode = GET_MODE (x);
6835
6836   /* frv_cannot_force_const_mem always returns true for FDPIC.  This
6837      means that the move expanders will be expected to deal with most
6838      kinds of constant, regardless of what we return here.
6839
6840      However, among its other duties, LEGITIMATE_CONSTANT_P decides whether
6841      a constant can be entered into reg_equiv_constant[].  If we return true,
6842      reload can create new instances of the constant whenever it likes.
6843
6844      The idea is therefore to accept as many constants as possible (to give
6845      reload more freedom) while rejecting constants that can only be created
6846      at certain times.  In particular, anything with a symbolic component will
6847      require use of the pseudo FDPIC register, which is only available before
6848      reload.  */
6849   if (TARGET_FDPIC)
6850     return LEGITIMATE_PIC_OPERAND_P (x);
6851
6852   /* All of the integer constants are ok.  */
6853   if (GET_CODE (x) != CONST_DOUBLE)
6854     return TRUE;
6855
6856   /* double integer constants are ok.  */
6857   if (mode == VOIDmode || mode == DImode)
6858     return TRUE;
6859
6860   /* 0 is always ok.  */
6861   if (x == CONST0_RTX (mode))
6862     return TRUE;
6863
6864   /* If floating point is just emulated, allow any constant, since it will be
6865      constructed in the GPRs.  */
6866   if (!TARGET_HAS_FPRS)
6867     return TRUE;
6868
6869   if (mode == DFmode && !TARGET_DOUBLE)
6870     return TRUE;
6871
6872   /* Otherwise store the constant away and do a load.  */
6873   return FALSE;
6874 }
6875
6876 /* Implement SELECT_CC_MODE.  Choose CC_FP for floating-point comparisons,
6877    CC_NZ for comparisons against zero in which a single Z or N flag test
6878    is enough, CC_UNS for other unsigned comparisons, and CC for other
6879    signed comparisons.  */
6880
6881 enum machine_mode
6882 frv_select_cc_mode (enum rtx_code code, rtx x, rtx y)
6883 {
6884   if (GET_MODE_CLASS (GET_MODE (x)) == MODE_FLOAT)
6885     return CC_FPmode;
6886
6887   switch (code)
6888     {
6889     case EQ:
6890     case NE:
6891     case LT:
6892     case GE:
6893       return y == const0_rtx ? CC_NZmode : CCmode;
6894
6895     case GTU:
6896     case GEU:
6897     case LTU:
6898     case LEU:
6899       return y == const0_rtx ? CC_NZmode : CC_UNSmode;
6900
6901     default:
6902       return CCmode;
6903     }
6904 }
6905 \f
6906
6907 /* Worker function for TARGET_REGISTER_MOVE_COST.  */
6908
6909 #define HIGH_COST 40
6910 #define MEDIUM_COST 3
6911 #define LOW_COST 1
6912
6913 static int
6914 frv_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
6915                         reg_class_t from, reg_class_t to)
6916 {
6917   switch (from)
6918     {
6919     default:
6920       break;
6921
6922     case QUAD_REGS:
6923     case EVEN_REGS:
6924     case GPR_REGS:
6925       switch (to)
6926         {
6927         default:
6928           break;
6929
6930         case QUAD_REGS:
6931         case EVEN_REGS:
6932         case GPR_REGS:
6933           return LOW_COST;
6934
6935         case FEVEN_REGS:
6936         case FPR_REGS:
6937           return LOW_COST;
6938
6939         case LCR_REG:
6940         case LR_REG:
6941         case SPR_REGS:
6942           return LOW_COST;
6943         }
6944
6945     case FEVEN_REGS:
6946     case FPR_REGS:
6947       switch (to)
6948         {
6949         default:
6950           break;
6951
6952         case QUAD_REGS:
6953         case EVEN_REGS:
6954         case GPR_REGS:
6955         case ACC_REGS:
6956         case EVEN_ACC_REGS:
6957         case QUAD_ACC_REGS:
6958         case ACCG_REGS:
6959           return MEDIUM_COST;
6960
6961         case FEVEN_REGS:
6962         case FPR_REGS:
6963           return LOW_COST;
6964         }
6965
6966     case LCR_REG:
6967     case LR_REG:
6968     case SPR_REGS:
6969       switch (to)
6970         {
6971         default:
6972           break;
6973
6974         case QUAD_REGS:
6975         case EVEN_REGS:
6976         case GPR_REGS:
6977           return MEDIUM_COST;
6978         }
6979
6980     case ACC_REGS:
6981     case EVEN_ACC_REGS:
6982     case QUAD_ACC_REGS:
6983     case ACCG_REGS:
6984       switch (to)
6985         {
6986         default:
6987           break;
6988
6989         case FEVEN_REGS:
6990         case FPR_REGS:
6991           return MEDIUM_COST;
6992
6993         }
6994     }
6995
6996   return HIGH_COST;
6997 }
6998
6999 /* Worker function for TARGET_MEMORY_MOVE_COST.  */
7000
7001 static int
7002 frv_memory_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
7003                       reg_class_t rclass ATTRIBUTE_UNUSED,
7004                       bool in ATTRIBUTE_UNUSED)
7005 {
7006   return 4;
7007 }
7008
7009 \f
7010 /* Implementation of TARGET_ASM_INTEGER.  In the FRV case we need to
7011    use ".picptr" to generate safe relocations for PIC code.  We also
7012    need a fixup entry for aligned (non-debugging) code.  */
7013
7014 static bool
7015 frv_assemble_integer (rtx value, unsigned int size, int aligned_p)
7016 {
7017   if ((flag_pic || TARGET_FDPIC) && size == UNITS_PER_WORD)
7018     {
7019       if (GET_CODE (value) == CONST
7020           || GET_CODE (value) == SYMBOL_REF
7021           || GET_CODE (value) == LABEL_REF)
7022         {
7023           if (TARGET_FDPIC && GET_CODE (value) == SYMBOL_REF
7024               && SYMBOL_REF_FUNCTION_P (value))
7025             {
7026               fputs ("\t.picptr\tfuncdesc(", asm_out_file);
7027               output_addr_const (asm_out_file, value);
7028               fputs (")\n", asm_out_file);
7029               return true;
7030             }
7031           else if (TARGET_FDPIC && GET_CODE (value) == CONST
7032                    && frv_function_symbol_referenced_p (value))
7033             return false;
7034           if (aligned_p && !TARGET_FDPIC)
7035             {
7036               static int label_num = 0;
7037               char buf[256];
7038               const char *p;
7039
7040               ASM_GENERATE_INTERNAL_LABEL (buf, "LCP", label_num++);
7041               p = (* targetm.strip_name_encoding) (buf);
7042
7043               fprintf (asm_out_file, "%s:\n", p);
7044               fprintf (asm_out_file, "%s\n", FIXUP_SECTION_ASM_OP);
7045               fprintf (asm_out_file, "\t.picptr\t%s\n", p);
7046               fprintf (asm_out_file, "\t.previous\n");
7047             }
7048           assemble_integer_with_op ("\t.picptr\t", value);
7049           return true;
7050         }
7051       if (!aligned_p)
7052         {
7053           /* We've set the unaligned SI op to NULL, so we always have to
7054              handle the unaligned case here.  */
7055           assemble_integer_with_op ("\t.4byte\t", value);
7056           return true;
7057         }
7058     }
7059   return default_assemble_integer (value, size, aligned_p);
7060 }
7061
7062 /* Function to set up the backend function structure.  */
7063
7064 static struct machine_function *
7065 frv_init_machine_status (void)
7066 {
7067   return ggc_alloc_cleared_machine_function ();
7068 }
7069 \f
7070 /* Implement TARGET_SCHED_ISSUE_RATE.  */
7071
7072 int
7073 frv_issue_rate (void)
7074 {
7075   if (!TARGET_PACK)
7076     return 1;
7077
7078   switch (frv_cpu_type)
7079     {
7080     default:
7081     case FRV_CPU_FR300:
7082     case FRV_CPU_SIMPLE:
7083       return 1;
7084
7085     case FRV_CPU_FR400:
7086     case FRV_CPU_FR405:
7087     case FRV_CPU_FR450:
7088       return 2;
7089
7090     case FRV_CPU_GENERIC:
7091     case FRV_CPU_FR500:
7092     case FRV_CPU_TOMCAT:
7093       return 4;
7094
7095     case FRV_CPU_FR550:
7096       return 8;
7097     }
7098 }
7099 \f
7100 /* A for_each_rtx callback.  If X refers to an accumulator, return
7101    ACC_GROUP_ODD if the bit 2 of the register number is set and
7102    ACC_GROUP_EVEN if it is clear.  Return 0 (ACC_GROUP_NONE)
7103    otherwise.  */
7104
7105 static int
7106 frv_acc_group_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
7107 {
7108   if (REG_P (*x))
7109     {
7110       if (ACC_P (REGNO (*x)))
7111         return (REGNO (*x) - ACC_FIRST) & 4 ? ACC_GROUP_ODD : ACC_GROUP_EVEN;
7112       if (ACCG_P (REGNO (*x)))
7113         return (REGNO (*x) - ACCG_FIRST) & 4 ? ACC_GROUP_ODD : ACC_GROUP_EVEN;
7114     }
7115   return 0;
7116 }
7117
7118 /* Return the value of INSN's acc_group attribute.  */
7119
7120 int
7121 frv_acc_group (rtx insn)
7122 {
7123   /* This distinction only applies to the FR550 packing constraints.  */
7124   if (frv_cpu_type != FRV_CPU_FR550)
7125     return ACC_GROUP_NONE;
7126   return for_each_rtx (&PATTERN (insn), frv_acc_group_1, 0);
7127 }
7128
7129 /* Return the index of the DFA unit in FRV_UNIT_NAMES[] that instruction
7130    INSN will try to claim first.  Since this value depends only on the
7131    type attribute, we can cache the results in FRV_TYPE_TO_UNIT[].  */
7132
7133 static unsigned int
7134 frv_insn_unit (rtx insn)
7135 {
7136   enum attr_type type;
7137
7138   type = get_attr_type (insn);
7139   if (frv_type_to_unit[type] == ARRAY_SIZE (frv_unit_codes))
7140     {
7141       /* We haven't seen this type of instruction before.  */
7142       state_t state;
7143       unsigned int unit;
7144
7145       /* Issue the instruction on its own to see which unit it prefers.  */
7146       state = alloca (state_size ());
7147       state_reset (state);
7148       state_transition (state, insn);
7149
7150       /* Find out which unit was taken.  */
7151       for (unit = 0; unit < ARRAY_SIZE (frv_unit_codes); unit++)
7152         if (cpu_unit_reservation_p (state, frv_unit_codes[unit]))
7153           break;
7154
7155       gcc_assert (unit != ARRAY_SIZE (frv_unit_codes));
7156
7157       frv_type_to_unit[type] = unit;
7158     }
7159   return frv_type_to_unit[type];
7160 }
7161
7162 /* Return true if INSN issues to a branch unit.  */
7163
7164 static bool
7165 frv_issues_to_branch_unit_p (rtx insn)
7166 {
7167   return frv_unit_groups[frv_insn_unit (insn)] == GROUP_B;
7168 }
7169 \f
7170 /* The instructions in the packet, partitioned into groups.  */
7171 struct frv_packet_group {
7172   /* How many instructions in the packet belong to this group.  */
7173   unsigned int num_insns;
7174
7175   /* A list of the instructions that belong to this group, in the order
7176      they appear in the rtl stream.  */
7177   rtx insns[ARRAY_SIZE (frv_unit_codes)];
7178
7179   /* The contents of INSNS after they have been sorted into the correct
7180      assembly-language order.  Element X issues to unit X.  The list may
7181      contain extra nops.  */
7182   rtx sorted[ARRAY_SIZE (frv_unit_codes)];
7183
7184   /* The member of frv_nops[] to use in sorted[].  */
7185   rtx nop;
7186 };
7187
7188 /* The current state of the packing pass, implemented by frv_pack_insns.  */
7189 static struct {
7190   /* The state of the pipeline DFA.  */
7191   state_t dfa_state;
7192
7193   /* Which hardware registers are set within the current packet,
7194      and the conditions under which they are set.  */
7195   regstate_t regstate[FIRST_PSEUDO_REGISTER];
7196
7197   /* The memory locations that have been modified so far in this
7198      packet.  MEM is the memref and COND is the regstate_t condition
7199      under which it is set.  */
7200   struct {
7201     rtx mem;
7202     regstate_t cond;
7203   } mems[2];
7204
7205   /* The number of valid entries in MEMS.  The value is larger than
7206      ARRAY_SIZE (mems) if there were too many mems to record.  */
7207   unsigned int num_mems;
7208
7209   /* The maximum number of instructions that can be packed together.  */
7210   unsigned int issue_rate;
7211
7212   /* The instructions in the packet, partitioned into groups.  */
7213   struct frv_packet_group groups[NUM_GROUPS];
7214
7215   /* The instructions that make up the current packet.  */
7216   rtx insns[ARRAY_SIZE (frv_unit_codes)];
7217   unsigned int num_insns;
7218 } frv_packet;
7219
7220 /* Return the regstate_t flags for the given COND_EXEC condition.
7221    Abort if the condition isn't in the right form.  */
7222
7223 static int
7224 frv_cond_flags (rtx cond)
7225 {
7226   gcc_assert ((GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
7227               && GET_CODE (XEXP (cond, 0)) == REG
7228               && CR_P (REGNO (XEXP (cond, 0)))
7229               && XEXP (cond, 1) == const0_rtx);
7230   return ((REGNO (XEXP (cond, 0)) - CR_FIRST)
7231           | (GET_CODE (cond) == NE
7232              ? REGSTATE_IF_TRUE
7233              : REGSTATE_IF_FALSE));
7234 }
7235
7236
7237 /* Return true if something accessed under condition COND2 can
7238    conflict with something written under condition COND1.  */
7239
7240 static bool
7241 frv_regstate_conflict_p (regstate_t cond1, regstate_t cond2)
7242 {
7243   /* If either reference was unconditional, we have a conflict.  */
7244   if ((cond1 & REGSTATE_IF_EITHER) == 0
7245       || (cond2 & REGSTATE_IF_EITHER) == 0)
7246     return true;
7247
7248   /* The references might conflict if they were controlled by
7249      different CRs.  */
7250   if ((cond1 & REGSTATE_CC_MASK) != (cond2 & REGSTATE_CC_MASK))
7251     return true;
7252
7253   /* They definitely conflict if they are controlled by the
7254      same condition.  */
7255   if ((cond1 & cond2 & REGSTATE_IF_EITHER) != 0)
7256     return true;
7257
7258   return false;
7259 }
7260
7261
7262 /* A for_each_rtx callback.  Return 1 if *X depends on an instruction in
7263    the current packet.  DATA points to a regstate_t that describes the
7264    condition under which *X might be set or used.  */
7265
7266 static int
7267 frv_registers_conflict_p_1 (rtx *x, void *data)
7268 {
7269   unsigned int regno, i;
7270   regstate_t cond;
7271
7272   cond = *(regstate_t *) data;
7273
7274   if (GET_CODE (*x) == REG)
7275     FOR_EACH_REGNO (regno, *x)
7276       if ((frv_packet.regstate[regno] & REGSTATE_MODIFIED) != 0)
7277         if (frv_regstate_conflict_p (frv_packet.regstate[regno], cond))
7278           return 1;
7279
7280   if (GET_CODE (*x) == MEM)
7281     {
7282       /* If we ran out of memory slots, assume a conflict.  */
7283       if (frv_packet.num_mems > ARRAY_SIZE (frv_packet.mems))
7284         return 1;
7285
7286       /* Check for output or true dependencies with earlier MEMs.  */
7287       for (i = 0; i < frv_packet.num_mems; i++)
7288         if (frv_regstate_conflict_p (frv_packet.mems[i].cond, cond))
7289           {
7290             if (true_dependence (frv_packet.mems[i].mem, VOIDmode,
7291                                  *x, rtx_varies_p))
7292               return 1;
7293
7294             if (output_dependence (frv_packet.mems[i].mem, *x))
7295               return 1;
7296           }
7297     }
7298
7299   /* The return values of calls aren't significant: they describe
7300      the effect of the call as a whole, not of the insn itself.  */
7301   if (GET_CODE (*x) == SET && GET_CODE (SET_SRC (*x)) == CALL)
7302     {
7303       if (for_each_rtx (&SET_SRC (*x), frv_registers_conflict_p_1, data))
7304         return 1;
7305       return -1;
7306     }
7307
7308   /* Check subexpressions.  */
7309   return 0;
7310 }
7311
7312
7313 /* Return true if something in X might depend on an instruction
7314    in the current packet.  */
7315
7316 static bool
7317 frv_registers_conflict_p (rtx x)
7318 {
7319   regstate_t flags;
7320
7321   flags = 0;
7322   if (GET_CODE (x) == COND_EXEC)
7323     {
7324       if (for_each_rtx (&XEXP (x, 0), frv_registers_conflict_p_1, &flags))
7325         return true;
7326
7327       flags |= frv_cond_flags (XEXP (x, 0));
7328       x = XEXP (x, 1);
7329     }
7330   return for_each_rtx (&x, frv_registers_conflict_p_1, &flags);
7331 }
7332
7333
7334 /* A note_stores callback.  DATA points to the regstate_t condition
7335    under which X is modified.  Update FRV_PACKET accordingly.  */
7336
7337 static void
7338 frv_registers_update_1 (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
7339 {
7340   unsigned int regno;
7341
7342   if (GET_CODE (x) == REG)
7343     FOR_EACH_REGNO (regno, x)
7344       frv_packet.regstate[regno] |= *(regstate_t *) data;
7345
7346   if (GET_CODE (x) == MEM)
7347     {
7348       if (frv_packet.num_mems < ARRAY_SIZE (frv_packet.mems))
7349         {
7350           frv_packet.mems[frv_packet.num_mems].mem = x;
7351           frv_packet.mems[frv_packet.num_mems].cond = *(regstate_t *) data;
7352         }
7353       frv_packet.num_mems++;
7354     }
7355 }
7356
7357
7358 /* Update the register state information for an instruction whose
7359    body is X.  */
7360
7361 static void
7362 frv_registers_update (rtx x)
7363 {
7364   regstate_t flags;
7365
7366   flags = REGSTATE_MODIFIED;
7367   if (GET_CODE (x) == COND_EXEC)
7368     {
7369       flags |= frv_cond_flags (XEXP (x, 0));
7370       x = XEXP (x, 1);
7371     }
7372   note_stores (x, frv_registers_update_1, &flags);
7373 }
7374
7375
7376 /* Initialize frv_packet for the start of a new packet.  */
7377
7378 static void
7379 frv_start_packet (void)
7380 {
7381   enum frv_insn_group group;
7382
7383   memset (frv_packet.regstate, 0, sizeof (frv_packet.regstate));
7384   frv_packet.num_mems = 0;
7385   frv_packet.num_insns = 0;
7386   for (group =  GROUP_I; group < NUM_GROUPS;
7387        group = (enum frv_insn_group) (group + 1))
7388     frv_packet.groups[group].num_insns = 0;
7389 }
7390
7391
7392 /* Likewise for the start of a new basic block.  */
7393
7394 static void
7395 frv_start_packet_block (void)
7396 {
7397   state_reset (frv_packet.dfa_state);
7398   frv_start_packet ();
7399 }
7400
7401
7402 /* Finish the current packet, if any, and start a new one.  Call
7403    HANDLE_PACKET with FRV_PACKET describing the completed packet.  */
7404
7405 static void
7406 frv_finish_packet (void (*handle_packet) (void))
7407 {
7408   if (frv_packet.num_insns > 0)
7409     {
7410       handle_packet ();
7411       state_transition (frv_packet.dfa_state, 0);
7412       frv_start_packet ();
7413     }
7414 }
7415
7416
7417 /* Return true if INSN can be added to the current packet.  Update
7418    the DFA state on success.  */
7419
7420 static bool
7421 frv_pack_insn_p (rtx insn)
7422 {
7423   /* See if the packet is already as long as it can be.  */
7424   if (frv_packet.num_insns == frv_packet.issue_rate)
7425     return false;
7426
7427   /* If the scheduler thought that an instruction should start a packet,
7428      it's usually a good idea to believe it.  It knows much more about
7429      the latencies than we do.
7430
7431      There are some exceptions though:
7432
7433        - Conditional instructions are scheduled on the assumption that
7434          they will be executed.  This is usually a good thing, since it
7435          tends to avoid unnecessary stalls in the conditional code.
7436          But we want to pack conditional instructions as tightly as
7437          possible, in order to optimize the case where they aren't
7438          executed.
7439
7440        - The scheduler will always put branches on their own, even
7441          if there's no real dependency.
7442
7443        - There's no point putting a call in its own packet unless
7444          we have to.  */
7445   if (frv_packet.num_insns > 0
7446       && GET_CODE (insn) == INSN
7447       && GET_MODE (insn) == TImode
7448       && GET_CODE (PATTERN (insn)) != COND_EXEC)
7449     return false;
7450
7451   /* Check for register conflicts.  Don't do this for setlo since any
7452      conflict will be with the partnering sethi, with which it can
7453      be packed.  */
7454   if (get_attr_type (insn) != TYPE_SETLO)
7455     if (frv_registers_conflict_p (PATTERN (insn)))
7456       return false;
7457
7458   return state_transition (frv_packet.dfa_state, insn) < 0;
7459 }
7460
7461
7462 /* Add instruction INSN to the current packet.  */
7463
7464 static void
7465 frv_add_insn_to_packet (rtx insn)
7466 {
7467   struct frv_packet_group *packet_group;
7468
7469   packet_group = &frv_packet.groups[frv_unit_groups[frv_insn_unit (insn)]];
7470   packet_group->insns[packet_group->num_insns++] = insn;
7471   frv_packet.insns[frv_packet.num_insns++] = insn;
7472
7473   frv_registers_update (PATTERN (insn));
7474 }
7475
7476
7477 /* Insert INSN (a member of frv_nops[]) into the current packet.  If the
7478    packet ends in a branch or call, insert the nop before it, otherwise
7479    add to the end.  */
7480
7481 static void
7482 frv_insert_nop_in_packet (rtx insn)
7483 {
7484   struct frv_packet_group *packet_group;
7485   rtx last;
7486
7487   packet_group = &frv_packet.groups[frv_unit_groups[frv_insn_unit (insn)]];
7488   last = frv_packet.insns[frv_packet.num_insns - 1];
7489   if (GET_CODE (last) != INSN)
7490     {
7491       insn = emit_insn_before (PATTERN (insn), last);
7492       frv_packet.insns[frv_packet.num_insns - 1] = insn;
7493       frv_packet.insns[frv_packet.num_insns++] = last;
7494     }
7495   else
7496     {
7497       insn = emit_insn_after (PATTERN (insn), last);
7498       frv_packet.insns[frv_packet.num_insns++] = insn;
7499     }
7500   packet_group->insns[packet_group->num_insns++] = insn;
7501 }
7502
7503
7504 /* If packing is enabled, divide the instructions into packets and
7505    return true.  Call HANDLE_PACKET for each complete packet.  */
7506
7507 static bool
7508 frv_for_each_packet (void (*handle_packet) (void))
7509 {
7510   rtx insn, next_insn;
7511
7512   frv_packet.issue_rate = frv_issue_rate ();
7513
7514   /* Early exit if we don't want to pack insns.  */
7515   if (!optimize
7516       || !flag_schedule_insns_after_reload
7517       || !TARGET_VLIW_BRANCH
7518       || frv_packet.issue_rate == 1)
7519     return false;
7520
7521   /* Set up the initial packing state.  */
7522   dfa_start ();
7523   frv_packet.dfa_state = alloca (state_size ());
7524
7525   frv_start_packet_block ();
7526   for (insn = get_insns (); insn != 0; insn = next_insn)
7527     {
7528       enum rtx_code code;
7529       bool eh_insn_p;
7530
7531       code = GET_CODE (insn);
7532       next_insn = NEXT_INSN (insn);
7533
7534       if (code == CODE_LABEL)
7535         {
7536           frv_finish_packet (handle_packet);
7537           frv_start_packet_block ();
7538         }
7539
7540       if (INSN_P (insn))
7541         switch (GET_CODE (PATTERN (insn)))
7542           {
7543           case USE:
7544           case CLOBBER:
7545           case ADDR_VEC:
7546           case ADDR_DIFF_VEC:
7547             break;
7548
7549           default:
7550             /* Calls mustn't be packed on a TOMCAT.  */
7551             if (GET_CODE (insn) == CALL_INSN && frv_cpu_type == FRV_CPU_TOMCAT)
7552               frv_finish_packet (handle_packet);
7553
7554             /* Since the last instruction in a packet determines the EH
7555                region, any exception-throwing instruction must come at
7556                the end of reordered packet.  Insns that issue to a
7557                branch unit are bound to come last; for others it's
7558                too hard to predict.  */
7559             eh_insn_p = (find_reg_note (insn, REG_EH_REGION, NULL) != NULL);
7560             if (eh_insn_p && !frv_issues_to_branch_unit_p (insn))
7561               frv_finish_packet (handle_packet);
7562
7563             /* Finish the current packet if we can't add INSN to it.
7564                Simulate cycles until INSN is ready to issue.  */
7565             if (!frv_pack_insn_p (insn))
7566               {
7567                 frv_finish_packet (handle_packet);
7568                 while (!frv_pack_insn_p (insn))
7569                   state_transition (frv_packet.dfa_state, 0);
7570               }
7571
7572             /* Add the instruction to the packet.  */
7573             frv_add_insn_to_packet (insn);
7574
7575             /* Calls and jumps end a packet, as do insns that throw
7576                an exception.  */
7577             if (code == CALL_INSN || code == JUMP_INSN || eh_insn_p)
7578               frv_finish_packet (handle_packet);
7579             break;
7580           }
7581     }
7582   frv_finish_packet (handle_packet);
7583   dfa_finish ();
7584   return true;
7585 }
7586 \f
7587 /* Subroutine of frv_sort_insn_group.  We are trying to sort
7588    frv_packet.groups[GROUP].sorted[0...NUM_INSNS-1] into assembly
7589    language order.  We have already picked a new position for
7590    frv_packet.groups[GROUP].sorted[X] if bit X of ISSUED is set.
7591    These instructions will occupy elements [0, LOWER_SLOT) and
7592    [UPPER_SLOT, NUM_INSNS) of the final (sorted) array.  STATE is
7593    the DFA state after issuing these instructions.
7594
7595    Try filling elements [LOWER_SLOT, UPPER_SLOT) with every permutation
7596    of the unused instructions.  Return true if one such permutation gives
7597    a valid ordering, leaving the successful permutation in sorted[].
7598    Do not modify sorted[] until a valid permutation is found.  */
7599
7600 static bool
7601 frv_sort_insn_group_1 (enum frv_insn_group group,
7602                        unsigned int lower_slot, unsigned int upper_slot,
7603                        unsigned int issued, unsigned int num_insns,
7604                        state_t state)
7605 {
7606   struct frv_packet_group *packet_group;
7607   unsigned int i;
7608   state_t test_state;
7609   size_t dfa_size;
7610   rtx insn;
7611
7612   /* Early success if we've filled all the slots.  */
7613   if (lower_slot == upper_slot)
7614     return true;
7615
7616   packet_group = &frv_packet.groups[group];
7617   dfa_size = state_size ();
7618   test_state = alloca (dfa_size);
7619
7620   /* Try issuing each unused instruction.  */
7621   for (i = num_insns - 1; i + 1 != 0; i--)
7622     if (~issued & (1 << i))
7623       {
7624         insn = packet_group->sorted[i];
7625         memcpy (test_state, state, dfa_size);
7626         if (state_transition (test_state, insn) < 0
7627             && cpu_unit_reservation_p (test_state,
7628                                        NTH_UNIT (group, upper_slot - 1))
7629             && frv_sort_insn_group_1 (group, lower_slot, upper_slot - 1,
7630                                       issued | (1 << i), num_insns,
7631                                       test_state))
7632           {
7633             packet_group->sorted[upper_slot - 1] = insn;
7634             return true;
7635           }
7636       }
7637
7638   return false;
7639 }
7640
7641 /* Compare two instructions by their frv_insn_unit.  */
7642
7643 static int
7644 frv_compare_insns (const void *first, const void *second)
7645 {
7646   const rtx *const insn1 = (rtx const *) first,
7647     *const insn2 = (rtx const *) second;
7648   return frv_insn_unit (*insn1) - frv_insn_unit (*insn2);
7649 }
7650
7651 /* Copy frv_packet.groups[GROUP].insns[] to frv_packet.groups[GROUP].sorted[]
7652    and sort it into assembly language order.  See frv.md for a description of
7653    the algorithm.  */
7654
7655 static void
7656 frv_sort_insn_group (enum frv_insn_group group)
7657 {
7658   struct frv_packet_group *packet_group;
7659   unsigned int first, i, nop, max_unit, num_slots;
7660   state_t state, test_state;
7661   size_t dfa_size;
7662
7663   packet_group = &frv_packet.groups[group];
7664
7665   /* Assume no nop is needed.  */
7666   packet_group->nop = 0;
7667
7668   if (packet_group->num_insns == 0)
7669     return;
7670
7671   /* Copy insns[] to sorted[].  */
7672   memcpy (packet_group->sorted, packet_group->insns,
7673           sizeof (rtx) * packet_group->num_insns);
7674
7675   /* Sort sorted[] by the unit that each insn tries to take first.  */
7676   if (packet_group->num_insns > 1)
7677     qsort (packet_group->sorted, packet_group->num_insns,
7678            sizeof (rtx), frv_compare_insns);
7679
7680   /* That's always enough for branch and control insns.  */
7681   if (group == GROUP_B || group == GROUP_C)
7682     return;
7683
7684   dfa_size = state_size ();
7685   state = alloca (dfa_size);
7686   test_state = alloca (dfa_size);
7687
7688   /* Find the highest FIRST such that sorted[0...FIRST-1] can issue
7689      consecutively and such that the DFA takes unit X when sorted[X]
7690      is added.  Set STATE to the new DFA state.  */
7691   state_reset (test_state);
7692   for (first = 0; first < packet_group->num_insns; first++)
7693     {
7694       memcpy (state, test_state, dfa_size);
7695       if (state_transition (test_state, packet_group->sorted[first]) >= 0
7696           || !cpu_unit_reservation_p (test_state, NTH_UNIT (group, first)))
7697         break;
7698     }
7699
7700   /* If all the instructions issued in ascending order, we're done.  */
7701   if (first == packet_group->num_insns)
7702     return;
7703
7704   /* Add nops to the end of sorted[] and try each permutation until
7705      we find one that works.  */
7706   for (nop = 0; nop < frv_num_nops; nop++)
7707     {
7708       max_unit = frv_insn_unit (frv_nops[nop]);
7709       if (frv_unit_groups[max_unit] == group)
7710         {
7711           packet_group->nop = frv_nops[nop];
7712           num_slots = UNIT_NUMBER (max_unit) + 1;
7713           for (i = packet_group->num_insns; i < num_slots; i++)
7714             packet_group->sorted[i] = frv_nops[nop];
7715           if (frv_sort_insn_group_1 (group, first, num_slots,
7716                                      (1 << first) - 1, num_slots, state))
7717             return;
7718         }
7719     }
7720   gcc_unreachable ();
7721 }
7722 \f
7723 /* Sort the current packet into assembly-language order.  Set packing
7724    flags as appropriate.  */
7725
7726 static void
7727 frv_reorder_packet (void)
7728 {
7729   unsigned int cursor[NUM_GROUPS];
7730   rtx insns[ARRAY_SIZE (frv_unit_groups)];
7731   unsigned int unit, to, from;
7732   enum frv_insn_group group;
7733   struct frv_packet_group *packet_group;
7734
7735   /* First sort each group individually.  */
7736   for (group = GROUP_I; group < NUM_GROUPS;
7737        group = (enum frv_insn_group) (group + 1))
7738     {
7739       cursor[group] = 0;
7740       frv_sort_insn_group (group);
7741     }
7742
7743   /* Go through the unit template and try add an instruction from
7744      that unit's group.  */
7745   to = 0;
7746   for (unit = 0; unit < ARRAY_SIZE (frv_unit_groups); unit++)
7747     {
7748       group = frv_unit_groups[unit];
7749       packet_group = &frv_packet.groups[group];
7750       if (cursor[group] < packet_group->num_insns)
7751         {
7752           /* frv_reorg should have added nops for us.  */
7753           gcc_assert (packet_group->sorted[cursor[group]]
7754                       != packet_group->nop);
7755           insns[to++] = packet_group->sorted[cursor[group]++];
7756         }
7757     }
7758
7759   gcc_assert (to == frv_packet.num_insns);
7760
7761   /* Clear the last instruction's packing flag, thus marking the end of
7762      a packet.  Reorder the other instructions relative to it.  */
7763   CLEAR_PACKING_FLAG (insns[to - 1]);
7764   for (from = 0; from < to - 1; from++)
7765     {
7766       remove_insn (insns[from]);
7767       add_insn_before (insns[from], insns[to - 1], NULL);
7768       SET_PACKING_FLAG (insns[from]);
7769     }
7770 }
7771
7772
7773 /* Divide instructions into packets.  Reorder the contents of each
7774    packet so that they are in the correct assembly-language order.
7775
7776    Since this pass can change the raw meaning of the rtl stream, it must
7777    only be called at the last minute, just before the instructions are
7778    written out.  */
7779
7780 static void
7781 frv_pack_insns (void)
7782 {
7783   if (frv_for_each_packet (frv_reorder_packet))
7784     frv_insn_packing_flag = 0;
7785   else
7786     frv_insn_packing_flag = -1;
7787 }
7788 \f
7789 /* See whether we need to add nops to group GROUP in order to
7790    make a valid packet.  */
7791
7792 static void
7793 frv_fill_unused_units (enum frv_insn_group group)
7794 {
7795   unsigned int non_nops, nops, i;
7796   struct frv_packet_group *packet_group;
7797
7798   packet_group = &frv_packet.groups[group];
7799
7800   /* Sort the instructions into assembly-language order.
7801      Use nops to fill slots that are otherwise unused.  */
7802   frv_sort_insn_group (group);
7803
7804   /* See how many nops are needed before the final useful instruction.  */
7805   i = nops = 0;
7806   for (non_nops = 0; non_nops < packet_group->num_insns; non_nops++)
7807     while (packet_group->sorted[i++] == packet_group->nop)
7808       nops++;
7809
7810   /* Insert that many nops into the instruction stream.  */
7811   while (nops-- > 0)
7812     frv_insert_nop_in_packet (packet_group->nop);
7813 }
7814
7815 /* Return true if accesses IO1 and IO2 refer to the same doubleword.  */
7816
7817 static bool
7818 frv_same_doubleword_p (const struct frv_io *io1, const struct frv_io *io2)
7819 {
7820   if (io1->const_address != 0 && io2->const_address != 0)
7821     return io1->const_address == io2->const_address;
7822
7823   if (io1->var_address != 0 && io2->var_address != 0)
7824     return rtx_equal_p (io1->var_address, io2->var_address);
7825
7826   return false;
7827 }
7828
7829 /* Return true if operations IO1 and IO2 are guaranteed to complete
7830    in order.  */
7831
7832 static bool
7833 frv_io_fixed_order_p (const struct frv_io *io1, const struct frv_io *io2)
7834 {
7835   /* The order of writes is always preserved.  */
7836   if (io1->type == FRV_IO_WRITE && io2->type == FRV_IO_WRITE)
7837     return true;
7838
7839   /* The order of reads isn't preserved.  */
7840   if (io1->type != FRV_IO_WRITE && io2->type != FRV_IO_WRITE)
7841     return false;
7842
7843   /* One operation is a write and the other is (or could be) a read.
7844      The order is only guaranteed if the accesses are to the same
7845      doubleword.  */
7846   return frv_same_doubleword_p (io1, io2);
7847 }
7848
7849 /* Generalize I/O operation X so that it covers both X and Y. */
7850
7851 static void
7852 frv_io_union (struct frv_io *x, const struct frv_io *y)
7853 {
7854   if (x->type != y->type)
7855     x->type = FRV_IO_UNKNOWN;
7856   if (!frv_same_doubleword_p (x, y))
7857     {
7858       x->const_address = 0;
7859       x->var_address = 0;
7860     }
7861 }
7862
7863 /* Fill IO with information about the load or store associated with
7864    membar instruction INSN.  */
7865
7866 static void
7867 frv_extract_membar (struct frv_io *io, rtx insn)
7868 {
7869   extract_insn (insn);
7870   io->type = (enum frv_io_type) INTVAL (recog_data.operand[2]);
7871   io->const_address = INTVAL (recog_data.operand[1]);
7872   io->var_address = XEXP (recog_data.operand[0], 0);
7873 }
7874
7875 /* A note_stores callback for which DATA points to an rtx.  Nullify *DATA
7876    if X is a register and *DATA depends on X.  */
7877
7878 static void
7879 frv_io_check_address (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
7880 {
7881   rtx *other = (rtx *) data;
7882
7883   if (REG_P (x) && *other != 0 && reg_overlap_mentioned_p (x, *other))
7884     *other = 0;
7885 }
7886
7887 /* A note_stores callback for which DATA points to a HARD_REG_SET.
7888    Remove every modified register from the set.  */
7889
7890 static void
7891 frv_io_handle_set (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
7892 {
7893   HARD_REG_SET *set = (HARD_REG_SET *) data;
7894   unsigned int regno;
7895
7896   if (REG_P (x))
7897     FOR_EACH_REGNO (regno, x)
7898       CLEAR_HARD_REG_BIT (*set, regno);
7899 }
7900
7901 /* A for_each_rtx callback for which DATA points to a HARD_REG_SET.
7902    Add every register in *X to the set.  */
7903
7904 static int
7905 frv_io_handle_use_1 (rtx *x, void *data)
7906 {
7907   HARD_REG_SET *set = (HARD_REG_SET *) data;
7908   unsigned int regno;
7909
7910   if (REG_P (*x))
7911     FOR_EACH_REGNO (regno, *x)
7912       SET_HARD_REG_BIT (*set, regno);
7913
7914   return 0;
7915 }
7916
7917 /* A note_stores callback that applies frv_io_handle_use_1 to an
7918    entire rhs value.  */
7919
7920 static void
7921 frv_io_handle_use (rtx *x, void *data)
7922 {
7923   for_each_rtx (x, frv_io_handle_use_1, data);
7924 }
7925
7926 /* Go through block BB looking for membars to remove.  There are two
7927    cases where intra-block analysis is enough:
7928
7929    - a membar is redundant if it occurs between two consecutive I/O
7930    operations and if those operations are guaranteed to complete
7931    in order.
7932
7933    - a membar for a __builtin_read is redundant if the result is
7934    used before the next I/O operation is issued.
7935
7936    If the last membar in the block could not be removed, and there
7937    are guaranteed to be no I/O operations between that membar and
7938    the end of the block, store the membar in *LAST_MEMBAR, otherwise
7939    store null.
7940
7941    Describe the block's first I/O operation in *NEXT_IO.  Describe
7942    an unknown operation if the block doesn't do any I/O.  */
7943
7944 static void
7945 frv_optimize_membar_local (basic_block bb, struct frv_io *next_io,
7946                            rtx *last_membar)
7947 {
7948   HARD_REG_SET used_regs;
7949   rtx next_membar, set, insn;
7950   bool next_is_end_p;
7951
7952   /* NEXT_IO is the next I/O operation to be performed after the current
7953      instruction.  It starts off as being an unknown operation.  */
7954   memset (next_io, 0, sizeof (*next_io));
7955
7956   /* NEXT_IS_END_P is true if NEXT_IO describes the end of the block.  */
7957   next_is_end_p = true;
7958
7959   /* If the current instruction is a __builtin_read or __builtin_write,
7960      NEXT_MEMBAR is the membar instruction associated with it.  NEXT_MEMBAR
7961      is null if the membar has already been deleted.
7962
7963      Note that the initialization here should only be needed to
7964      suppress warnings.  */
7965   next_membar = 0;
7966
7967   /* USED_REGS is the set of registers that are used before the
7968      next I/O instruction.  */
7969   CLEAR_HARD_REG_SET (used_regs);
7970
7971   for (insn = BB_END (bb); insn != BB_HEAD (bb); insn = PREV_INSN (insn))
7972     if (GET_CODE (insn) == CALL_INSN)
7973       {
7974         /* We can't predict what a call will do to volatile memory.  */
7975         memset (next_io, 0, sizeof (struct frv_io));
7976         next_is_end_p = false;
7977         CLEAR_HARD_REG_SET (used_regs);
7978       }
7979     else if (INSN_P (insn))
7980       switch (recog_memoized (insn))
7981         {
7982         case CODE_FOR_optional_membar_qi:
7983         case CODE_FOR_optional_membar_hi:
7984         case CODE_FOR_optional_membar_si:
7985         case CODE_FOR_optional_membar_di:
7986           next_membar = insn;
7987           if (next_is_end_p)
7988             {
7989               /* Local information isn't enough to decide whether this
7990                  membar is needed.  Stash it away for later.  */
7991               *last_membar = insn;
7992               frv_extract_membar (next_io, insn);
7993               next_is_end_p = false;
7994             }
7995           else
7996             {
7997               /* Check whether the I/O operation before INSN could be
7998                  reordered with one described by NEXT_IO.  If it can't,
7999                  INSN will not be needed.  */
8000               struct frv_io prev_io;
8001
8002               frv_extract_membar (&prev_io, insn);
8003               if (frv_io_fixed_order_p (&prev_io, next_io))
8004                 {
8005                   if (dump_file)
8006                     fprintf (dump_file,
8007                              ";; [Local] Removing membar %d since order"
8008                              " of accesses is guaranteed\n",
8009                              INSN_UID (next_membar));
8010
8011                   insn = NEXT_INSN (insn);
8012                   delete_insn (next_membar);
8013                   next_membar = 0;
8014                 }
8015               *next_io = prev_io;
8016             }
8017           break;
8018
8019         default:
8020           /* Invalidate NEXT_IO's address if it depends on something that
8021              is clobbered by INSN.  */
8022           if (next_io->var_address)
8023             note_stores (PATTERN (insn), frv_io_check_address,
8024                          &next_io->var_address);
8025
8026           /* If the next membar is associated with a __builtin_read,
8027              see if INSN reads from that address.  If it does, and if
8028              the destination register is used before the next I/O access,
8029              there is no need for the membar.  */
8030           set = PATTERN (insn);
8031           if (next_io->type == FRV_IO_READ
8032               && next_io->var_address != 0
8033               && next_membar != 0
8034               && GET_CODE (set) == SET
8035               && GET_CODE (SET_DEST (set)) == REG
8036               && TEST_HARD_REG_BIT (used_regs, REGNO (SET_DEST (set))))
8037             {
8038               rtx src;
8039
8040               src = SET_SRC (set);
8041               if (GET_CODE (src) == ZERO_EXTEND)
8042                 src = XEXP (src, 0);
8043
8044               if (GET_CODE (src) == MEM
8045                   && rtx_equal_p (XEXP (src, 0), next_io->var_address))
8046                 {
8047                   if (dump_file)
8048                     fprintf (dump_file,
8049                              ";; [Local] Removing membar %d since the target"
8050                              " of %d is used before the I/O operation\n",
8051                              INSN_UID (next_membar), INSN_UID (insn));
8052
8053                   if (next_membar == *last_membar)
8054                     *last_membar = 0;
8055
8056                   delete_insn (next_membar);
8057                   next_membar = 0;
8058                 }
8059             }
8060
8061           /* If INSN has volatile references, forget about any registers
8062              that are used after it.  Otherwise forget about uses that
8063              are (or might be) defined by INSN.  */
8064           if (volatile_refs_p (PATTERN (insn)))
8065             CLEAR_HARD_REG_SET (used_regs);
8066           else
8067             note_stores (PATTERN (insn), frv_io_handle_set, &used_regs);
8068
8069           note_uses (&PATTERN (insn), frv_io_handle_use, &used_regs);
8070           break;
8071         }
8072 }
8073
8074 /* See if MEMBAR, the last membar instruction in BB, can be removed.
8075    FIRST_IO[X] describes the first operation performed by basic block X.  */
8076
8077 static void
8078 frv_optimize_membar_global (basic_block bb, struct frv_io *first_io,
8079                             rtx membar)
8080 {
8081   struct frv_io this_io, next_io;
8082   edge succ;
8083   edge_iterator ei;
8084
8085   /* We need to keep the membar if there is an edge to the exit block.  */
8086   FOR_EACH_EDGE (succ, ei, bb->succs)
8087   /* for (succ = bb->succ; succ != 0; succ = succ->succ_next) */
8088     if (succ->dest == EXIT_BLOCK_PTR)
8089       return;
8090
8091   /* Work out the union of all successor blocks.  */
8092   ei = ei_start (bb->succs);
8093   ei_cond (ei, &succ);
8094   /* next_io = first_io[bb->succ->dest->index]; */
8095   next_io = first_io[succ->dest->index];
8096   ei = ei_start (bb->succs);
8097   if (ei_cond (ei, &succ))
8098     {
8099       for (ei_next (&ei); ei_cond (ei, &succ); ei_next (&ei))
8100         /*for (succ = bb->succ->succ_next; succ != 0; succ = succ->succ_next)*/
8101         frv_io_union (&next_io, &first_io[succ->dest->index]);
8102     }
8103   else
8104     gcc_unreachable ();
8105
8106   frv_extract_membar (&this_io, membar);
8107   if (frv_io_fixed_order_p (&this_io, &next_io))
8108     {
8109       if (dump_file)
8110         fprintf (dump_file,
8111                  ";; [Global] Removing membar %d since order of accesses"
8112                  " is guaranteed\n", INSN_UID (membar));
8113
8114       delete_insn (membar);
8115     }
8116 }
8117
8118 /* Remove redundant membars from the current function.  */
8119
8120 static void
8121 frv_optimize_membar (void)
8122 {
8123   basic_block bb;
8124   struct frv_io *first_io;
8125   rtx *last_membar;
8126
8127   compute_bb_for_insn ();
8128   first_io = XCNEWVEC (struct frv_io, last_basic_block);
8129   last_membar = XCNEWVEC (rtx, last_basic_block);
8130
8131   FOR_EACH_BB (bb)
8132     frv_optimize_membar_local (bb, &first_io[bb->index],
8133                                &last_membar[bb->index]);
8134
8135   FOR_EACH_BB (bb)
8136     if (last_membar[bb->index] != 0)
8137       frv_optimize_membar_global (bb, first_io, last_membar[bb->index]);
8138
8139   free (first_io);
8140   free (last_membar);
8141 }
8142 \f
8143 /* Used by frv_reorg to keep track of the current packet's address.  */
8144 static unsigned int frv_packet_address;
8145
8146 /* If the current packet falls through to a label, try to pad the packet
8147    with nops in order to fit the label's alignment requirements.  */
8148
8149 static void
8150 frv_align_label (void)
8151 {
8152   unsigned int alignment, target, nop;
8153   rtx x, last, barrier, label;
8154
8155   /* Walk forward to the start of the next packet.  Set ALIGNMENT to the
8156      maximum alignment of that packet, LABEL to the last label between
8157      the packets, and BARRIER to the last barrier.  */
8158   last = frv_packet.insns[frv_packet.num_insns - 1];
8159   label = barrier = 0;
8160   alignment = 4;
8161   for (x = NEXT_INSN (last); x != 0 && !INSN_P (x); x = NEXT_INSN (x))
8162     {
8163       if (LABEL_P (x))
8164         {
8165           unsigned int subalign = 1 << label_to_alignment (x);
8166           alignment = MAX (alignment, subalign);
8167           label = x;
8168         }
8169       if (BARRIER_P (x))
8170         barrier = x;
8171     }
8172
8173   /* If -malign-labels, and the packet falls through to an unaligned
8174      label, try introducing a nop to align that label to 8 bytes.  */
8175   if (TARGET_ALIGN_LABELS
8176       && label != 0
8177       && barrier == 0
8178       && frv_packet.num_insns < frv_packet.issue_rate)
8179     alignment = MAX (alignment, 8);
8180
8181   /* Advance the address to the end of the current packet.  */
8182   frv_packet_address += frv_packet.num_insns * 4;
8183
8184   /* Work out the target address, after alignment.  */
8185   target = (frv_packet_address + alignment - 1) & -alignment;
8186
8187   /* If the packet falls through to the label, try to find an efficient
8188      padding sequence.  */
8189   if (barrier == 0)
8190     {
8191       /* First try adding nops to the current packet.  */
8192       for (nop = 0; nop < frv_num_nops; nop++)
8193         while (frv_packet_address < target && frv_pack_insn_p (frv_nops[nop]))
8194           {
8195             frv_insert_nop_in_packet (frv_nops[nop]);
8196             frv_packet_address += 4;
8197           }
8198
8199       /* If we still haven't reached the target, add some new packets that
8200          contain only nops.  If there are two types of nop, insert an
8201          alternating sequence of frv_nops[0] and frv_nops[1], which will
8202          lead to packets like:
8203
8204                 nop.p
8205                 mnop.p/fnop.p
8206                 nop.p
8207                 mnop/fnop
8208
8209          etc.  Just emit frv_nops[0] if that's the only nop we have.  */
8210       last = frv_packet.insns[frv_packet.num_insns - 1];
8211       nop = 0;
8212       while (frv_packet_address < target)
8213         {
8214           last = emit_insn_after (PATTERN (frv_nops[nop]), last);
8215           frv_packet_address += 4;
8216           if (frv_num_nops > 1)
8217             nop ^= 1;
8218         }
8219     }
8220
8221   frv_packet_address = target;
8222 }
8223
8224 /* Subroutine of frv_reorg, called after each packet has been constructed
8225    in frv_packet.  */
8226
8227 static void
8228 frv_reorg_packet (void)
8229 {
8230   frv_fill_unused_units (GROUP_I);
8231   frv_fill_unused_units (GROUP_FM);
8232   frv_align_label ();
8233 }
8234
8235 /* Add an instruction with pattern NOP to frv_nops[].  */
8236
8237 static void
8238 frv_register_nop (rtx nop)
8239 {
8240   nop = make_insn_raw (nop);
8241   NEXT_INSN (nop) = 0;
8242   PREV_INSN (nop) = 0;
8243   frv_nops[frv_num_nops++] = nop;
8244 }
8245
8246 /* Implement TARGET_MACHINE_DEPENDENT_REORG.  Divide the instructions
8247    into packets and check whether we need to insert nops in order to
8248    fulfill the processor's issue requirements.  Also, if the user has
8249    requested a certain alignment for a label, try to meet that alignment
8250    by inserting nops in the previous packet.  */
8251
8252 static void
8253 frv_reorg (void)
8254 {
8255   if (optimize > 0 && TARGET_OPTIMIZE_MEMBAR && cfun->machine->has_membar_p)
8256     frv_optimize_membar ();
8257
8258   frv_num_nops = 0;
8259   frv_register_nop (gen_nop ());
8260   if (TARGET_MEDIA)
8261     frv_register_nop (gen_mnop ());
8262   if (TARGET_HARD_FLOAT)
8263     frv_register_nop (gen_fnop ());
8264
8265   /* Estimate the length of each branch.  Although this may change after
8266      we've inserted nops, it will only do so in big functions.  */
8267   shorten_branches (get_insns ());
8268
8269   frv_packet_address = 0;
8270   frv_for_each_packet (frv_reorg_packet);
8271 }
8272 \f
8273 #define def_builtin(name, type, code) \
8274   add_builtin_function ((name), (type), (code), BUILT_IN_MD, NULL, NULL)
8275
8276 struct builtin_description
8277 {
8278   enum insn_code icode;
8279   const char *name;
8280   enum frv_builtins code;
8281   enum rtx_code comparison;
8282   unsigned int flag;
8283 };
8284
8285 /* Media intrinsics that take a single, constant argument.  */
8286
8287 static struct builtin_description bdesc_set[] =
8288 {
8289   { CODE_FOR_mhdsets, "__MHDSETS", FRV_BUILTIN_MHDSETS, UNKNOWN, 0 }
8290 };
8291
8292 /* Media intrinsics that take just one argument.  */
8293
8294 static struct builtin_description bdesc_1arg[] =
8295 {
8296   { CODE_FOR_mnot, "__MNOT", FRV_BUILTIN_MNOT, UNKNOWN, 0 },
8297   { CODE_FOR_munpackh, "__MUNPACKH", FRV_BUILTIN_MUNPACKH, UNKNOWN, 0 },
8298   { CODE_FOR_mbtoh, "__MBTOH", FRV_BUILTIN_MBTOH, UNKNOWN, 0 },
8299   { CODE_FOR_mhtob, "__MHTOB", FRV_BUILTIN_MHTOB, UNKNOWN, 0},
8300   { CODE_FOR_mabshs, "__MABSHS", FRV_BUILTIN_MABSHS, UNKNOWN, 0 },
8301   { CODE_FOR_scutss, "__SCUTSS", FRV_BUILTIN_SCUTSS, UNKNOWN, 0 }
8302 };
8303
8304 /* Media intrinsics that take two arguments.  */
8305
8306 static struct builtin_description bdesc_2arg[] =
8307 {
8308   { CODE_FOR_mand, "__MAND", FRV_BUILTIN_MAND, UNKNOWN, 0},
8309   { CODE_FOR_mor, "__MOR", FRV_BUILTIN_MOR, UNKNOWN, 0},
8310   { CODE_FOR_mxor, "__MXOR", FRV_BUILTIN_MXOR, UNKNOWN, 0},
8311   { CODE_FOR_maveh, "__MAVEH", FRV_BUILTIN_MAVEH, UNKNOWN, 0},
8312   { CODE_FOR_msaths, "__MSATHS", FRV_BUILTIN_MSATHS, UNKNOWN, 0},
8313   { CODE_FOR_msathu, "__MSATHU", FRV_BUILTIN_MSATHU, UNKNOWN, 0},
8314   { CODE_FOR_maddhss, "__MADDHSS", FRV_BUILTIN_MADDHSS, UNKNOWN, 0},
8315   { CODE_FOR_maddhus, "__MADDHUS", FRV_BUILTIN_MADDHUS, UNKNOWN, 0},
8316   { CODE_FOR_msubhss, "__MSUBHSS", FRV_BUILTIN_MSUBHSS, UNKNOWN, 0},
8317   { CODE_FOR_msubhus, "__MSUBHUS", FRV_BUILTIN_MSUBHUS, UNKNOWN, 0},
8318   { CODE_FOR_mqaddhss, "__MQADDHSS", FRV_BUILTIN_MQADDHSS, UNKNOWN, 0},
8319   { CODE_FOR_mqaddhus, "__MQADDHUS", FRV_BUILTIN_MQADDHUS, UNKNOWN, 0},
8320   { CODE_FOR_mqsubhss, "__MQSUBHSS", FRV_BUILTIN_MQSUBHSS, UNKNOWN, 0},
8321   { CODE_FOR_mqsubhus, "__MQSUBHUS", FRV_BUILTIN_MQSUBHUS, UNKNOWN, 0},
8322   { CODE_FOR_mpackh, "__MPACKH", FRV_BUILTIN_MPACKH, UNKNOWN, 0},
8323   { CODE_FOR_mcop1, "__Mcop1", FRV_BUILTIN_MCOP1, UNKNOWN, 0},
8324   { CODE_FOR_mcop2, "__Mcop2", FRV_BUILTIN_MCOP2, UNKNOWN, 0},
8325   { CODE_FOR_mwcut, "__MWCUT", FRV_BUILTIN_MWCUT, UNKNOWN, 0},
8326   { CODE_FOR_mqsaths, "__MQSATHS", FRV_BUILTIN_MQSATHS, UNKNOWN, 0},
8327   { CODE_FOR_mqlclrhs, "__MQLCLRHS", FRV_BUILTIN_MQLCLRHS, UNKNOWN, 0},
8328   { CODE_FOR_mqlmths, "__MQLMTHS", FRV_BUILTIN_MQLMTHS, UNKNOWN, 0},
8329   { CODE_FOR_smul, "__SMUL", FRV_BUILTIN_SMUL, UNKNOWN, 0},
8330   { CODE_FOR_umul, "__UMUL", FRV_BUILTIN_UMUL, UNKNOWN, 0},
8331   { CODE_FOR_addss, "__ADDSS", FRV_BUILTIN_ADDSS, UNKNOWN, 0},
8332   { CODE_FOR_subss, "__SUBSS", FRV_BUILTIN_SUBSS, UNKNOWN, 0},
8333   { CODE_FOR_slass, "__SLASS", FRV_BUILTIN_SLASS, UNKNOWN, 0},
8334   { CODE_FOR_scan, "__SCAN", FRV_BUILTIN_SCAN, UNKNOWN, 0}
8335 };
8336
8337 /* Integer intrinsics that take two arguments and have no return value.  */
8338
8339 static struct builtin_description bdesc_int_void2arg[] =
8340 {
8341   { CODE_FOR_smass, "__SMASS", FRV_BUILTIN_SMASS, UNKNOWN, 0},
8342   { CODE_FOR_smsss, "__SMSSS", FRV_BUILTIN_SMSSS, UNKNOWN, 0},
8343   { CODE_FOR_smu, "__SMU", FRV_BUILTIN_SMU, UNKNOWN, 0}
8344 };
8345
8346 static struct builtin_description bdesc_prefetches[] =
8347 {
8348   { CODE_FOR_frv_prefetch0, "__data_prefetch0", FRV_BUILTIN_PREFETCH0, UNKNOWN,
8349     0},
8350   { CODE_FOR_frv_prefetch, "__data_prefetch", FRV_BUILTIN_PREFETCH, UNKNOWN, 0}
8351 };
8352
8353 /* Media intrinsics that take two arguments, the first being an ACC number.  */
8354
8355 static struct builtin_description bdesc_cut[] =
8356 {
8357   { CODE_FOR_mcut, "__MCUT", FRV_BUILTIN_MCUT, UNKNOWN, 0},
8358   { CODE_FOR_mcutss, "__MCUTSS", FRV_BUILTIN_MCUTSS, UNKNOWN, 0},
8359   { CODE_FOR_mdcutssi, "__MDCUTSSI", FRV_BUILTIN_MDCUTSSI, UNKNOWN, 0}
8360 };
8361
8362 /* Two-argument media intrinsics with an immediate second argument.  */
8363
8364 static struct builtin_description bdesc_2argimm[] =
8365 {
8366   { CODE_FOR_mrotli, "__MROTLI", FRV_BUILTIN_MROTLI, UNKNOWN, 0},
8367   { CODE_FOR_mrotri, "__MROTRI", FRV_BUILTIN_MROTRI, UNKNOWN, 0},
8368   { CODE_FOR_msllhi, "__MSLLHI", FRV_BUILTIN_MSLLHI, UNKNOWN, 0},
8369   { CODE_FOR_msrlhi, "__MSRLHI", FRV_BUILTIN_MSRLHI, UNKNOWN, 0},
8370   { CODE_FOR_msrahi, "__MSRAHI", FRV_BUILTIN_MSRAHI, UNKNOWN, 0},
8371   { CODE_FOR_mexpdhw, "__MEXPDHW", FRV_BUILTIN_MEXPDHW, UNKNOWN, 0},
8372   { CODE_FOR_mexpdhd, "__MEXPDHD", FRV_BUILTIN_MEXPDHD, UNKNOWN, 0},
8373   { CODE_FOR_mdrotli, "__MDROTLI", FRV_BUILTIN_MDROTLI, UNKNOWN, 0},
8374   { CODE_FOR_mcplhi, "__MCPLHI", FRV_BUILTIN_MCPLHI, UNKNOWN, 0},
8375   { CODE_FOR_mcpli, "__MCPLI", FRV_BUILTIN_MCPLI, UNKNOWN, 0},
8376   { CODE_FOR_mhsetlos, "__MHSETLOS", FRV_BUILTIN_MHSETLOS, UNKNOWN, 0},
8377   { CODE_FOR_mhsetloh, "__MHSETLOH", FRV_BUILTIN_MHSETLOH, UNKNOWN, 0},
8378   { CODE_FOR_mhsethis, "__MHSETHIS", FRV_BUILTIN_MHSETHIS, UNKNOWN, 0},
8379   { CODE_FOR_mhsethih, "__MHSETHIH", FRV_BUILTIN_MHSETHIH, UNKNOWN, 0},
8380   { CODE_FOR_mhdseth, "__MHDSETH", FRV_BUILTIN_MHDSETH, UNKNOWN, 0},
8381   { CODE_FOR_mqsllhi, "__MQSLLHI", FRV_BUILTIN_MQSLLHI, UNKNOWN, 0},
8382   { CODE_FOR_mqsrahi, "__MQSRAHI", FRV_BUILTIN_MQSRAHI, UNKNOWN, 0}
8383 };
8384
8385 /* Media intrinsics that take two arguments and return void, the first argument
8386    being a pointer to 4 words in memory.  */
8387
8388 static struct builtin_description bdesc_void2arg[] =
8389 {
8390   { CODE_FOR_mdunpackh, "__MDUNPACKH", FRV_BUILTIN_MDUNPACKH, UNKNOWN, 0},
8391   { CODE_FOR_mbtohe, "__MBTOHE", FRV_BUILTIN_MBTOHE, UNKNOWN, 0},
8392 };
8393
8394 /* Media intrinsics that take three arguments, the first being a const_int that
8395    denotes an accumulator, and that return void.  */
8396
8397 static struct builtin_description bdesc_void3arg[] =
8398 {
8399   { CODE_FOR_mcpxrs, "__MCPXRS", FRV_BUILTIN_MCPXRS, UNKNOWN, 0},
8400   { CODE_FOR_mcpxru, "__MCPXRU", FRV_BUILTIN_MCPXRU, UNKNOWN, 0},
8401   { CODE_FOR_mcpxis, "__MCPXIS", FRV_BUILTIN_MCPXIS, UNKNOWN, 0},
8402   { CODE_FOR_mcpxiu, "__MCPXIU", FRV_BUILTIN_MCPXIU, UNKNOWN, 0},
8403   { CODE_FOR_mmulhs, "__MMULHS", FRV_BUILTIN_MMULHS, UNKNOWN, 0},
8404   { CODE_FOR_mmulhu, "__MMULHU", FRV_BUILTIN_MMULHU, UNKNOWN, 0},
8405   { CODE_FOR_mmulxhs, "__MMULXHS", FRV_BUILTIN_MMULXHS, UNKNOWN, 0},
8406   { CODE_FOR_mmulxhu, "__MMULXHU", FRV_BUILTIN_MMULXHU, UNKNOWN, 0},
8407   { CODE_FOR_mmachs, "__MMACHS", FRV_BUILTIN_MMACHS, UNKNOWN, 0},
8408   { CODE_FOR_mmachu, "__MMACHU", FRV_BUILTIN_MMACHU, UNKNOWN, 0},
8409   { CODE_FOR_mmrdhs, "__MMRDHS", FRV_BUILTIN_MMRDHS, UNKNOWN, 0},
8410   { CODE_FOR_mmrdhu, "__MMRDHU", FRV_BUILTIN_MMRDHU, UNKNOWN, 0},
8411   { CODE_FOR_mqcpxrs, "__MQCPXRS", FRV_BUILTIN_MQCPXRS, UNKNOWN, 0},
8412   { CODE_FOR_mqcpxru, "__MQCPXRU", FRV_BUILTIN_MQCPXRU, UNKNOWN, 0},
8413   { CODE_FOR_mqcpxis, "__MQCPXIS", FRV_BUILTIN_MQCPXIS, UNKNOWN, 0},
8414   { CODE_FOR_mqcpxiu, "__MQCPXIU", FRV_BUILTIN_MQCPXIU, UNKNOWN, 0},
8415   { CODE_FOR_mqmulhs, "__MQMULHS", FRV_BUILTIN_MQMULHS, UNKNOWN, 0},
8416   { CODE_FOR_mqmulhu, "__MQMULHU", FRV_BUILTIN_MQMULHU, UNKNOWN, 0},
8417   { CODE_FOR_mqmulxhs, "__MQMULXHS", FRV_BUILTIN_MQMULXHS, UNKNOWN, 0},
8418   { CODE_FOR_mqmulxhu, "__MQMULXHU", FRV_BUILTIN_MQMULXHU, UNKNOWN, 0},
8419   { CODE_FOR_mqmachs, "__MQMACHS", FRV_BUILTIN_MQMACHS, UNKNOWN, 0},
8420   { CODE_FOR_mqmachu, "__MQMACHU", FRV_BUILTIN_MQMACHU, UNKNOWN, 0},
8421   { CODE_FOR_mqxmachs, "__MQXMACHS", FRV_BUILTIN_MQXMACHS, UNKNOWN, 0},
8422   { CODE_FOR_mqxmacxhs, "__MQXMACXHS", FRV_BUILTIN_MQXMACXHS, UNKNOWN, 0},
8423   { CODE_FOR_mqmacxhs, "__MQMACXHS", FRV_BUILTIN_MQMACXHS, UNKNOWN, 0}
8424 };
8425
8426 /* Media intrinsics that take two accumulator numbers as argument and
8427    return void.  */
8428
8429 static struct builtin_description bdesc_voidacc[] =
8430 {
8431   { CODE_FOR_maddaccs, "__MADDACCS", FRV_BUILTIN_MADDACCS, UNKNOWN, 0},
8432   { CODE_FOR_msubaccs, "__MSUBACCS", FRV_BUILTIN_MSUBACCS, UNKNOWN, 0},
8433   { CODE_FOR_masaccs, "__MASACCS", FRV_BUILTIN_MASACCS, UNKNOWN, 0},
8434   { CODE_FOR_mdaddaccs, "__MDADDACCS", FRV_BUILTIN_MDADDACCS, UNKNOWN, 0},
8435   { CODE_FOR_mdsubaccs, "__MDSUBACCS", FRV_BUILTIN_MDSUBACCS, UNKNOWN, 0},
8436   { CODE_FOR_mdasaccs, "__MDASACCS", FRV_BUILTIN_MDASACCS, UNKNOWN, 0}
8437 };
8438
8439 /* Intrinsics that load a value and then issue a MEMBAR.  The load is
8440    a normal move and the ICODE is for the membar.  */
8441
8442 static struct builtin_description bdesc_loads[] =
8443 {
8444   { CODE_FOR_optional_membar_qi, "__builtin_read8",
8445     FRV_BUILTIN_READ8, UNKNOWN, 0},
8446   { CODE_FOR_optional_membar_hi, "__builtin_read16",
8447     FRV_BUILTIN_READ16, UNKNOWN, 0},
8448   { CODE_FOR_optional_membar_si, "__builtin_read32",
8449     FRV_BUILTIN_READ32, UNKNOWN, 0},
8450   { CODE_FOR_optional_membar_di, "__builtin_read64",
8451     FRV_BUILTIN_READ64, UNKNOWN, 0}
8452 };
8453
8454 /* Likewise stores.  */
8455
8456 static struct builtin_description bdesc_stores[] =
8457 {
8458   { CODE_FOR_optional_membar_qi, "__builtin_write8",
8459     FRV_BUILTIN_WRITE8, UNKNOWN, 0},
8460   { CODE_FOR_optional_membar_hi, "__builtin_write16",
8461     FRV_BUILTIN_WRITE16, UNKNOWN, 0},
8462   { CODE_FOR_optional_membar_si, "__builtin_write32",
8463     FRV_BUILTIN_WRITE32, UNKNOWN, 0},
8464   { CODE_FOR_optional_membar_di, "__builtin_write64",
8465     FRV_BUILTIN_WRITE64, UNKNOWN, 0},
8466 };
8467
8468 /* Initialize media builtins.  */
8469
8470 static void
8471 frv_init_builtins (void)
8472 {
8473   tree endlink = void_list_node;
8474   tree accumulator = integer_type_node;
8475   tree integer = integer_type_node;
8476   tree voidt = void_type_node;
8477   tree uhalf = short_unsigned_type_node;
8478   tree sword1 = long_integer_type_node;
8479   tree uword1 = long_unsigned_type_node;
8480   tree sword2 = long_long_integer_type_node;
8481   tree uword2 = long_long_unsigned_type_node;
8482   tree uword4 = build_pointer_type (uword1);
8483   tree vptr   = build_pointer_type (build_type_variant (void_type_node, 0, 1));
8484   tree ubyte  = unsigned_char_type_node;
8485   tree iacc   = integer_type_node;
8486
8487 #define UNARY(RET, T1) \
8488   build_function_type (RET, tree_cons (NULL_TREE, T1, endlink))
8489
8490 #define BINARY(RET, T1, T2) \
8491   build_function_type (RET, tree_cons (NULL_TREE, T1, \
8492                             tree_cons (NULL_TREE, T2, endlink)))
8493
8494 #define TRINARY(RET, T1, T2, T3) \
8495   build_function_type (RET, tree_cons (NULL_TREE, T1, \
8496                             tree_cons (NULL_TREE, T2, \
8497                             tree_cons (NULL_TREE, T3, endlink))))
8498
8499 #define QUAD(RET, T1, T2, T3, T4) \
8500   build_function_type (RET, tree_cons (NULL_TREE, T1, \
8501                             tree_cons (NULL_TREE, T2, \
8502                             tree_cons (NULL_TREE, T3, \
8503                             tree_cons (NULL_TREE, T4, endlink)))))
8504
8505   tree void_ftype_void = build_function_type (voidt, endlink);
8506
8507   tree void_ftype_acc = UNARY (voidt, accumulator);
8508   tree void_ftype_uw4_uw1 = BINARY (voidt, uword4, uword1);
8509   tree void_ftype_uw4_uw2 = BINARY (voidt, uword4, uword2);
8510   tree void_ftype_acc_uw1 = BINARY (voidt, accumulator, uword1);
8511   tree void_ftype_acc_acc = BINARY (voidt, accumulator, accumulator);
8512   tree void_ftype_acc_uw1_uw1 = TRINARY (voidt, accumulator, uword1, uword1);
8513   tree void_ftype_acc_sw1_sw1 = TRINARY (voidt, accumulator, sword1, sword1);
8514   tree void_ftype_acc_uw2_uw2 = TRINARY (voidt, accumulator, uword2, uword2);
8515   tree void_ftype_acc_sw2_sw2 = TRINARY (voidt, accumulator, sword2, sword2);
8516
8517   tree uw1_ftype_uw1 = UNARY (uword1, uword1);
8518   tree uw1_ftype_sw1 = UNARY (uword1, sword1);
8519   tree uw1_ftype_uw2 = UNARY (uword1, uword2);
8520   tree uw1_ftype_acc = UNARY (uword1, accumulator);
8521   tree uw1_ftype_uh_uh = BINARY (uword1, uhalf, uhalf);
8522   tree uw1_ftype_uw1_uw1 = BINARY (uword1, uword1, uword1);
8523   tree uw1_ftype_uw1_int = BINARY (uword1, uword1, integer);
8524   tree uw1_ftype_acc_uw1 = BINARY (uword1, accumulator, uword1);
8525   tree uw1_ftype_acc_sw1 = BINARY (uword1, accumulator, sword1);
8526   tree uw1_ftype_uw2_uw1 = BINARY (uword1, uword2, uword1);
8527   tree uw1_ftype_uw2_int = BINARY (uword1, uword2, integer);
8528
8529   tree sw1_ftype_int = UNARY (sword1, integer);
8530   tree sw1_ftype_sw1_sw1 = BINARY (sword1, sword1, sword1);
8531   tree sw1_ftype_sw1_int = BINARY (sword1, sword1, integer);
8532
8533   tree uw2_ftype_uw1 = UNARY (uword2, uword1);
8534   tree uw2_ftype_uw1_int = BINARY (uword2, uword1, integer);
8535   tree uw2_ftype_uw2_uw2 = BINARY (uword2, uword2, uword2);
8536   tree uw2_ftype_uw2_int = BINARY (uword2, uword2, integer);
8537   tree uw2_ftype_acc_int = BINARY (uword2, accumulator, integer);
8538   tree uw2_ftype_uh_uh_uh_uh = QUAD (uword2, uhalf, uhalf, uhalf, uhalf);
8539
8540   tree sw2_ftype_sw2_sw2 = BINARY (sword2, sword2, sword2);
8541   tree sw2_ftype_sw2_int   = BINARY (sword2, sword2, integer);
8542   tree uw2_ftype_uw1_uw1   = BINARY (uword2, uword1, uword1);
8543   tree sw2_ftype_sw1_sw1   = BINARY (sword2, sword1, sword1);
8544   tree void_ftype_sw1_sw1  = BINARY (voidt, sword1, sword1);
8545   tree void_ftype_iacc_sw2 = BINARY (voidt, iacc, sword2);
8546   tree void_ftype_iacc_sw1 = BINARY (voidt, iacc, sword1);
8547   tree sw1_ftype_sw1       = UNARY (sword1, sword1);
8548   tree sw2_ftype_iacc      = UNARY (sword2, iacc);
8549   tree sw1_ftype_iacc      = UNARY (sword1, iacc);
8550   tree void_ftype_ptr      = UNARY (voidt, const_ptr_type_node);
8551   tree uw1_ftype_vptr      = UNARY (uword1, vptr);
8552   tree uw2_ftype_vptr      = UNARY (uword2, vptr);
8553   tree void_ftype_vptr_ub  = BINARY (voidt, vptr, ubyte);
8554   tree void_ftype_vptr_uh  = BINARY (voidt, vptr, uhalf);
8555   tree void_ftype_vptr_uw1 = BINARY (voidt, vptr, uword1);
8556   tree void_ftype_vptr_uw2 = BINARY (voidt, vptr, uword2);
8557
8558   def_builtin ("__MAND", uw1_ftype_uw1_uw1, FRV_BUILTIN_MAND);
8559   def_builtin ("__MOR", uw1_ftype_uw1_uw1, FRV_BUILTIN_MOR);
8560   def_builtin ("__MXOR", uw1_ftype_uw1_uw1, FRV_BUILTIN_MXOR);
8561   def_builtin ("__MNOT", uw1_ftype_uw1, FRV_BUILTIN_MNOT);
8562   def_builtin ("__MROTLI", uw1_ftype_uw1_int, FRV_BUILTIN_MROTLI);
8563   def_builtin ("__MROTRI", uw1_ftype_uw1_int, FRV_BUILTIN_MROTRI);
8564   def_builtin ("__MWCUT", uw1_ftype_uw2_uw1, FRV_BUILTIN_MWCUT);
8565   def_builtin ("__MAVEH", uw1_ftype_uw1_uw1, FRV_BUILTIN_MAVEH);
8566   def_builtin ("__MSLLHI", uw1_ftype_uw1_int, FRV_BUILTIN_MSLLHI);
8567   def_builtin ("__MSRLHI", uw1_ftype_uw1_int, FRV_BUILTIN_MSRLHI);
8568   def_builtin ("__MSRAHI", sw1_ftype_sw1_int, FRV_BUILTIN_MSRAHI);
8569   def_builtin ("__MSATHS", sw1_ftype_sw1_sw1, FRV_BUILTIN_MSATHS);
8570   def_builtin ("__MSATHU", uw1_ftype_uw1_uw1, FRV_BUILTIN_MSATHU);
8571   def_builtin ("__MADDHSS", sw1_ftype_sw1_sw1, FRV_BUILTIN_MADDHSS);
8572   def_builtin ("__MADDHUS", uw1_ftype_uw1_uw1, FRV_BUILTIN_MADDHUS);
8573   def_builtin ("__MSUBHSS", sw1_ftype_sw1_sw1, FRV_BUILTIN_MSUBHSS);
8574   def_builtin ("__MSUBHUS", uw1_ftype_uw1_uw1, FRV_BUILTIN_MSUBHUS);
8575   def_builtin ("__MMULHS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MMULHS);
8576   def_builtin ("__MMULHU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MMULHU);
8577   def_builtin ("__MMULXHS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MMULXHS);
8578   def_builtin ("__MMULXHU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MMULXHU);
8579   def_builtin ("__MMACHS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MMACHS);
8580   def_builtin ("__MMACHU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MMACHU);
8581   def_builtin ("__MMRDHS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MMRDHS);
8582   def_builtin ("__MMRDHU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MMRDHU);
8583   def_builtin ("__MQADDHSS", sw2_ftype_sw2_sw2, FRV_BUILTIN_MQADDHSS);
8584   def_builtin ("__MQADDHUS", uw2_ftype_uw2_uw2, FRV_BUILTIN_MQADDHUS);
8585   def_builtin ("__MQSUBHSS", sw2_ftype_sw2_sw2, FRV_BUILTIN_MQSUBHSS);
8586   def_builtin ("__MQSUBHUS", uw2_ftype_uw2_uw2, FRV_BUILTIN_MQSUBHUS);
8587   def_builtin ("__MQMULHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQMULHS);
8588   def_builtin ("__MQMULHU", void_ftype_acc_uw2_uw2, FRV_BUILTIN_MQMULHU);
8589   def_builtin ("__MQMULXHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQMULXHS);
8590   def_builtin ("__MQMULXHU", void_ftype_acc_uw2_uw2, FRV_BUILTIN_MQMULXHU);
8591   def_builtin ("__MQMACHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQMACHS);
8592   def_builtin ("__MQMACHU", void_ftype_acc_uw2_uw2, FRV_BUILTIN_MQMACHU);
8593   def_builtin ("__MCPXRS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MCPXRS);
8594   def_builtin ("__MCPXRU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MCPXRU);
8595   def_builtin ("__MCPXIS", void_ftype_acc_sw1_sw1, FRV_BUILTIN_MCPXIS);
8596   def_builtin ("__MCPXIU", void_ftype_acc_uw1_uw1, FRV_BUILTIN_MCPXIU);
8597   def_builtin ("__MQCPXRS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQCPXRS);
8598   def_builtin ("__MQCPXRU", void_ftype_acc_uw2_uw2, FRV_BUILTIN_MQCPXRU);
8599   def_builtin ("__MQCPXIS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQCPXIS);
8600   def_builtin ("__MQCPXIU", void_ftype_acc_uw2_uw2, FRV_BUILTIN_MQCPXIU);
8601   def_builtin ("__MCUT", uw1_ftype_acc_uw1, FRV_BUILTIN_MCUT);
8602   def_builtin ("__MCUTSS", uw1_ftype_acc_sw1, FRV_BUILTIN_MCUTSS);
8603   def_builtin ("__MEXPDHW", uw1_ftype_uw1_int, FRV_BUILTIN_MEXPDHW);
8604   def_builtin ("__MEXPDHD", uw2_ftype_uw1_int, FRV_BUILTIN_MEXPDHD);
8605   def_builtin ("__MPACKH", uw1_ftype_uh_uh, FRV_BUILTIN_MPACKH);
8606   def_builtin ("__MUNPACKH", uw2_ftype_uw1, FRV_BUILTIN_MUNPACKH);
8607   def_builtin ("__MDPACKH", uw2_ftype_uh_uh_uh_uh, FRV_BUILTIN_MDPACKH);
8608   def_builtin ("__MDUNPACKH", void_ftype_uw4_uw2, FRV_BUILTIN_MDUNPACKH);
8609   def_builtin ("__MBTOH", uw2_ftype_uw1, FRV_BUILTIN_MBTOH);
8610   def_builtin ("__MHTOB", uw1_ftype_uw2, FRV_BUILTIN_MHTOB);
8611   def_builtin ("__MBTOHE", void_ftype_uw4_uw1, FRV_BUILTIN_MBTOHE);
8612   def_builtin ("__MCLRACC", void_ftype_acc, FRV_BUILTIN_MCLRACC);
8613   def_builtin ("__MCLRACCA", void_ftype_void, FRV_BUILTIN_MCLRACCA);
8614   def_builtin ("__MRDACC", uw1_ftype_acc, FRV_BUILTIN_MRDACC);
8615   def_builtin ("__MRDACCG", uw1_ftype_acc, FRV_BUILTIN_MRDACCG);
8616   def_builtin ("__MWTACC", void_ftype_acc_uw1, FRV_BUILTIN_MWTACC);
8617   def_builtin ("__MWTACCG", void_ftype_acc_uw1, FRV_BUILTIN_MWTACCG);
8618   def_builtin ("__Mcop1", uw1_ftype_uw1_uw1, FRV_BUILTIN_MCOP1);
8619   def_builtin ("__Mcop2", uw1_ftype_uw1_uw1, FRV_BUILTIN_MCOP2);
8620   def_builtin ("__MTRAP", void_ftype_void, FRV_BUILTIN_MTRAP);
8621   def_builtin ("__MQXMACHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQXMACHS);
8622   def_builtin ("__MQXMACXHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQXMACXHS);
8623   def_builtin ("__MQMACXHS", void_ftype_acc_sw2_sw2, FRV_BUILTIN_MQMACXHS);
8624   def_builtin ("__MADDACCS", void_ftype_acc_acc, FRV_BUILTIN_MADDACCS);
8625   def_builtin ("__MSUBACCS", void_ftype_acc_acc, FRV_BUILTIN_MSUBACCS);
8626   def_builtin ("__MASACCS", void_ftype_acc_acc, FRV_BUILTIN_MASACCS);
8627   def_builtin ("__MDADDACCS", void_ftype_acc_acc, FRV_BUILTIN_MDADDACCS);
8628   def_builtin ("__MDSUBACCS", void_ftype_acc_acc, FRV_BUILTIN_MDSUBACCS);
8629   def_builtin ("__MDASACCS", void_ftype_acc_acc, FRV_BUILTIN_MDASACCS);
8630   def_builtin ("__MABSHS", uw1_ftype_sw1, FRV_BUILTIN_MABSHS);
8631   def_builtin ("__MDROTLI", uw2_ftype_uw2_int, FRV_BUILTIN_MDROTLI);
8632   def_builtin ("__MCPLHI", uw1_ftype_uw2_int, FRV_BUILTIN_MCPLHI);
8633   def_builtin ("__MCPLI", uw1_ftype_uw2_int, FRV_BUILTIN_MCPLI);
8634   def_builtin ("__MDCUTSSI", uw2_ftype_acc_int, FRV_BUILTIN_MDCUTSSI);
8635   def_builtin ("__MQSATHS", sw2_ftype_sw2_sw2, FRV_BUILTIN_MQSATHS);
8636   def_builtin ("__MHSETLOS", sw1_ftype_sw1_int, FRV_BUILTIN_MHSETLOS);
8637   def_builtin ("__MHSETHIS", sw1_ftype_sw1_int, FRV_BUILTIN_MHSETHIS);
8638   def_builtin ("__MHDSETS", sw1_ftype_int, FRV_BUILTIN_MHDSETS);
8639   def_builtin ("__MHSETLOH", uw1_ftype_uw1_int, FRV_BUILTIN_MHSETLOH);
8640   def_builtin ("__MHSETHIH", uw1_ftype_uw1_int, FRV_BUILTIN_MHSETHIH);
8641   def_builtin ("__MHDSETH", uw1_ftype_uw1_int, FRV_BUILTIN_MHDSETH);
8642   def_builtin ("__MQLCLRHS", sw2_ftype_sw2_sw2, FRV_BUILTIN_MQLCLRHS);
8643   def_builtin ("__MQLMTHS", sw2_ftype_sw2_sw2, FRV_BUILTIN_MQLMTHS);
8644   def_builtin ("__MQSLLHI", uw2_ftype_uw2_int, FRV_BUILTIN_MQSLLHI);
8645   def_builtin ("__MQSRAHI", sw2_ftype_sw2_int, FRV_BUILTIN_MQSRAHI);
8646   def_builtin ("__SMUL", sw2_ftype_sw1_sw1, FRV_BUILTIN_SMUL);
8647   def_builtin ("__UMUL", uw2_ftype_uw1_uw1, FRV_BUILTIN_UMUL);
8648   def_builtin ("__SMASS", void_ftype_sw1_sw1, FRV_BUILTIN_SMASS);
8649   def_builtin ("__SMSSS", void_ftype_sw1_sw1, FRV_BUILTIN_SMSSS);
8650   def_builtin ("__SMU", void_ftype_sw1_sw1, FRV_BUILTIN_SMU);
8651   def_builtin ("__ADDSS", sw1_ftype_sw1_sw1, FRV_BUILTIN_ADDSS);
8652   def_builtin ("__SUBSS", sw1_ftype_sw1_sw1, FRV_BUILTIN_SUBSS);
8653   def_builtin ("__SLASS", sw1_ftype_sw1_sw1, FRV_BUILTIN_SLASS);
8654   def_builtin ("__SCAN", sw1_ftype_sw1_sw1, FRV_BUILTIN_SCAN);
8655   def_builtin ("__SCUTSS", sw1_ftype_sw1, FRV_BUILTIN_SCUTSS);
8656   def_builtin ("__IACCreadll", sw2_ftype_iacc, FRV_BUILTIN_IACCreadll);
8657   def_builtin ("__IACCreadl", sw1_ftype_iacc, FRV_BUILTIN_IACCreadl);
8658   def_builtin ("__IACCsetll", void_ftype_iacc_sw2, FRV_BUILTIN_IACCsetll);
8659   def_builtin ("__IACCsetl", void_ftype_iacc_sw1, FRV_BUILTIN_IACCsetl);
8660   def_builtin ("__data_prefetch0", void_ftype_ptr, FRV_BUILTIN_PREFETCH0);
8661   def_builtin ("__data_prefetch", void_ftype_ptr, FRV_BUILTIN_PREFETCH);
8662   def_builtin ("__builtin_read8", uw1_ftype_vptr, FRV_BUILTIN_READ8);
8663   def_builtin ("__builtin_read16", uw1_ftype_vptr, FRV_BUILTIN_READ16);
8664   def_builtin ("__builtin_read32", uw1_ftype_vptr, FRV_BUILTIN_READ32);
8665   def_builtin ("__builtin_read64", uw2_ftype_vptr, FRV_BUILTIN_READ64);
8666
8667   def_builtin ("__builtin_write8", void_ftype_vptr_ub, FRV_BUILTIN_WRITE8);
8668   def_builtin ("__builtin_write16", void_ftype_vptr_uh, FRV_BUILTIN_WRITE16);
8669   def_builtin ("__builtin_write32", void_ftype_vptr_uw1, FRV_BUILTIN_WRITE32);
8670   def_builtin ("__builtin_write64", void_ftype_vptr_uw2, FRV_BUILTIN_WRITE64);
8671
8672 #undef UNARY
8673 #undef BINARY
8674 #undef TRINARY
8675 #undef QUAD
8676 }
8677
8678 /* Set the names for various arithmetic operations according to the
8679    FRV ABI.  */
8680 static void
8681 frv_init_libfuncs (void)
8682 {
8683   set_optab_libfunc (smod_optab,     SImode, "__modi");
8684   set_optab_libfunc (umod_optab,     SImode, "__umodi");
8685
8686   set_optab_libfunc (add_optab,      DImode, "__addll");
8687   set_optab_libfunc (sub_optab,      DImode, "__subll");
8688   set_optab_libfunc (smul_optab,     DImode, "__mulll");
8689   set_optab_libfunc (sdiv_optab,     DImode, "__divll");
8690   set_optab_libfunc (smod_optab,     DImode, "__modll");
8691   set_optab_libfunc (umod_optab,     DImode, "__umodll");
8692   set_optab_libfunc (and_optab,      DImode, "__andll");
8693   set_optab_libfunc (ior_optab,      DImode, "__orll");
8694   set_optab_libfunc (xor_optab,      DImode, "__xorll");
8695   set_optab_libfunc (one_cmpl_optab, DImode, "__notll");
8696
8697   set_optab_libfunc (add_optab,      SFmode, "__addf");
8698   set_optab_libfunc (sub_optab,      SFmode, "__subf");
8699   set_optab_libfunc (smul_optab,     SFmode, "__mulf");
8700   set_optab_libfunc (sdiv_optab,     SFmode, "__divf");
8701
8702   set_optab_libfunc (add_optab,      DFmode, "__addd");
8703   set_optab_libfunc (sub_optab,      DFmode, "__subd");
8704   set_optab_libfunc (smul_optab,     DFmode, "__muld");
8705   set_optab_libfunc (sdiv_optab,     DFmode, "__divd");
8706
8707   set_conv_libfunc (sext_optab,   DFmode, SFmode, "__ftod");
8708   set_conv_libfunc (trunc_optab,  SFmode, DFmode, "__dtof");
8709
8710   set_conv_libfunc (sfix_optab,   SImode, SFmode, "__ftoi");
8711   set_conv_libfunc (sfix_optab,   DImode, SFmode, "__ftoll");
8712   set_conv_libfunc (sfix_optab,   SImode, DFmode, "__dtoi");
8713   set_conv_libfunc (sfix_optab,   DImode, DFmode, "__dtoll");
8714
8715   set_conv_libfunc (ufix_optab,   SImode, SFmode, "__ftoui");
8716   set_conv_libfunc (ufix_optab,   DImode, SFmode, "__ftoull");
8717   set_conv_libfunc (ufix_optab,   SImode, DFmode, "__dtoui");
8718   set_conv_libfunc (ufix_optab,   DImode, DFmode, "__dtoull");
8719
8720   set_conv_libfunc (sfloat_optab, SFmode, SImode, "__itof");
8721   set_conv_libfunc (sfloat_optab, SFmode, DImode, "__lltof");
8722   set_conv_libfunc (sfloat_optab, DFmode, SImode, "__itod");
8723   set_conv_libfunc (sfloat_optab, DFmode, DImode, "__lltod");
8724 }
8725
8726 /* Convert an integer constant to an accumulator register.  ICODE is the
8727    code of the target instruction, OPNUM is the number of the
8728    accumulator operand and OPVAL is the constant integer.  Try both
8729    ACC and ACCG registers; only report an error if neither fit the
8730    instruction.  */
8731
8732 static rtx
8733 frv_int_to_acc (enum insn_code icode, int opnum, rtx opval)
8734 {
8735   rtx reg;
8736   int i;
8737
8738   /* ACCs and ACCGs are implicit global registers if media intrinsics
8739      are being used.  We set up this lazily to avoid creating lots of
8740      unnecessary call_insn rtl in non-media code.  */
8741   for (i = 0; i <= ACC_MASK; i++)
8742     if ((i & ACC_MASK) == i)
8743       global_regs[i + ACC_FIRST] = global_regs[i + ACCG_FIRST] = 1;
8744
8745   if (GET_CODE (opval) != CONST_INT)
8746     {
8747       error ("accumulator is not a constant integer");
8748       return NULL_RTX;
8749     }
8750   if ((INTVAL (opval) & ~ACC_MASK) != 0)
8751     {
8752       error ("accumulator number is out of bounds");
8753       return NULL_RTX;
8754     }
8755
8756   reg = gen_rtx_REG (insn_data[icode].operand[opnum].mode,
8757                      ACC_FIRST + INTVAL (opval));
8758   if (! (*insn_data[icode].operand[opnum].predicate) (reg, VOIDmode))
8759     SET_REGNO (reg, ACCG_FIRST + INTVAL (opval));
8760
8761   if (! (*insn_data[icode].operand[opnum].predicate) (reg, VOIDmode))
8762     {
8763       error ("inappropriate accumulator for %qs", insn_data[icode].name);
8764       return NULL_RTX;
8765     }
8766   return reg;
8767 }
8768
8769 /* If an ACC rtx has mode MODE, return the mode that the matching ACCG
8770    should have.  */
8771
8772 static enum machine_mode
8773 frv_matching_accg_mode (enum machine_mode mode)
8774 {
8775   switch (mode)
8776     {
8777     case V4SImode:
8778       return V4QImode;
8779
8780     case DImode:
8781       return HImode;
8782
8783     case SImode:
8784       return QImode;
8785
8786     default:
8787       gcc_unreachable ();
8788     }
8789 }
8790
8791 /* Given that a __builtin_read or __builtin_write function is accessing
8792    address ADDRESS, return the value that should be used as operand 1
8793    of the membar.  */
8794
8795 static rtx
8796 frv_io_address_cookie (rtx address)
8797 {
8798   return (GET_CODE (address) == CONST_INT
8799           ? GEN_INT (INTVAL (address) / 8 * 8)
8800           : const0_rtx);
8801 }
8802
8803 /* Return the accumulator guard that should be paired with accumulator
8804    register ACC.  The mode of the returned register is in the same
8805    class as ACC, but is four times smaller.  */
8806
8807 rtx
8808 frv_matching_accg_for_acc (rtx acc)
8809 {
8810   return gen_rtx_REG (frv_matching_accg_mode (GET_MODE (acc)),
8811                       REGNO (acc) - ACC_FIRST + ACCG_FIRST);
8812 }
8813
8814 /* Read the requested argument from the call EXP given by INDEX.
8815    Return the value as an rtx.  */
8816
8817 static rtx
8818 frv_read_argument (tree exp, unsigned int index)
8819 {
8820   return expand_normal (CALL_EXPR_ARG (exp, index));
8821 }
8822
8823 /* Like frv_read_argument, but interpret the argument as the number
8824    of an IACC register and return a (reg:MODE ...) rtx for it.  */
8825
8826 static rtx
8827 frv_read_iacc_argument (enum machine_mode mode, tree call,
8828                         unsigned int index)
8829 {
8830   int i, regno;
8831   rtx op;
8832
8833   op = frv_read_argument (call, index);
8834   if (GET_CODE (op) != CONST_INT
8835       || INTVAL (op) < 0
8836       || INTVAL (op) > IACC_LAST - IACC_FIRST
8837       || ((INTVAL (op) * 4) & (GET_MODE_SIZE (mode) - 1)) != 0)
8838     {
8839       error ("invalid IACC argument");
8840       op = const0_rtx;
8841     }
8842
8843   /* IACCs are implicit global registers.  We set up this lazily to
8844      avoid creating lots of unnecessary call_insn rtl when IACCs aren't
8845      being used.  */
8846   regno = INTVAL (op) + IACC_FIRST;
8847   for (i = 0; i < HARD_REGNO_NREGS (regno, mode); i++)
8848     global_regs[regno + i] = 1;
8849
8850   return gen_rtx_REG (mode, regno);
8851 }
8852
8853 /* Return true if OPVAL can be used for operand OPNUM of instruction ICODE.
8854    The instruction should require a constant operand of some sort.  The
8855    function prints an error if OPVAL is not valid.  */
8856
8857 static int
8858 frv_check_constant_argument (enum insn_code icode, int opnum, rtx opval)
8859 {
8860   if (GET_CODE (opval) != CONST_INT)
8861     {
8862       error ("%qs expects a constant argument", insn_data[icode].name);
8863       return FALSE;
8864     }
8865   if (! (*insn_data[icode].operand[opnum].predicate) (opval, VOIDmode))
8866     {
8867       error ("constant argument out of range for %qs", insn_data[icode].name);
8868       return FALSE;
8869     }
8870   return TRUE;
8871 }
8872
8873 /* Return a legitimate rtx for instruction ICODE's return value.  Use TARGET
8874    if it's not null, has the right mode, and satisfies operand 0's
8875    predicate.  */
8876
8877 static rtx
8878 frv_legitimize_target (enum insn_code icode, rtx target)
8879 {
8880   enum machine_mode mode = insn_data[icode].operand[0].mode;
8881
8882   if (! target
8883       || GET_MODE (target) != mode
8884       || ! (*insn_data[icode].operand[0].predicate) (target, mode))
8885     return gen_reg_rtx (mode);
8886   else
8887     return target;
8888 }
8889
8890 /* Given that ARG is being passed as operand OPNUM to instruction ICODE,
8891    check whether ARG satisfies the operand's constraints.  If it doesn't,
8892    copy ARG to a temporary register and return that.  Otherwise return ARG
8893    itself.  */
8894
8895 static rtx
8896 frv_legitimize_argument (enum insn_code icode, int opnum, rtx arg)
8897 {
8898   enum machine_mode mode = insn_data[icode].operand[opnum].mode;
8899
8900   if ((*insn_data[icode].operand[opnum].predicate) (arg, mode))
8901     return arg;
8902   else
8903     return copy_to_mode_reg (mode, arg);
8904 }
8905
8906 /* Return a volatile memory reference of mode MODE whose address is ARG.  */
8907
8908 static rtx
8909 frv_volatile_memref (enum machine_mode mode, rtx arg)
8910 {
8911   rtx mem;
8912
8913   mem = gen_rtx_MEM (mode, memory_address (mode, arg));
8914   MEM_VOLATILE_P (mem) = 1;
8915   return mem;
8916 }
8917
8918 /* Expand builtins that take a single, constant argument.  At the moment,
8919    only MHDSETS falls into this category.  */
8920
8921 static rtx
8922 frv_expand_set_builtin (enum insn_code icode, tree call, rtx target)
8923 {
8924   rtx pat;
8925   rtx op0 = frv_read_argument (call, 0);
8926
8927   if (! frv_check_constant_argument (icode, 1, op0))
8928     return NULL_RTX;
8929
8930   target = frv_legitimize_target (icode, target);
8931   pat = GEN_FCN (icode) (target, op0);
8932   if (! pat)
8933     return NULL_RTX;
8934
8935   emit_insn (pat);
8936   return target;
8937 }
8938
8939 /* Expand builtins that take one operand.  */
8940
8941 static rtx
8942 frv_expand_unop_builtin (enum insn_code icode, tree call, rtx target)
8943 {
8944   rtx pat;
8945   rtx op0 = frv_read_argument (call, 0);
8946
8947   target = frv_legitimize_target (icode, target);
8948   op0 = frv_legitimize_argument (icode, 1, op0);
8949   pat = GEN_FCN (icode) (target, op0);
8950   if (! pat)
8951     return NULL_RTX;
8952
8953   emit_insn (pat);
8954   return target;
8955 }
8956
8957 /* Expand builtins that take two operands.  */
8958
8959 static rtx
8960 frv_expand_binop_builtin (enum insn_code icode, tree call, rtx target)
8961 {
8962   rtx pat;
8963   rtx op0 = frv_read_argument (call, 0);
8964   rtx op1 = frv_read_argument (call, 1);
8965
8966   target = frv_legitimize_target (icode, target);
8967   op0 = frv_legitimize_argument (icode, 1, op0);
8968   op1 = frv_legitimize_argument (icode, 2, op1);
8969   pat = GEN_FCN (icode) (target, op0, op1);
8970   if (! pat)
8971     return NULL_RTX;
8972
8973   emit_insn (pat);
8974   return target;
8975 }
8976
8977 /* Expand cut-style builtins, which take two operands and an implicit ACCG
8978    one.  */
8979
8980 static rtx
8981 frv_expand_cut_builtin (enum insn_code icode, tree call, rtx target)
8982 {
8983   rtx pat;
8984   rtx op0 = frv_read_argument (call, 0);
8985   rtx op1 = frv_read_argument (call, 1);
8986   rtx op2;
8987
8988   target = frv_legitimize_target (icode, target);
8989   op0 = frv_int_to_acc (icode, 1, op0);
8990   if (! op0)
8991     return NULL_RTX;
8992
8993   if (icode == CODE_FOR_mdcutssi || GET_CODE (op1) == CONST_INT)
8994     {
8995       if (! frv_check_constant_argument (icode, 2, op1))
8996         return NULL_RTX;
8997     }
8998   else
8999     op1 = frv_legitimize_argument (icode, 2, op1);
9000
9001   op2 = frv_matching_accg_for_acc (op0);
9002   pat = GEN_FCN (icode) (target, op0, op1, op2);
9003   if (! pat)
9004     return NULL_RTX;
9005
9006   emit_insn (pat);
9007   return target;
9008 }
9009
9010 /* Expand builtins that take two operands and the second is immediate.  */
9011
9012 static rtx
9013 frv_expand_binopimm_builtin (enum insn_code icode, tree call, rtx target)
9014 {
9015   rtx pat;
9016   rtx op0 = frv_read_argument (call, 0);
9017   rtx op1 = frv_read_argument (call, 1);
9018
9019   if (! frv_check_constant_argument (icode, 2, op1))
9020     return NULL_RTX;
9021
9022   target = frv_legitimize_target (icode, target);
9023   op0 = frv_legitimize_argument (icode, 1, op0);
9024   pat = GEN_FCN (icode) (target, op0, op1);
9025   if (! pat)
9026     return NULL_RTX;
9027
9028   emit_insn (pat);
9029   return target;
9030 }
9031
9032 /* Expand builtins that take two operands, the first operand being a pointer to
9033    ints and return void.  */
9034
9035 static rtx
9036 frv_expand_voidbinop_builtin (enum insn_code icode, tree call)
9037 {
9038   rtx pat;
9039   rtx op0 = frv_read_argument (call, 0);
9040   rtx op1 = frv_read_argument (call, 1);
9041   enum machine_mode mode0 = insn_data[icode].operand[0].mode;
9042   rtx addr;
9043
9044   if (GET_CODE (op0) != MEM)
9045     {
9046       rtx reg = op0;
9047
9048       if (! offsettable_address_p (0, mode0, op0))
9049         {
9050           reg = gen_reg_rtx (Pmode);
9051           emit_insn (gen_rtx_SET (VOIDmode, reg, op0));
9052         }
9053
9054       op0 = gen_rtx_MEM (SImode, reg);
9055     }
9056
9057   addr = XEXP (op0, 0);
9058   if (! offsettable_address_p (0, mode0, addr))
9059     addr = copy_to_mode_reg (Pmode, op0);
9060
9061   op0 = change_address (op0, V4SImode, addr);
9062   op1 = frv_legitimize_argument (icode, 1, op1);
9063   pat = GEN_FCN (icode) (op0, op1);
9064   if (! pat)
9065     return 0;
9066
9067   emit_insn (pat);
9068   return 0;
9069 }
9070
9071 /* Expand builtins that take two long operands and return void.  */
9072
9073 static rtx
9074 frv_expand_int_void2arg (enum insn_code icode, tree call)
9075 {
9076   rtx pat;
9077   rtx op0 = frv_read_argument (call, 0);
9078   rtx op1 = frv_read_argument (call, 1);
9079
9080   op0 = frv_legitimize_argument (icode, 1, op0);
9081   op1 = frv_legitimize_argument (icode, 1, op1);
9082   pat = GEN_FCN (icode) (op0, op1);
9083   if (! pat)
9084     return NULL_RTX;
9085
9086   emit_insn (pat);
9087   return NULL_RTX;
9088 }
9089
9090 /* Expand prefetch builtins.  These take a single address as argument.  */
9091
9092 static rtx
9093 frv_expand_prefetches (enum insn_code icode, tree call)
9094 {
9095   rtx pat;
9096   rtx op0 = frv_read_argument (call, 0);
9097
9098   pat = GEN_FCN (icode) (force_reg (Pmode, op0));
9099   if (! pat)
9100     return 0;
9101
9102   emit_insn (pat);
9103   return 0;
9104 }
9105
9106 /* Expand builtins that take three operands and return void.  The first
9107    argument must be a constant that describes a pair or quad accumulators.  A
9108    fourth argument is created that is the accumulator guard register that
9109    corresponds to the accumulator.  */
9110
9111 static rtx
9112 frv_expand_voidtriop_builtin (enum insn_code icode, tree call)
9113 {
9114   rtx pat;
9115   rtx op0 = frv_read_argument (call, 0);
9116   rtx op1 = frv_read_argument (call, 1);
9117   rtx op2 = frv_read_argument (call, 2);
9118   rtx op3;
9119
9120   op0 = frv_int_to_acc (icode, 0, op0);
9121   if (! op0)
9122     return NULL_RTX;
9123
9124   op1 = frv_legitimize_argument (icode, 1, op1);
9125   op2 = frv_legitimize_argument (icode, 2, op2);
9126   op3 = frv_matching_accg_for_acc (op0);
9127   pat = GEN_FCN (icode) (op0, op1, op2, op3);
9128   if (! pat)
9129     return NULL_RTX;
9130
9131   emit_insn (pat);
9132   return NULL_RTX;
9133 }
9134
9135 /* Expand builtins that perform accumulator-to-accumulator operations.
9136    These builtins take two accumulator numbers as argument and return
9137    void.  */
9138
9139 static rtx
9140 frv_expand_voidaccop_builtin (enum insn_code icode, tree call)
9141 {
9142   rtx pat;
9143   rtx op0 = frv_read_argument (call, 0);
9144   rtx op1 = frv_read_argument (call, 1);
9145   rtx op2;
9146   rtx op3;
9147
9148   op0 = frv_int_to_acc (icode, 0, op0);
9149   if (! op0)
9150     return NULL_RTX;
9151
9152   op1 = frv_int_to_acc (icode, 1, op1);
9153   if (! op1)
9154     return NULL_RTX;
9155
9156   op2 = frv_matching_accg_for_acc (op0);
9157   op3 = frv_matching_accg_for_acc (op1);
9158   pat = GEN_FCN (icode) (op0, op1, op2, op3);
9159   if (! pat)
9160     return NULL_RTX;
9161
9162   emit_insn (pat);
9163   return NULL_RTX;
9164 }
9165
9166 /* Expand a __builtin_read* function.  ICODE is the instruction code for the
9167    membar and TARGET_MODE is the mode that the loaded value should have.  */
9168
9169 static rtx
9170 frv_expand_load_builtin (enum insn_code icode, enum machine_mode target_mode,
9171                          tree call, rtx target)
9172 {
9173   rtx op0 = frv_read_argument (call, 0);
9174   rtx cookie = frv_io_address_cookie (op0);
9175
9176   if (target == 0 || !REG_P (target))
9177     target = gen_reg_rtx (target_mode);
9178   op0 = frv_volatile_memref (insn_data[icode].operand[0].mode, op0);
9179   convert_move (target, op0, 1);
9180   emit_insn (GEN_FCN (icode) (copy_rtx (op0), cookie, GEN_INT (FRV_IO_READ)));
9181   cfun->machine->has_membar_p = 1;
9182   return target;
9183 }
9184
9185 /* Likewise __builtin_write* functions.  */
9186
9187 static rtx
9188 frv_expand_store_builtin (enum insn_code icode, tree call)
9189 {
9190   rtx op0 = frv_read_argument (call, 0);
9191   rtx op1 = frv_read_argument (call, 1);
9192   rtx cookie = frv_io_address_cookie (op0);
9193
9194   op0 = frv_volatile_memref (insn_data[icode].operand[0].mode, op0);
9195   convert_move (op0, force_reg (insn_data[icode].operand[0].mode, op1), 1);
9196   emit_insn (GEN_FCN (icode) (copy_rtx (op0), cookie, GEN_INT (FRV_IO_WRITE)));
9197   cfun->machine->has_membar_p = 1;
9198   return NULL_RTX;
9199 }
9200
9201 /* Expand the MDPACKH builtin.  It takes four unsigned short arguments and
9202    each argument forms one word of the two double-word input registers.
9203    CALL is the tree for the call and TARGET, if nonnull, suggests a good place
9204    to put the return value.  */
9205
9206 static rtx
9207 frv_expand_mdpackh_builtin (tree call, rtx target)
9208 {
9209   enum insn_code icode = CODE_FOR_mdpackh;
9210   rtx pat, op0, op1;
9211   rtx arg1 = frv_read_argument (call, 0);
9212   rtx arg2 = frv_read_argument (call, 1);
9213   rtx arg3 = frv_read_argument (call, 2);
9214   rtx arg4 = frv_read_argument (call, 3);
9215
9216   target = frv_legitimize_target (icode, target);
9217   op0 = gen_reg_rtx (DImode);
9218   op1 = gen_reg_rtx (DImode);
9219
9220   /* The high half of each word is not explicitly initialized, so indicate
9221      that the input operands are not live before this point.  */
9222   emit_clobber (op0);
9223   emit_clobber (op1);
9224
9225   /* Move each argument into the low half of its associated input word.  */
9226   emit_move_insn (simplify_gen_subreg (HImode, op0, DImode, 2), arg1);
9227   emit_move_insn (simplify_gen_subreg (HImode, op0, DImode, 6), arg2);
9228   emit_move_insn (simplify_gen_subreg (HImode, op1, DImode, 2), arg3);
9229   emit_move_insn (simplify_gen_subreg (HImode, op1, DImode, 6), arg4);
9230
9231   pat = GEN_FCN (icode) (target, op0, op1);
9232   if (! pat)
9233     return NULL_RTX;
9234
9235   emit_insn (pat);
9236   return target;
9237 }
9238
9239 /* Expand the MCLRACC builtin.  This builtin takes a single accumulator
9240    number as argument.  */
9241
9242 static rtx
9243 frv_expand_mclracc_builtin (tree call)
9244 {
9245   enum insn_code icode = CODE_FOR_mclracc;
9246   rtx pat;
9247   rtx op0 = frv_read_argument (call, 0);
9248
9249   op0 = frv_int_to_acc (icode, 0, op0);
9250   if (! op0)
9251     return NULL_RTX;
9252
9253   pat = GEN_FCN (icode) (op0);
9254   if (pat)
9255     emit_insn (pat);
9256
9257   return NULL_RTX;
9258 }
9259
9260 /* Expand builtins that take no arguments.  */
9261
9262 static rtx
9263 frv_expand_noargs_builtin (enum insn_code icode)
9264 {
9265   rtx pat = GEN_FCN (icode) (const0_rtx);
9266   if (pat)
9267     emit_insn (pat);
9268
9269   return NULL_RTX;
9270 }
9271
9272 /* Expand MRDACC and MRDACCG.  These builtins take a single accumulator
9273    number or accumulator guard number as argument and return an SI integer.  */
9274
9275 static rtx
9276 frv_expand_mrdacc_builtin (enum insn_code icode, tree call)
9277 {
9278   rtx pat;
9279   rtx target = gen_reg_rtx (SImode);
9280   rtx op0 = frv_read_argument (call, 0);
9281
9282   op0 = frv_int_to_acc (icode, 1, op0);
9283   if (! op0)
9284     return NULL_RTX;
9285
9286   pat = GEN_FCN (icode) (target, op0);
9287   if (! pat)
9288     return NULL_RTX;
9289
9290   emit_insn (pat);
9291   return target;
9292 }
9293
9294 /* Expand MWTACC and MWTACCG.  These builtins take an accumulator or
9295    accumulator guard as their first argument and an SImode value as their
9296    second.  */
9297
9298 static rtx
9299 frv_expand_mwtacc_builtin (enum insn_code icode, tree call)
9300 {
9301   rtx pat;
9302   rtx op0 = frv_read_argument (call, 0);
9303   rtx op1 = frv_read_argument (call, 1);
9304
9305   op0 = frv_int_to_acc (icode, 0, op0);
9306   if (! op0)
9307     return NULL_RTX;
9308
9309   op1 = frv_legitimize_argument (icode, 1, op1);
9310   pat = GEN_FCN (icode) (op0, op1);
9311   if (pat)
9312     emit_insn (pat);
9313
9314   return NULL_RTX;
9315 }
9316
9317 /* Emit a move from SRC to DEST in SImode chunks.  This can be used
9318    to move DImode values into and out of IACC0.  */
9319
9320 static void
9321 frv_split_iacc_move (rtx dest, rtx src)
9322 {
9323   enum machine_mode inner;
9324   int i;
9325
9326   inner = GET_MODE (dest);
9327   for (i = 0; i < GET_MODE_SIZE (inner); i += GET_MODE_SIZE (SImode))
9328     emit_move_insn (simplify_gen_subreg (SImode, dest, inner, i),
9329                     simplify_gen_subreg (SImode, src, inner, i));
9330 }
9331
9332 /* Expand builtins.  */
9333
9334 static rtx
9335 frv_expand_builtin (tree exp,
9336                     rtx target,
9337                     rtx subtarget ATTRIBUTE_UNUSED,
9338                     enum machine_mode mode ATTRIBUTE_UNUSED,
9339                     int ignore ATTRIBUTE_UNUSED)
9340 {
9341   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
9342   unsigned fcode = (unsigned)DECL_FUNCTION_CODE (fndecl);
9343   unsigned i;
9344   struct builtin_description *d;
9345
9346   if (fcode < FRV_BUILTIN_FIRST_NONMEDIA && !TARGET_MEDIA)
9347     {
9348       error ("media functions are not available unless -mmedia is used");
9349       return NULL_RTX;
9350     }
9351
9352   switch (fcode)
9353     {
9354     case FRV_BUILTIN_MCOP1:
9355     case FRV_BUILTIN_MCOP2:
9356     case FRV_BUILTIN_MDUNPACKH:
9357     case FRV_BUILTIN_MBTOHE:
9358       if (! TARGET_MEDIA_REV1)
9359         {
9360           error ("this media function is only available on the fr500");
9361           return NULL_RTX;
9362         }
9363       break;
9364
9365     case FRV_BUILTIN_MQXMACHS:
9366     case FRV_BUILTIN_MQXMACXHS:
9367     case FRV_BUILTIN_MQMACXHS:
9368     case FRV_BUILTIN_MADDACCS:
9369     case FRV_BUILTIN_MSUBACCS:
9370     case FRV_BUILTIN_MASACCS:
9371     case FRV_BUILTIN_MDADDACCS:
9372     case FRV_BUILTIN_MDSUBACCS:
9373     case FRV_BUILTIN_MDASACCS:
9374     case FRV_BUILTIN_MABSHS:
9375     case FRV_BUILTIN_MDROTLI:
9376     case FRV_BUILTIN_MCPLHI:
9377     case FRV_BUILTIN_MCPLI:
9378     case FRV_BUILTIN_MDCUTSSI:
9379     case FRV_BUILTIN_MQSATHS:
9380     case FRV_BUILTIN_MHSETLOS:
9381     case FRV_BUILTIN_MHSETLOH:
9382     case FRV_BUILTIN_MHSETHIS:
9383     case FRV_BUILTIN_MHSETHIH:
9384     case FRV_BUILTIN_MHDSETS:
9385     case FRV_BUILTIN_MHDSETH:
9386       if (! TARGET_MEDIA_REV2)
9387         {
9388           error ("this media function is only available on the fr400"
9389                  " and fr550");
9390           return NULL_RTX;
9391         }
9392       break;
9393
9394     case FRV_BUILTIN_SMASS:
9395     case FRV_BUILTIN_SMSSS:
9396     case FRV_BUILTIN_SMU:
9397     case FRV_BUILTIN_ADDSS:
9398     case FRV_BUILTIN_SUBSS:
9399     case FRV_BUILTIN_SLASS:
9400     case FRV_BUILTIN_SCUTSS:
9401     case FRV_BUILTIN_IACCreadll:
9402     case FRV_BUILTIN_IACCreadl:
9403     case FRV_BUILTIN_IACCsetll:
9404     case FRV_BUILTIN_IACCsetl:
9405       if (!TARGET_FR405_BUILTINS)
9406         {
9407           error ("this builtin function is only available"
9408                  " on the fr405 and fr450");
9409           return NULL_RTX;
9410         }
9411       break;
9412
9413     case FRV_BUILTIN_PREFETCH:
9414       if (!TARGET_FR500_FR550_BUILTINS)
9415         {
9416           error ("this builtin function is only available on the fr500"
9417                  " and fr550");
9418           return NULL_RTX;
9419         }
9420       break;
9421
9422     case FRV_BUILTIN_MQLCLRHS:
9423     case FRV_BUILTIN_MQLMTHS:
9424     case FRV_BUILTIN_MQSLLHI:
9425     case FRV_BUILTIN_MQSRAHI:
9426       if (!TARGET_MEDIA_FR450)
9427         {
9428           error ("this builtin function is only available on the fr450");
9429           return NULL_RTX;
9430         }
9431       break;
9432
9433     default:
9434       break;
9435     }
9436
9437   /* Expand unique builtins.  */
9438
9439   switch (fcode)
9440     {
9441     case FRV_BUILTIN_MTRAP:
9442       return frv_expand_noargs_builtin (CODE_FOR_mtrap);
9443
9444     case FRV_BUILTIN_MCLRACC:
9445       return frv_expand_mclracc_builtin (exp);
9446
9447     case FRV_BUILTIN_MCLRACCA:
9448       if (TARGET_ACC_8)
9449         return frv_expand_noargs_builtin (CODE_FOR_mclracca8);
9450       else
9451         return frv_expand_noargs_builtin (CODE_FOR_mclracca4);
9452
9453     case FRV_BUILTIN_MRDACC:
9454       return frv_expand_mrdacc_builtin (CODE_FOR_mrdacc, exp);
9455
9456     case FRV_BUILTIN_MRDACCG:
9457       return frv_expand_mrdacc_builtin (CODE_FOR_mrdaccg, exp);
9458
9459     case FRV_BUILTIN_MWTACC:
9460       return frv_expand_mwtacc_builtin (CODE_FOR_mwtacc, exp);
9461
9462     case FRV_BUILTIN_MWTACCG:
9463       return frv_expand_mwtacc_builtin (CODE_FOR_mwtaccg, exp);
9464
9465     case FRV_BUILTIN_MDPACKH:
9466       return frv_expand_mdpackh_builtin (exp, target);
9467
9468     case FRV_BUILTIN_IACCreadll:
9469       {
9470         rtx src = frv_read_iacc_argument (DImode, exp, 0);
9471         if (target == 0 || !REG_P (target))
9472           target = gen_reg_rtx (DImode);
9473         frv_split_iacc_move (target, src);
9474         return target;
9475       }
9476
9477     case FRV_BUILTIN_IACCreadl:
9478       return frv_read_iacc_argument (SImode, exp, 0);
9479
9480     case FRV_BUILTIN_IACCsetll:
9481       {
9482         rtx dest = frv_read_iacc_argument (DImode, exp, 0);
9483         rtx src = frv_read_argument (exp, 1);
9484         frv_split_iacc_move (dest, force_reg (DImode, src));
9485         return 0;
9486       }
9487
9488     case FRV_BUILTIN_IACCsetl:
9489       {
9490         rtx dest = frv_read_iacc_argument (SImode, exp, 0);
9491         rtx src = frv_read_argument (exp, 1);
9492         emit_move_insn (dest, force_reg (SImode, src));
9493         return 0;
9494       }
9495
9496     default:
9497       break;
9498     }
9499
9500   /* Expand groups of builtins.  */
9501
9502   for (i = 0, d = bdesc_set; i < ARRAY_SIZE (bdesc_set); i++, d++)
9503     if (d->code == fcode)
9504       return frv_expand_set_builtin (d->icode, exp, target);
9505
9506   for (i = 0, d = bdesc_1arg; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
9507     if (d->code == fcode)
9508       return frv_expand_unop_builtin (d->icode, exp, target);
9509
9510   for (i = 0, d = bdesc_2arg; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
9511     if (d->code == fcode)
9512       return frv_expand_binop_builtin (d->icode, exp, target);
9513
9514   for (i = 0, d = bdesc_cut; i < ARRAY_SIZE (bdesc_cut); i++, d++)
9515     if (d->code == fcode)
9516       return frv_expand_cut_builtin (d->icode, exp, target);
9517
9518   for (i = 0, d = bdesc_2argimm; i < ARRAY_SIZE (bdesc_2argimm); i++, d++)
9519     if (d->code == fcode)
9520       return frv_expand_binopimm_builtin (d->icode, exp, target);
9521
9522   for (i = 0, d = bdesc_void2arg; i < ARRAY_SIZE (bdesc_void2arg); i++, d++)
9523     if (d->code == fcode)
9524       return frv_expand_voidbinop_builtin (d->icode, exp);
9525
9526   for (i = 0, d = bdesc_void3arg; i < ARRAY_SIZE (bdesc_void3arg); i++, d++)
9527     if (d->code == fcode)
9528       return frv_expand_voidtriop_builtin (d->icode, exp);
9529
9530   for (i = 0, d = bdesc_voidacc; i < ARRAY_SIZE (bdesc_voidacc); i++, d++)
9531     if (d->code == fcode)
9532       return frv_expand_voidaccop_builtin (d->icode, exp);
9533
9534   for (i = 0, d = bdesc_int_void2arg;
9535        i < ARRAY_SIZE (bdesc_int_void2arg); i++, d++)
9536     if (d->code == fcode)
9537       return frv_expand_int_void2arg (d->icode, exp);
9538
9539   for (i = 0, d = bdesc_prefetches;
9540        i < ARRAY_SIZE (bdesc_prefetches); i++, d++)
9541     if (d->code == fcode)
9542       return frv_expand_prefetches (d->icode, exp);
9543
9544   for (i = 0, d = bdesc_loads; i < ARRAY_SIZE (bdesc_loads); i++, d++)
9545     if (d->code == fcode)
9546       return frv_expand_load_builtin (d->icode, TYPE_MODE (TREE_TYPE (exp)),
9547                                       exp, target);
9548
9549   for (i = 0, d = bdesc_stores; i < ARRAY_SIZE (bdesc_stores); i++, d++)
9550     if (d->code == fcode)
9551       return frv_expand_store_builtin (d->icode, exp);
9552
9553   return 0;
9554 }
9555
9556 static bool
9557 frv_in_small_data_p (const_tree decl)
9558 {
9559   HOST_WIDE_INT size;
9560   const_tree section_name;
9561
9562   /* Don't apply the -G flag to internal compiler structures.  We
9563      should leave such structures in the main data section, partly
9564      for efficiency and partly because the size of some of them
9565      (such as C++ typeinfos) is not known until later.  */
9566   if (TREE_CODE (decl) != VAR_DECL || DECL_ARTIFICIAL (decl))
9567     return false;
9568
9569   /* If we already know which section the decl should be in, see if
9570      it's a small data section.  */
9571   section_name = DECL_SECTION_NAME (decl);
9572   if (section_name)
9573     {
9574       gcc_assert (TREE_CODE (section_name) == STRING_CST);
9575       if (frv_string_begins_with (section_name, ".sdata"))
9576         return true;
9577       if (frv_string_begins_with (section_name, ".sbss"))
9578         return true;
9579       return false;
9580     }
9581
9582   size = int_size_in_bytes (TREE_TYPE (decl));
9583   if (size > 0 && size <= g_switch_value)
9584     return true;
9585
9586   return false;
9587 }
9588 \f
9589 static bool
9590 frv_rtx_costs (rtx x,
9591                int code ATTRIBUTE_UNUSED,
9592                int outer_code ATTRIBUTE_UNUSED,
9593                int *total,
9594                bool speed ATTRIBUTE_UNUSED)
9595 {
9596   if (outer_code == MEM)
9597     {
9598       /* Don't differentiate between memory addresses.  All the ones
9599          we accept have equal cost.  */
9600       *total = COSTS_N_INSNS (0);
9601       return true;
9602     }
9603
9604   switch (code)
9605     {
9606     case CONST_INT:
9607       /* Make 12-bit integers really cheap.  */
9608       if (IN_RANGE_P (INTVAL (x), -2048, 2047))
9609         {
9610           *total = 0;
9611           return true;
9612         }
9613       /* Fall through.  */
9614
9615     case CONST:
9616     case LABEL_REF:
9617     case SYMBOL_REF:
9618     case CONST_DOUBLE:
9619       *total = COSTS_N_INSNS (2);
9620       return true;
9621
9622     case PLUS:
9623     case MINUS:
9624     case AND:
9625     case IOR:
9626     case XOR:
9627     case ASHIFT:
9628     case ASHIFTRT:
9629     case LSHIFTRT:
9630     case NOT:
9631     case NEG:
9632     case COMPARE:
9633       if (GET_MODE (x) == SImode)
9634         *total = COSTS_N_INSNS (1);
9635       else if (GET_MODE (x) == DImode)
9636         *total = COSTS_N_INSNS (2);
9637       else
9638         *total = COSTS_N_INSNS (3);
9639       return true;
9640
9641     case MULT:
9642       if (GET_MODE (x) == SImode)
9643         *total = COSTS_N_INSNS (2);
9644       else
9645         *total = COSTS_N_INSNS (6);     /* guess */
9646       return true;
9647
9648     case DIV:
9649     case UDIV:
9650     case MOD:
9651     case UMOD:
9652       *total = COSTS_N_INSNS (18);
9653       return true;
9654
9655     case MEM:
9656       *total = COSTS_N_INSNS (3);
9657       return true;
9658
9659     default:
9660       return false;
9661     }
9662 }
9663 \f
9664 static void
9665 frv_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
9666 {
9667   switch_to_section (ctors_section);
9668   assemble_align (POINTER_SIZE);
9669   if (TARGET_FDPIC)
9670     {
9671       int ok = frv_assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, 1);
9672
9673       gcc_assert (ok);
9674       return;
9675     }
9676   assemble_integer_with_op ("\t.picptr\t", symbol);
9677 }
9678
9679 static void
9680 frv_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
9681 {
9682   switch_to_section (dtors_section);
9683   assemble_align (POINTER_SIZE);
9684   if (TARGET_FDPIC)
9685     {
9686       int ok = frv_assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, 1);
9687
9688       gcc_assert (ok);
9689       return;
9690     }
9691   assemble_integer_with_op ("\t.picptr\t", symbol);
9692 }
9693
9694 /* Worker function for TARGET_STRUCT_VALUE_RTX.  */
9695
9696 static rtx
9697 frv_struct_value_rtx (tree fntype ATTRIBUTE_UNUSED,
9698                       int incoming ATTRIBUTE_UNUSED)
9699 {
9700   return gen_rtx_REG (Pmode, FRV_STRUCT_VALUE_REGNUM);
9701 }
9702
9703 #define TLS_BIAS (2048 - 16)
9704
9705 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
9706    We need to emit DTP-relative relocations.  */
9707
9708 static void
9709 frv_output_dwarf_dtprel (FILE *file, int size, rtx x)
9710 {
9711   gcc_assert (size == 4);
9712   fputs ("\t.picptr\ttlsmoff(", file);
9713   /* We want the unbiased TLS offset, so add the bias to the
9714      expression, such that the implicit biasing cancels out.  */
9715   output_addr_const (file, plus_constant (x, TLS_BIAS));
9716   fputs (")", file);
9717 }
9718
9719 #include "gt-frv.h"