OSDN Git Service

575b328fc8273bdde5bf9bd16ae2514b97603f84
[pf3gnuchains/gcc-fork.git] / gcc / config / mips / mips.c
1 /* Subroutines used for MIPS code generation.
2    Copyright (C) 1989, 1990, 1991, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 
4    Free Software Foundation, Inc.
5    Contributed by A. Lichnewsky, lich@inria.inria.fr.
6    Changes by Michael Meissner, meissner@osf.org.
7    64-bit r4000 support by Ian Lance Taylor, ian@cygnus.com, and
8    Brendan Eich, brendan@microunity.com.
9
10 This file is part of GCC.
11
12 GCC is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2, or (at your option)
15 any later version.
16
17 GCC is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING.  If not, write to
24 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
25 Boston, MA 02110-1301, USA.  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include <signal.h>
32 #include "rtl.h"
33 #include "regs.h"
34 #include "hard-reg-set.h"
35 #include "real.h"
36 #include "insn-config.h"
37 #include "conditions.h"
38 #include "insn-attr.h"
39 #include "recog.h"
40 #include "toplev.h"
41 #include "output.h"
42 #include "tree.h"
43 #include "function.h"
44 #include "expr.h"
45 #include "optabs.h"
46 #include "flags.h"
47 #include "reload.h"
48 #include "tm_p.h"
49 #include "ggc.h"
50 #include "gstab.h"
51 #include "hashtab.h"
52 #include "debug.h"
53 #include "target.h"
54 #include "target-def.h"
55 #include "integrate.h"
56 #include "langhooks.h"
57 #include "cfglayout.h"
58 #include "sched-int.h"
59 #include "tree-gimple.h"
60 #include "bitmap.h"
61
62 /* True if X is an unspec wrapper around a SYMBOL_REF or LABEL_REF.  */
63 #define UNSPEC_ADDRESS_P(X)                                     \
64   (GET_CODE (X) == UNSPEC                                       \
65    && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST                       \
66    && XINT (X, 1) < UNSPEC_ADDRESS_FIRST + NUM_SYMBOL_TYPES)
67
68 /* Extract the symbol or label from UNSPEC wrapper X.  */
69 #define UNSPEC_ADDRESS(X) \
70   XVECEXP (X, 0, 0)
71
72 /* Extract the symbol type from UNSPEC wrapper X.  */
73 #define UNSPEC_ADDRESS_TYPE(X) \
74   ((enum mips_symbol_type) (XINT (X, 1) - UNSPEC_ADDRESS_FIRST))
75
76 /* The maximum distance between the top of the stack frame and the
77    value $sp has when we save and restore registers.
78
79    The value for normal-mode code must be a SMALL_OPERAND and must
80    preserve the maximum stack alignment.  We therefore use a value
81    of 0x7ff0 in this case.
82
83    MIPS16e SAVE and RESTORE instructions can adjust the stack pointer by
84    up to 0x7f8 bytes and can usually save or restore all the registers
85    that we need to save or restore.  (Note that we can only use these
86    instructions for o32, for which the stack alignment is 8 bytes.)
87
88    We use a maximum gap of 0x100 or 0x400 for MIPS16 code when SAVE and
89    RESTORE are not available.  We can then use unextended instructions
90    to save and restore registers, and to allocate and deallocate the top
91    part of the frame.  */
92 #define MIPS_MAX_FIRST_STACK_STEP                                       \
93   (!TARGET_MIPS16 ? 0x7ff0                                              \
94    : GENERATE_MIPS16E_SAVE_RESTORE ? 0x7f8                              \
95    : TARGET_64BIT ? 0x100 : 0x400)
96
97 /* True if INSN is a mips.md pattern or asm statement.  */
98 #define USEFUL_INSN_P(INSN)                                             \
99   (INSN_P (INSN)                                                        \
100    && GET_CODE (PATTERN (INSN)) != USE                                  \
101    && GET_CODE (PATTERN (INSN)) != CLOBBER                              \
102    && GET_CODE (PATTERN (INSN)) != ADDR_VEC                             \
103    && GET_CODE (PATTERN (INSN)) != ADDR_DIFF_VEC)
104
105 /* If INSN is a delayed branch sequence, return the first instruction
106    in the sequence, otherwise return INSN itself.  */
107 #define SEQ_BEGIN(INSN)                                                 \
108   (INSN_P (INSN) && GET_CODE (PATTERN (INSN)) == SEQUENCE               \
109    ? XVECEXP (PATTERN (INSN), 0, 0)                                     \
110    : (INSN))
111
112 /* Likewise for the last instruction in a delayed branch sequence.  */
113 #define SEQ_END(INSN)                                                   \
114   (INSN_P (INSN) && GET_CODE (PATTERN (INSN)) == SEQUENCE               \
115    ? XVECEXP (PATTERN (INSN), 0, XVECLEN (PATTERN (INSN), 0) - 1)       \
116    : (INSN))
117
118 /* Execute the following loop body with SUBINSN set to each instruction
119    between SEQ_BEGIN (INSN) and SEQ_END (INSN) inclusive.  */
120 #define FOR_EACH_SUBINSN(SUBINSN, INSN)                                 \
121   for ((SUBINSN) = SEQ_BEGIN (INSN);                                    \
122        (SUBINSN) != NEXT_INSN (SEQ_END (INSN));                         \
123        (SUBINSN) = NEXT_INSN (SUBINSN))
124
125 /* True if bit BIT is set in VALUE.  */
126 #define BITSET_P(VALUE, BIT) (((VALUE) & (1 << (BIT))) != 0)
127
128 /* Classifies an address.
129
130    ADDRESS_REG
131        A natural register + offset address.  The register satisfies
132        mips_valid_base_register_p and the offset is a const_arith_operand.
133
134    ADDRESS_LO_SUM
135        A LO_SUM rtx.  The first operand is a valid base register and
136        the second operand is a symbolic address.
137
138    ADDRESS_CONST_INT
139        A signed 16-bit constant address.
140
141    ADDRESS_SYMBOLIC:
142        A constant symbolic address (equivalent to CONSTANT_SYMBOLIC).  */
143 enum mips_address_type {
144   ADDRESS_REG,
145   ADDRESS_LO_SUM,
146   ADDRESS_CONST_INT,
147   ADDRESS_SYMBOLIC
148 };
149
150 /* Classifies the prototype of a builtin function.  */
151 enum mips_function_type
152 {
153   MIPS_V2SF_FTYPE_V2SF,
154   MIPS_V2SF_FTYPE_V2SF_V2SF,
155   MIPS_V2SF_FTYPE_V2SF_V2SF_INT,
156   MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,
157   MIPS_V2SF_FTYPE_SF_SF,
158   MIPS_INT_FTYPE_V2SF_V2SF,
159   MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,
160   MIPS_INT_FTYPE_SF_SF,
161   MIPS_INT_FTYPE_DF_DF,
162   MIPS_SF_FTYPE_V2SF,
163   MIPS_SF_FTYPE_SF,
164   MIPS_SF_FTYPE_SF_SF,
165   MIPS_DF_FTYPE_DF,
166   MIPS_DF_FTYPE_DF_DF,
167
168   /* For MIPS DSP ASE  */
169   MIPS_DI_FTYPE_DI_SI,
170   MIPS_DI_FTYPE_DI_SI_SI,
171   MIPS_DI_FTYPE_DI_V2HI_V2HI,
172   MIPS_DI_FTYPE_DI_V4QI_V4QI,
173   MIPS_SI_FTYPE_DI_SI,
174   MIPS_SI_FTYPE_PTR_SI,
175   MIPS_SI_FTYPE_SI,
176   MIPS_SI_FTYPE_SI_SI,
177   MIPS_SI_FTYPE_V2HI,
178   MIPS_SI_FTYPE_V2HI_V2HI,
179   MIPS_SI_FTYPE_V4QI,
180   MIPS_SI_FTYPE_V4QI_V4QI,
181   MIPS_SI_FTYPE_VOID,
182   MIPS_V2HI_FTYPE_SI,
183   MIPS_V2HI_FTYPE_SI_SI,
184   MIPS_V2HI_FTYPE_V2HI,
185   MIPS_V2HI_FTYPE_V2HI_SI,
186   MIPS_V2HI_FTYPE_V2HI_V2HI,
187   MIPS_V2HI_FTYPE_V4QI,
188   MIPS_V2HI_FTYPE_V4QI_V2HI,
189   MIPS_V4QI_FTYPE_SI,
190   MIPS_V4QI_FTYPE_V2HI_V2HI,
191   MIPS_V4QI_FTYPE_V4QI_SI,
192   MIPS_V4QI_FTYPE_V4QI_V4QI,
193   MIPS_VOID_FTYPE_SI_SI,
194   MIPS_VOID_FTYPE_V2HI_V2HI,
195   MIPS_VOID_FTYPE_V4QI_V4QI,
196
197   /* For MIPS DSP REV 2 ASE.  */
198   MIPS_V4QI_FTYPE_V4QI,
199   MIPS_SI_FTYPE_SI_SI_SI,
200   MIPS_DI_FTYPE_DI_USI_USI,
201   MIPS_DI_FTYPE_SI_SI,
202   MIPS_DI_FTYPE_USI_USI,
203   MIPS_V2HI_FTYPE_SI_SI_SI,
204
205   /* The last type.  */
206   MIPS_MAX_FTYPE_MAX
207 };
208
209 /* Specifies how a builtin function should be converted into rtl.  */
210 enum mips_builtin_type
211 {
212   /* The builtin corresponds directly to an .md pattern.  The return
213      value is mapped to operand 0 and the arguments are mapped to
214      operands 1 and above.  */
215   MIPS_BUILTIN_DIRECT,
216
217   /* The builtin corresponds directly to an .md pattern.  There is no return
218      value and the arguments are mapped to operands 0 and above.  */
219   MIPS_BUILTIN_DIRECT_NO_TARGET,
220
221   /* The builtin corresponds to a comparison instruction followed by
222      a mips_cond_move_tf_ps pattern.  The first two arguments are the
223      values to compare and the second two arguments are the vector
224      operands for the movt.ps or movf.ps instruction (in assembly order).  */
225   MIPS_BUILTIN_MOVF,
226   MIPS_BUILTIN_MOVT,
227
228   /* The builtin corresponds to a V2SF comparison instruction.  Operand 0
229      of this instruction is the result of the comparison, which has mode
230      CCV2 or CCV4.  The function arguments are mapped to operands 1 and
231      above.  The function's return value is an SImode boolean that is
232      true under the following conditions:
233
234      MIPS_BUILTIN_CMP_ANY: one of the registers is true
235      MIPS_BUILTIN_CMP_ALL: all of the registers are true
236      MIPS_BUILTIN_CMP_LOWER: the first register is true
237      MIPS_BUILTIN_CMP_UPPER: the second register is true.  */
238   MIPS_BUILTIN_CMP_ANY,
239   MIPS_BUILTIN_CMP_ALL,
240   MIPS_BUILTIN_CMP_UPPER,
241   MIPS_BUILTIN_CMP_LOWER,
242
243   /* As above, but the instruction only sets a single $fcc register.  */
244   MIPS_BUILTIN_CMP_SINGLE,
245
246   /* For generating bposge32 branch instructions in MIPS32 DSP ASE.  */
247   MIPS_BUILTIN_BPOSGE32
248 };
249
250 /* Invokes MACRO (COND) for each c.cond.fmt condition.  */
251 #define MIPS_FP_CONDITIONS(MACRO) \
252   MACRO (f),    \
253   MACRO (un),   \
254   MACRO (eq),   \
255   MACRO (ueq),  \
256   MACRO (olt),  \
257   MACRO (ult),  \
258   MACRO (ole),  \
259   MACRO (ule),  \
260   MACRO (sf),   \
261   MACRO (ngle), \
262   MACRO (seq),  \
263   MACRO (ngl),  \
264   MACRO (lt),   \
265   MACRO (nge),  \
266   MACRO (le),   \
267   MACRO (ngt)
268
269 /* Enumerates the codes above as MIPS_FP_COND_<X>.  */
270 #define DECLARE_MIPS_COND(X) MIPS_FP_COND_ ## X
271 enum mips_fp_condition {
272   MIPS_FP_CONDITIONS (DECLARE_MIPS_COND)
273 };
274
275 /* Index X provides the string representation of MIPS_FP_COND_<X>.  */
276 #define STRINGIFY(X) #X
277 static const char *const mips_fp_conditions[] = {
278   MIPS_FP_CONDITIONS (STRINGIFY)
279 };
280
281 /* A function to save or store a register.  The first argument is the
282    register and the second is the stack slot.  */
283 typedef void (*mips_save_restore_fn) (rtx, rtx);
284
285 struct mips16_constant;
286 struct mips_arg_info;
287 struct mips_address_info;
288 struct mips_integer_op;
289 struct mips_sim;
290
291 static enum mips_symbol_type mips_classify_symbol (rtx);
292 static bool mips_valid_base_register_p (rtx, enum machine_mode, int);
293 static bool mips_symbolic_address_p (enum mips_symbol_type, enum machine_mode);
294 static bool mips_classify_address (struct mips_address_info *, rtx,
295                                    enum machine_mode, int);
296 static bool mips_cannot_force_const_mem (rtx);
297 static bool mips_use_blocks_for_constant_p (enum machine_mode, rtx);
298 static int mips_symbol_insns (enum mips_symbol_type);
299 static bool mips16_unextended_reference_p (enum machine_mode mode, rtx, rtx);
300 static rtx mips_force_temporary (rtx, rtx);
301 static rtx mips_unspec_offset_high (rtx, rtx, rtx, enum mips_symbol_type);
302 static rtx mips_add_offset (rtx, rtx, HOST_WIDE_INT);
303 static unsigned int mips_build_shift (struct mips_integer_op *, HOST_WIDE_INT);
304 static unsigned int mips_build_lower (struct mips_integer_op *,
305                                       unsigned HOST_WIDE_INT);
306 static unsigned int mips_build_integer (struct mips_integer_op *,
307                                         unsigned HOST_WIDE_INT);
308 static void mips_legitimize_const_move (enum machine_mode, rtx, rtx);
309 static int m16_check_op (rtx, int, int, int);
310 static bool mips_rtx_costs (rtx, int, int, int *);
311 static int mips_address_cost (rtx);
312 static void mips_emit_compare (enum rtx_code *, rtx *, rtx *, bool);
313 static void mips_load_call_address (rtx, rtx, int);
314 static bool mips_function_ok_for_sibcall (tree, tree);
315 static void mips_block_move_straight (rtx, rtx, HOST_WIDE_INT);
316 static void mips_adjust_block_mem (rtx, HOST_WIDE_INT, rtx *, rtx *);
317 static void mips_block_move_loop (rtx, rtx, HOST_WIDE_INT);
318 static void mips_arg_info (const CUMULATIVE_ARGS *, enum machine_mode,
319                            tree, int, struct mips_arg_info *);
320 static bool mips_get_unaligned_mem (rtx *, unsigned int, int, rtx *, rtx *);
321 static void mips_set_architecture (const struct mips_cpu_info *);
322 static void mips_set_tune (const struct mips_cpu_info *);
323 static bool mips_handle_option (size_t, const char *, int);
324 static struct machine_function *mips_init_machine_status (void);
325 static void print_operand_reloc (FILE *, rtx, const char **);
326 static void mips_file_start (void);
327 static bool mips_rewrite_small_data_p (rtx);
328 static int mips_small_data_pattern_1 (rtx *, void *);
329 static int mips_rewrite_small_data_1 (rtx *, void *);
330 static bool mips_function_has_gp_insn (void);
331 static unsigned int mips_global_pointer (void);
332 static bool mips_save_reg_p (unsigned int);
333 static void mips_save_restore_reg (enum machine_mode, int, HOST_WIDE_INT,
334                                    mips_save_restore_fn);
335 static void mips_for_each_saved_reg (HOST_WIDE_INT, mips_save_restore_fn);
336 static void mips_output_cplocal (void);
337 static void mips_emit_loadgp (void);
338 static void mips_output_function_prologue (FILE *, HOST_WIDE_INT);
339 static void mips_set_frame_expr (rtx);
340 static rtx mips_frame_set (rtx, rtx);
341 static void mips_save_reg (rtx, rtx);
342 static void mips_output_function_epilogue (FILE *, HOST_WIDE_INT);
343 static void mips_restore_reg (rtx, rtx);
344 static void mips_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
345                                   HOST_WIDE_INT, tree);
346 static int symbolic_expression_p (rtx);
347 static section *mips_select_rtx_section (enum machine_mode, rtx,
348                                          unsigned HOST_WIDE_INT);
349 static section *mips_function_rodata_section (tree);
350 static bool mips_in_small_data_p (tree);
351 static bool mips_use_anchors_for_symbol_p (rtx);
352 static int mips_fpr_return_fields (tree, tree *);
353 static bool mips_return_in_msb (tree);
354 static rtx mips_return_fpr_pair (enum machine_mode mode,
355                                  enum machine_mode mode1, HOST_WIDE_INT,
356                                  enum machine_mode mode2, HOST_WIDE_INT);
357 static rtx mips16_gp_pseudo_reg (void);
358 static void mips16_fp_args (FILE *, int, int);
359 static void build_mips16_function_stub (FILE *);
360 static rtx dump_constants_1 (enum machine_mode, rtx, rtx);
361 static void dump_constants (struct mips16_constant *, rtx);
362 static int mips16_insn_length (rtx);
363 static int mips16_rewrite_pool_refs (rtx *, void *);
364 static void mips16_lay_out_constants (void);
365 static void mips_sim_reset (struct mips_sim *);
366 static void mips_sim_init (struct mips_sim *, state_t);
367 static void mips_sim_next_cycle (struct mips_sim *);
368 static void mips_sim_wait_reg (struct mips_sim *, rtx, rtx);
369 static int mips_sim_wait_regs_2 (rtx *, void *);
370 static void mips_sim_wait_regs_1 (rtx *, void *);
371 static void mips_sim_wait_regs (struct mips_sim *, rtx);
372 static void mips_sim_wait_units (struct mips_sim *, rtx);
373 static void mips_sim_wait_insn (struct mips_sim *, rtx);
374 static void mips_sim_record_set (rtx, rtx, void *);
375 static void mips_sim_issue_insn (struct mips_sim *, rtx);
376 static void mips_sim_issue_nop (struct mips_sim *);
377 static void mips_sim_finish_insn (struct mips_sim *, rtx);
378 static void vr4130_avoid_branch_rt_conflict (rtx);
379 static void vr4130_align_insns (void);
380 static void mips_avoid_hazard (rtx, rtx, int *, rtx *, rtx);
381 static void mips_avoid_hazards (void);
382 static void mips_reorg (void);
383 static bool mips_strict_matching_cpu_name_p (const char *, const char *);
384 static bool mips_matching_cpu_name_p (const char *, const char *);
385 static const struct mips_cpu_info *mips_parse_cpu (const char *);
386 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
387 static bool mips_return_in_memory (tree, tree);
388 static bool mips_strict_argument_naming (CUMULATIVE_ARGS *);
389 static void mips_macc_chains_record (rtx);
390 static void mips_macc_chains_reorder (rtx *, int);
391 static void vr4130_true_reg_dependence_p_1 (rtx, rtx, void *);
392 static bool vr4130_true_reg_dependence_p (rtx);
393 static bool vr4130_swap_insns_p (rtx, rtx);
394 static void vr4130_reorder (rtx *, int);
395 static void mips_promote_ready (rtx *, int, int);
396 static int mips_sched_reorder (FILE *, int, rtx *, int *, int);
397 static int mips_variable_issue (FILE *, int, rtx, int);
398 static int mips_adjust_cost (rtx, rtx, rtx, int);
399 static int mips_issue_rate (void);
400 static int mips_multipass_dfa_lookahead (void);
401 static void mips_init_libfuncs (void);
402 static void mips_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
403                                          tree, int *, int);
404 static tree mips_build_builtin_va_list (void);
405 static tree mips_gimplify_va_arg_expr (tree, tree, tree *, tree *);
406 static bool mips_pass_by_reference (CUMULATIVE_ARGS *, enum machine_mode mode,
407                                     tree, bool);
408 static bool mips_callee_copies (CUMULATIVE_ARGS *, enum machine_mode mode,
409                                 tree, bool);
410 static int mips_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode mode,
411                                    tree, bool);
412 static bool mips_valid_pointer_mode (enum machine_mode);
413 static bool mips_vector_mode_supported_p (enum machine_mode);
414 static rtx mips_prepare_builtin_arg (enum insn_code, unsigned int, tree, unsigned int);
415 static rtx mips_prepare_builtin_target (enum insn_code, unsigned int, rtx);
416 static rtx mips_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
417 static void mips_init_builtins (void);
418 static rtx mips_expand_builtin_direct (enum insn_code, rtx, tree, bool);
419 static rtx mips_expand_builtin_movtf (enum mips_builtin_type,
420                                       enum insn_code, enum mips_fp_condition,
421                                       rtx, tree);
422 static rtx mips_expand_builtin_compare (enum mips_builtin_type,
423                                         enum insn_code, enum mips_fp_condition,
424                                         rtx, tree);
425 static rtx mips_expand_builtin_bposge (enum mips_builtin_type, rtx);
426 static void mips_encode_section_info (tree, rtx, int);
427 static void mips_extra_live_on_entry (bitmap);
428 static int mips_comp_type_attributes (tree, tree);
429 static int mips_mode_rep_extended (enum machine_mode, enum machine_mode);
430 static bool mips_offset_within_alignment_p (rtx, HOST_WIDE_INT);
431
432 /* Structure to be filled in by compute_frame_size with register
433    save masks, and offsets for the current function.  */
434
435 struct mips_frame_info GTY(())
436 {
437   HOST_WIDE_INT total_size;     /* # bytes that the entire frame takes up */
438   HOST_WIDE_INT var_size;       /* # bytes that variables take up */
439   HOST_WIDE_INT args_size;      /* # bytes that outgoing arguments take up */
440   HOST_WIDE_INT cprestore_size; /* # bytes that the .cprestore slot takes up */
441   HOST_WIDE_INT gp_reg_size;    /* # bytes needed to store gp regs */
442   HOST_WIDE_INT fp_reg_size;    /* # bytes needed to store fp regs */
443   unsigned int mask;            /* mask of saved gp registers */
444   unsigned int fmask;           /* mask of saved fp registers */
445   HOST_WIDE_INT gp_save_offset; /* offset from vfp to store gp registers */
446   HOST_WIDE_INT fp_save_offset; /* offset from vfp to store fp registers */
447   HOST_WIDE_INT gp_sp_offset;   /* offset from new sp to store gp registers */
448   HOST_WIDE_INT fp_sp_offset;   /* offset from new sp to store fp registers */
449   bool initialized;             /* true if frame size already calculated */
450   int num_gp;                   /* number of gp registers saved */
451   int num_fp;                   /* number of fp registers saved */
452 };
453
454 struct machine_function GTY(()) {
455   /* Pseudo-reg holding the value of $28 in a mips16 function which
456      refers to GP relative global variables.  */
457   rtx mips16_gp_pseudo_rtx;
458
459   /* The number of extra stack bytes taken up by register varargs.
460      This area is allocated by the callee at the very top of the frame.  */
461   int varargs_size;
462
463   /* Current frame information, calculated by compute_frame_size.  */
464   struct mips_frame_info frame;
465
466   /* The register to use as the global pointer within this function.  */
467   unsigned int global_pointer;
468
469   /* True if mips_adjust_insn_length should ignore an instruction's
470      hazard attribute.  */
471   bool ignore_hazard_length_p;
472
473   /* True if the whole function is suitable for .set noreorder and
474      .set nomacro.  */
475   bool all_noreorder_p;
476
477   /* True if the function is known to have an instruction that needs $gp.  */
478   bool has_gp_insn_p;
479 };
480
481 /* Information about a single argument.  */
482 struct mips_arg_info
483 {
484   /* True if the argument is passed in a floating-point register, or
485      would have been if we hadn't run out of registers.  */
486   bool fpr_p;
487
488   /* The number of words passed in registers, rounded up.  */
489   unsigned int reg_words;
490
491   /* For EABI, the offset of the first register from GP_ARG_FIRST or
492      FP_ARG_FIRST.  For other ABIs, the offset of the first register from
493      the start of the ABI's argument structure (see the CUMULATIVE_ARGS
494      comment for details).
495
496      The value is MAX_ARGS_IN_REGISTERS if the argument is passed entirely
497      on the stack.  */
498   unsigned int reg_offset;
499
500   /* The number of words that must be passed on the stack, rounded up.  */
501   unsigned int stack_words;
502
503   /* The offset from the start of the stack overflow area of the argument's
504      first stack word.  Only meaningful when STACK_WORDS is nonzero.  */
505   unsigned int stack_offset;
506 };
507
508
509 /* Information about an address described by mips_address_type.
510
511    ADDRESS_CONST_INT
512        No fields are used.
513
514    ADDRESS_REG
515        REG is the base register and OFFSET is the constant offset.
516
517    ADDRESS_LO_SUM
518        REG is the register that contains the high part of the address,
519        OFFSET is the symbolic address being referenced and SYMBOL_TYPE
520        is the type of OFFSET's symbol.
521
522    ADDRESS_SYMBOLIC
523        SYMBOL_TYPE is the type of symbol being referenced.  */
524
525 struct mips_address_info
526 {
527   enum mips_address_type type;
528   rtx reg;
529   rtx offset;
530   enum mips_symbol_type symbol_type;
531 };
532
533
534 /* One stage in a constant building sequence.  These sequences have
535    the form:
536
537         A = VALUE[0]
538         A = A CODE[1] VALUE[1]
539         A = A CODE[2] VALUE[2]
540         ...
541
542    where A is an accumulator, each CODE[i] is a binary rtl operation
543    and each VALUE[i] is a constant integer.  */
544 struct mips_integer_op {
545   enum rtx_code code;
546   unsigned HOST_WIDE_INT value;
547 };
548
549
550 /* The largest number of operations needed to load an integer constant.
551    The worst accepted case for 64-bit constants is LUI,ORI,SLL,ORI,SLL,ORI.
552    When the lowest bit is clear, we can try, but reject a sequence with
553    an extra SLL at the end.  */
554 #define MIPS_MAX_INTEGER_OPS 7
555
556 /* Information about a MIPS16e SAVE or RESTORE instruction.  */
557 struct mips16e_save_restore_info {
558   /* The number of argument registers saved by a SAVE instruction.
559      0 for RESTORE instructions.  */
560   unsigned int nargs;
561
562   /* Bit X is set if the instruction saves or restores GPR X.  */
563   unsigned int mask;
564
565   /* The total number of bytes to allocate.  */
566   HOST_WIDE_INT size;
567 };
568
569 /* Global variables for machine-dependent things.  */
570
571 /* Threshold for data being put into the small data/bss area, instead
572    of the normal data area.  */
573 int mips_section_threshold = -1;
574
575 /* Count the number of .file directives, so that .loc is up to date.  */
576 int num_source_filenames = 0;
577
578 /* Count the number of sdb related labels are generated (to find block
579    start and end boundaries).  */
580 int sdb_label_count = 0;
581
582 /* Next label # for each statement for Silicon Graphics IRIS systems.  */
583 int sym_lineno = 0;
584
585 /* Name of the file containing the current function.  */
586 const char *current_function_file = "";
587
588 /* Number of nested .set noreorder, noat, nomacro, and volatile requests.  */
589 int set_noreorder;
590 int set_noat;
591 int set_nomacro;
592 int set_volatile;
593
594 /* The next branch instruction is a branch likely, not branch normal.  */
595 int mips_branch_likely;
596
597 /* The operands passed to the last cmpMM expander.  */
598 rtx cmp_operands[2];
599
600 /* The target cpu for code generation.  */
601 enum processor_type mips_arch;
602 const struct mips_cpu_info *mips_arch_info;
603
604 /* The target cpu for optimization and scheduling.  */
605 enum processor_type mips_tune;
606 const struct mips_cpu_info *mips_tune_info;
607
608 /* Which instruction set architecture to use.  */
609 int mips_isa;
610
611 /* Which ABI to use.  */
612 int mips_abi = MIPS_ABI_DEFAULT;
613
614 /* Cost information to use.  */
615 const struct mips_rtx_cost_data *mips_cost;
616
617 /* Whether we are generating mips16 hard float code.  In mips16 mode
618    we always set TARGET_SOFT_FLOAT; this variable is nonzero if
619    -msoft-float was not specified by the user, which means that we
620    should arrange to call mips32 hard floating point code.  */
621 int mips16_hard_float;
622
623 /* The architecture selected by -mipsN.  */
624 static const struct mips_cpu_info *mips_isa_info;
625
626 /* If TRUE, we split addresses into their high and low parts in the RTL.  */
627 int mips_split_addresses;
628
629 /* Mode used for saving/restoring general purpose registers.  */
630 static enum machine_mode gpr_mode;
631
632 /* Array giving truth value on whether or not a given hard register
633    can support a given mode.  */
634 char mips_hard_regno_mode_ok[(int)MAX_MACHINE_MODE][FIRST_PSEUDO_REGISTER];
635
636 /* List of all MIPS punctuation characters used by print_operand.  */
637 char mips_print_operand_punct[256];
638
639 /* Map GCC register number to debugger register number.  */
640 int mips_dbx_regno[FIRST_PSEUDO_REGISTER];
641
642 /* A copy of the original flag_delayed_branch: see override_options.  */
643 static int mips_flag_delayed_branch;
644
645 static GTY (()) int mips_output_filename_first_time = 1;
646
647 /* mips_split_p[X] is true if symbols of type X can be split by
648    mips_split_symbol().  */
649 bool mips_split_p[NUM_SYMBOL_TYPES];
650
651 /* mips_lo_relocs[X] is the relocation to use when a symbol of type X
652    appears in a LO_SUM.  It can be null if such LO_SUMs aren't valid or
653    if they are matched by a special .md file pattern.  */
654 static const char *mips_lo_relocs[NUM_SYMBOL_TYPES];
655
656 /* Likewise for HIGHs.  */
657 static const char *mips_hi_relocs[NUM_SYMBOL_TYPES];
658
659 /* Map hard register number to register class */
660 const enum reg_class mips_regno_to_class[] =
661 {
662   LEA_REGS,     LEA_REGS,       M16_NA_REGS,    V1_REG,
663   M16_REGS,     M16_REGS,       M16_REGS,       M16_REGS,
664   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
665   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
666   M16_NA_REGS,  M16_NA_REGS,    LEA_REGS,       LEA_REGS,
667   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
668   T_REG,        PIC_FN_ADDR_REG, LEA_REGS,      LEA_REGS,
669   LEA_REGS,     LEA_REGS,       LEA_REGS,       LEA_REGS,
670   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
671   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
672   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
673   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
674   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
675   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
676   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
677   FP_REGS,      FP_REGS,        FP_REGS,        FP_REGS,
678   HI_REG,       LO_REG,         NO_REGS,        ST_REGS,
679   ST_REGS,      ST_REGS,        ST_REGS,        ST_REGS,
680   ST_REGS,      ST_REGS,        ST_REGS,        NO_REGS,
681   NO_REGS,      ALL_REGS,       ALL_REGS,       NO_REGS,
682   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
683   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
684   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
685   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
686   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
687   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
688   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
689   COP0_REGS,    COP0_REGS,      COP0_REGS,      COP0_REGS,
690   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
691   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
692   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
693   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
694   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
695   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
696   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
697   COP2_REGS,    COP2_REGS,      COP2_REGS,      COP2_REGS,
698   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
699   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
700   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
701   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
702   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
703   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
704   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
705   COP3_REGS,    COP3_REGS,      COP3_REGS,      COP3_REGS,
706   DSP_ACC_REGS, DSP_ACC_REGS,   DSP_ACC_REGS,   DSP_ACC_REGS,
707   DSP_ACC_REGS, DSP_ACC_REGS,   ALL_REGS,       ALL_REGS,
708   ALL_REGS,     ALL_REGS,       ALL_REGS,       ALL_REGS
709 };
710
711 /* Table of machine dependent attributes.  */
712 const struct attribute_spec mips_attribute_table[] =
713 {
714   { "long_call",   0, 0, false, true,  true,  NULL },
715   { "far",         0, 0, false, true,  true,  NULL },
716   { "near",        0, 0, false, true,  true,  NULL },
717   { NULL,          0, 0, false, false, false, NULL }
718 };
719 \f
720 /* A table describing all the processors gcc knows about.  Names are
721    matched in the order listed.  The first mention of an ISA level is
722    taken as the canonical name for that ISA.
723
724    To ease comparison, please keep this table in the same order as
725    gas's mips_cpu_info_table[].  */
726 const struct mips_cpu_info mips_cpu_info_table[] = {
727   /* Entries for generic ISAs */
728   { "mips1", PROCESSOR_R3000, 1 },
729   { "mips2", PROCESSOR_R6000, 2 },
730   { "mips3", PROCESSOR_R4000, 3 },
731   { "mips4", PROCESSOR_R8000, 4 },
732   { "mips32", PROCESSOR_4KC, 32 },
733   { "mips32r2", PROCESSOR_M4K, 33 },
734   { "mips64", PROCESSOR_5KC, 64 },
735
736   /* MIPS I */
737   { "r3000", PROCESSOR_R3000, 1 },
738   { "r2000", PROCESSOR_R3000, 1 }, /* = r3000 */
739   { "r3900", PROCESSOR_R3900, 1 },
740
741   /* MIPS II */
742   { "r6000", PROCESSOR_R6000, 2 },
743
744   /* MIPS III */
745   { "r4000", PROCESSOR_R4000, 3 },
746   { "vr4100", PROCESSOR_R4100, 3 },
747   { "vr4111", PROCESSOR_R4111, 3 },
748   { "vr4120", PROCESSOR_R4120, 3 },
749   { "vr4130", PROCESSOR_R4130, 3 },
750   { "vr4300", PROCESSOR_R4300, 3 },
751   { "r4400", PROCESSOR_R4000, 3 }, /* = r4000 */
752   { "r4600", PROCESSOR_R4600, 3 },
753   { "orion", PROCESSOR_R4600, 3 }, /* = r4600 */
754   { "r4650", PROCESSOR_R4650, 3 },
755
756   /* MIPS IV */
757   { "r8000", PROCESSOR_R8000, 4 },
758   { "vr5000", PROCESSOR_R5000, 4 },
759   { "vr5400", PROCESSOR_R5400, 4 },
760   { "vr5500", PROCESSOR_R5500, 4 },
761   { "rm7000", PROCESSOR_R7000, 4 },
762   { "rm9000", PROCESSOR_R9000, 4 },
763
764   /* MIPS32 */
765   { "4kc", PROCESSOR_4KC, 32 },
766   { "4km", PROCESSOR_4KC, 32 }, /* = 4kc */
767   { "4kp", PROCESSOR_4KP, 32 },
768
769   /* MIPS32 Release 2 */
770   { "m4k", PROCESSOR_M4K, 33 },
771   { "4kec", PROCESSOR_4KC, 33 },
772   { "4kem", PROCESSOR_4KC, 33 },
773   { "4kep", PROCESSOR_4KP, 33 },
774   { "24kc", PROCESSOR_24KC, 33 },  /* 24K  no FPU */
775   { "24kf", PROCESSOR_24KF, 33 },  /* 24K 1:2 FPU */
776   { "24kx", PROCESSOR_24KX, 33 },  /* 24K 1:1 FPU */
777   { "24kec", PROCESSOR_24KC, 33 }, /* 24K with DSP */
778   { "24kef", PROCESSOR_24KF, 33 },
779   { "24kex", PROCESSOR_24KX, 33 },
780   { "34kc", PROCESSOR_24KC, 33 },  /* 34K with MT/DSP */
781   { "34kf", PROCESSOR_24KF, 33 },
782   { "34kx", PROCESSOR_24KX, 33 },
783   { "74kc", PROCESSOR_74KC, 33 },
784   { "74kf", PROCESSOR_74KF, 33 },
785   { "74kx", PROCESSOR_74KX, 33 },
786
787   /* MIPS64 */
788   { "5kc", PROCESSOR_5KC, 64 },
789   { "5kf", PROCESSOR_5KF, 64 },
790   { "20kc", PROCESSOR_20KC, 64 },
791   { "sb1", PROCESSOR_SB1, 64 },
792   { "sb1a", PROCESSOR_SB1A, 64 },
793   { "sr71000", PROCESSOR_SR71000, 64 },
794
795   /* End marker */
796   { 0, 0, 0 }
797 };
798
799 /* Default costs. If these are used for a processor we should look
800    up the actual costs.  */
801 #define DEFAULT_COSTS COSTS_N_INSNS (6),  /* fp_add */       \
802                       COSTS_N_INSNS (7),  /* fp_mult_sf */   \
803                       COSTS_N_INSNS (8),  /* fp_mult_df */   \
804                       COSTS_N_INSNS (23), /* fp_div_sf */    \
805                       COSTS_N_INSNS (36), /* fp_div_df */    \
806                       COSTS_N_INSNS (10), /* int_mult_si */  \
807                       COSTS_N_INSNS (10), /* int_mult_di */  \
808                       COSTS_N_INSNS (69), /* int_div_si */   \
809                       COSTS_N_INSNS (69), /* int_div_di */   \
810                                        2, /* branch_cost */  \
811                                        4  /* memory_latency */
812
813 /* Need to replace these with the costs of calling the appropriate
814    libgcc routine.  */
815 #define SOFT_FP_COSTS COSTS_N_INSNS (256), /* fp_add */       \
816                       COSTS_N_INSNS (256), /* fp_mult_sf */   \
817                       COSTS_N_INSNS (256), /* fp_mult_df */   \
818                       COSTS_N_INSNS (256), /* fp_div_sf */    \
819                       COSTS_N_INSNS (256)  /* fp_div_df */
820
821 static struct mips_rtx_cost_data const mips_rtx_cost_optimize_size =
822   {
823       COSTS_N_INSNS (1),            /* fp_add */
824       COSTS_N_INSNS (1),            /* fp_mult_sf */
825       COSTS_N_INSNS (1),            /* fp_mult_df */
826       COSTS_N_INSNS (1),            /* fp_div_sf */
827       COSTS_N_INSNS (1),            /* fp_div_df */
828       COSTS_N_INSNS (1),            /* int_mult_si */
829       COSTS_N_INSNS (1),            /* int_mult_di */
830       COSTS_N_INSNS (1),            /* int_div_si */
831       COSTS_N_INSNS (1),            /* int_div_di */
832                        2,           /* branch_cost */
833                        4            /* memory_latency */
834   };
835
836 static struct mips_rtx_cost_data const mips_rtx_cost_data[PROCESSOR_MAX] =
837   {
838     { /* R3000 */
839       COSTS_N_INSNS (2),            /* fp_add */
840       COSTS_N_INSNS (4),            /* fp_mult_sf */
841       COSTS_N_INSNS (5),            /* fp_mult_df */
842       COSTS_N_INSNS (12),           /* fp_div_sf */
843       COSTS_N_INSNS (19),           /* fp_div_df */
844       COSTS_N_INSNS (12),           /* int_mult_si */
845       COSTS_N_INSNS (12),           /* int_mult_di */
846       COSTS_N_INSNS (35),           /* int_div_si */
847       COSTS_N_INSNS (35),           /* int_div_di */
848                        1,           /* branch_cost */
849                        4            /* memory_latency */
850
851     },
852     { /* 4KC */
853       SOFT_FP_COSTS,
854       COSTS_N_INSNS (6),            /* int_mult_si */
855       COSTS_N_INSNS (6),            /* int_mult_di */
856       COSTS_N_INSNS (36),           /* int_div_si */
857       COSTS_N_INSNS (36),           /* int_div_di */
858                        1,           /* branch_cost */
859                        4            /* memory_latency */
860     },
861     { /* 4KP */
862       SOFT_FP_COSTS,
863       COSTS_N_INSNS (36),           /* int_mult_si */
864       COSTS_N_INSNS (36),           /* int_mult_di */
865       COSTS_N_INSNS (37),           /* int_div_si */
866       COSTS_N_INSNS (37),           /* int_div_di */
867                        1,           /* branch_cost */
868                        4            /* memory_latency */
869     },
870     { /* 5KC */
871       SOFT_FP_COSTS,
872       COSTS_N_INSNS (4),            /* int_mult_si */
873       COSTS_N_INSNS (11),           /* int_mult_di */
874       COSTS_N_INSNS (36),           /* int_div_si */
875       COSTS_N_INSNS (68),           /* int_div_di */
876                        1,           /* branch_cost */
877                        4            /* memory_latency */
878     },
879     { /* 5KF */
880       COSTS_N_INSNS (4),            /* fp_add */
881       COSTS_N_INSNS (4),            /* fp_mult_sf */
882       COSTS_N_INSNS (5),            /* fp_mult_df */
883       COSTS_N_INSNS (17),           /* fp_div_sf */
884       COSTS_N_INSNS (32),           /* fp_div_df */
885       COSTS_N_INSNS (4),            /* int_mult_si */
886       COSTS_N_INSNS (11),           /* int_mult_di */
887       COSTS_N_INSNS (36),           /* int_div_si */
888       COSTS_N_INSNS (68),           /* int_div_di */
889                        1,           /* branch_cost */
890                        4            /* memory_latency */
891     },
892     { /* 20KC */
893       DEFAULT_COSTS
894     },
895     { /* 24KC */
896       SOFT_FP_COSTS,
897       COSTS_N_INSNS (5),            /* int_mult_si */
898       COSTS_N_INSNS (5),            /* int_mult_di */
899       COSTS_N_INSNS (41),           /* int_div_si */
900       COSTS_N_INSNS (41),           /* int_div_di */
901                        1,           /* branch_cost */
902                        4            /* memory_latency */
903     },
904     { /* 24KF */
905       COSTS_N_INSNS (8),            /* fp_add */
906       COSTS_N_INSNS (8),            /* fp_mult_sf */
907       COSTS_N_INSNS (10),           /* fp_mult_df */
908       COSTS_N_INSNS (34),           /* fp_div_sf */
909       COSTS_N_INSNS (64),           /* fp_div_df */
910       COSTS_N_INSNS (5),            /* int_mult_si */
911       COSTS_N_INSNS (5),            /* int_mult_di */
912       COSTS_N_INSNS (41),           /* int_div_si */
913       COSTS_N_INSNS (41),           /* int_div_di */
914                        1,           /* branch_cost */
915                        4            /* memory_latency */
916     },
917     { /* 24KX */
918       COSTS_N_INSNS (4),            /* fp_add */
919       COSTS_N_INSNS (4),            /* fp_mult_sf */
920       COSTS_N_INSNS (5),            /* fp_mult_df */
921       COSTS_N_INSNS (17),           /* fp_div_sf */
922       COSTS_N_INSNS (32),           /* fp_div_df */
923       COSTS_N_INSNS (5),            /* int_mult_si */
924       COSTS_N_INSNS (5),            /* int_mult_di */
925       COSTS_N_INSNS (41),           /* int_div_si */
926       COSTS_N_INSNS (41),           /* int_div_di */
927                        1,           /* branch_cost */
928                        4            /* memory_latency */
929     },
930     { /* 74KC */
931       SOFT_FP_COSTS,
932       COSTS_N_INSNS (5),            /* int_mult_si */
933       COSTS_N_INSNS (5),            /* int_mult_di */
934       COSTS_N_INSNS (41),           /* int_div_si */
935       COSTS_N_INSNS (41),           /* int_div_di */
936                        1,           /* branch_cost */
937                        4            /* memory_latency */
938     },
939     { /* 74KF */
940       COSTS_N_INSNS (8),            /* fp_add */
941       COSTS_N_INSNS (8),            /* fp_mult_sf */
942       COSTS_N_INSNS (10),           /* fp_mult_df */
943       COSTS_N_INSNS (34),           /* fp_div_sf */
944       COSTS_N_INSNS (64),           /* fp_div_df */
945       COSTS_N_INSNS (5),            /* int_mult_si */
946       COSTS_N_INSNS (5),            /* int_mult_di */
947       COSTS_N_INSNS (41),           /* int_div_si */
948       COSTS_N_INSNS (41),           /* int_div_di */
949                        1,           /* branch_cost */
950                        4            /* memory_latency */
951     },
952     { /* 74KX */
953       COSTS_N_INSNS (4),            /* fp_add */
954       COSTS_N_INSNS (4),            /* fp_mult_sf */
955       COSTS_N_INSNS (5),            /* fp_mult_df */
956       COSTS_N_INSNS (17),           /* fp_div_sf */
957       COSTS_N_INSNS (32),           /* fp_div_df */
958       COSTS_N_INSNS (5),            /* int_mult_si */
959       COSTS_N_INSNS (5),            /* int_mult_di */
960       COSTS_N_INSNS (41),           /* int_div_si */
961       COSTS_N_INSNS (41),           /* int_div_di */
962                        1,           /* branch_cost */
963                        4            /* memory_latency */
964     },
965     { /* M4k */
966       DEFAULT_COSTS
967     },
968     { /* R3900 */
969       COSTS_N_INSNS (2),            /* fp_add */
970       COSTS_N_INSNS (4),            /* fp_mult_sf */
971       COSTS_N_INSNS (5),            /* fp_mult_df */
972       COSTS_N_INSNS (12),           /* fp_div_sf */
973       COSTS_N_INSNS (19),           /* fp_div_df */
974       COSTS_N_INSNS (2),            /* int_mult_si */
975       COSTS_N_INSNS (2),            /* int_mult_di */
976       COSTS_N_INSNS (35),           /* int_div_si */
977       COSTS_N_INSNS (35),           /* int_div_di */
978                        1,           /* branch_cost */
979                        4            /* memory_latency */
980     },
981     { /* R6000 */
982       COSTS_N_INSNS (3),            /* fp_add */
983       COSTS_N_INSNS (5),            /* fp_mult_sf */
984       COSTS_N_INSNS (6),            /* fp_mult_df */
985       COSTS_N_INSNS (15),           /* fp_div_sf */
986       COSTS_N_INSNS (16),           /* fp_div_df */
987       COSTS_N_INSNS (17),           /* int_mult_si */
988       COSTS_N_INSNS (17),           /* int_mult_di */
989       COSTS_N_INSNS (38),           /* int_div_si */
990       COSTS_N_INSNS (38),           /* int_div_di */
991                        2,           /* branch_cost */
992                        6            /* memory_latency */
993     },
994     { /* R4000 */
995        COSTS_N_INSNS (6),           /* fp_add */
996        COSTS_N_INSNS (7),           /* fp_mult_sf */
997        COSTS_N_INSNS (8),           /* fp_mult_df */
998        COSTS_N_INSNS (23),          /* fp_div_sf */
999        COSTS_N_INSNS (36),          /* fp_div_df */
1000        COSTS_N_INSNS (10),          /* int_mult_si */
1001        COSTS_N_INSNS (10),          /* int_mult_di */
1002        COSTS_N_INSNS (69),          /* int_div_si */
1003        COSTS_N_INSNS (69),          /* int_div_di */
1004                         2,          /* branch_cost */
1005                         6           /* memory_latency */
1006     },
1007     { /* R4100 */
1008       DEFAULT_COSTS
1009     },
1010     { /* R4111 */
1011       DEFAULT_COSTS
1012     },
1013     { /* R4120 */
1014       DEFAULT_COSTS
1015     },
1016     { /* R4130 */
1017       /* The only costs that appear to be updated here are
1018          integer multiplication.  */
1019       SOFT_FP_COSTS,
1020       COSTS_N_INSNS (4),            /* int_mult_si */
1021       COSTS_N_INSNS (6),            /* int_mult_di */
1022       COSTS_N_INSNS (69),           /* int_div_si */
1023       COSTS_N_INSNS (69),           /* int_div_di */
1024                        1,           /* branch_cost */
1025                        4            /* memory_latency */
1026     },
1027     { /* R4300 */
1028       DEFAULT_COSTS
1029     },
1030     { /* R4600 */
1031       DEFAULT_COSTS
1032     },
1033     { /* R4650 */
1034       DEFAULT_COSTS
1035     },
1036     { /* R5000 */
1037       COSTS_N_INSNS (6),            /* fp_add */
1038       COSTS_N_INSNS (4),            /* fp_mult_sf */
1039       COSTS_N_INSNS (5),            /* fp_mult_df */
1040       COSTS_N_INSNS (23),           /* fp_div_sf */
1041       COSTS_N_INSNS (36),           /* fp_div_df */
1042       COSTS_N_INSNS (5),            /* int_mult_si */
1043       COSTS_N_INSNS (5),            /* int_mult_di */
1044       COSTS_N_INSNS (36),           /* int_div_si */
1045       COSTS_N_INSNS (36),           /* int_div_di */
1046                        1,           /* branch_cost */
1047                        4            /* memory_latency */
1048     },
1049     { /* R5400 */
1050       COSTS_N_INSNS (6),            /* fp_add */
1051       COSTS_N_INSNS (5),            /* fp_mult_sf */
1052       COSTS_N_INSNS (6),            /* fp_mult_df */
1053       COSTS_N_INSNS (30),           /* fp_div_sf */
1054       COSTS_N_INSNS (59),           /* fp_div_df */
1055       COSTS_N_INSNS (3),            /* int_mult_si */
1056       COSTS_N_INSNS (4),            /* int_mult_di */
1057       COSTS_N_INSNS (42),           /* int_div_si */
1058       COSTS_N_INSNS (74),           /* int_div_di */
1059                        1,           /* branch_cost */
1060                        4            /* memory_latency */
1061     },
1062     { /* R5500 */
1063       COSTS_N_INSNS (6),            /* fp_add */
1064       COSTS_N_INSNS (5),            /* fp_mult_sf */
1065       COSTS_N_INSNS (6),            /* fp_mult_df */
1066       COSTS_N_INSNS (30),           /* fp_div_sf */
1067       COSTS_N_INSNS (59),           /* fp_div_df */
1068       COSTS_N_INSNS (5),            /* int_mult_si */
1069       COSTS_N_INSNS (9),            /* int_mult_di */
1070       COSTS_N_INSNS (42),           /* int_div_si */
1071       COSTS_N_INSNS (74),           /* int_div_di */
1072                        1,           /* branch_cost */
1073                        4            /* memory_latency */
1074     },
1075     { /* R7000 */
1076       /* The only costs that are changed here are
1077          integer multiplication.  */
1078       COSTS_N_INSNS (6),            /* fp_add */
1079       COSTS_N_INSNS (7),            /* fp_mult_sf */
1080       COSTS_N_INSNS (8),            /* fp_mult_df */
1081       COSTS_N_INSNS (23),           /* fp_div_sf */
1082       COSTS_N_INSNS (36),           /* fp_div_df */
1083       COSTS_N_INSNS (5),            /* int_mult_si */
1084       COSTS_N_INSNS (9),            /* int_mult_di */
1085       COSTS_N_INSNS (69),           /* int_div_si */
1086       COSTS_N_INSNS (69),           /* int_div_di */
1087                        1,           /* branch_cost */
1088                        4            /* memory_latency */
1089     },
1090     { /* R8000 */
1091       DEFAULT_COSTS
1092     },
1093     { /* R9000 */
1094       /* The only costs that are changed here are
1095          integer multiplication.  */
1096       COSTS_N_INSNS (6),            /* fp_add */
1097       COSTS_N_INSNS (7),            /* fp_mult_sf */
1098       COSTS_N_INSNS (8),            /* fp_mult_df */
1099       COSTS_N_INSNS (23),           /* fp_div_sf */
1100       COSTS_N_INSNS (36),           /* fp_div_df */
1101       COSTS_N_INSNS (3),            /* int_mult_si */
1102       COSTS_N_INSNS (8),            /* int_mult_di */
1103       COSTS_N_INSNS (69),           /* int_div_si */
1104       COSTS_N_INSNS (69),           /* int_div_di */
1105                        1,           /* branch_cost */
1106                        4            /* memory_latency */
1107     },
1108     { /* SB1 */
1109       /* These costs are the same as the SB-1A below.  */
1110       COSTS_N_INSNS (4),            /* fp_add */
1111       COSTS_N_INSNS (4),            /* fp_mult_sf */
1112       COSTS_N_INSNS (4),            /* fp_mult_df */
1113       COSTS_N_INSNS (24),           /* fp_div_sf */
1114       COSTS_N_INSNS (32),           /* fp_div_df */
1115       COSTS_N_INSNS (3),            /* int_mult_si */
1116       COSTS_N_INSNS (4),            /* int_mult_di */
1117       COSTS_N_INSNS (36),           /* int_div_si */
1118       COSTS_N_INSNS (68),           /* int_div_di */
1119                        1,           /* branch_cost */
1120                        4            /* memory_latency */
1121     },
1122     { /* SB1-A */
1123       /* These costs are the same as the SB-1 above.  */
1124       COSTS_N_INSNS (4),            /* fp_add */
1125       COSTS_N_INSNS (4),            /* fp_mult_sf */
1126       COSTS_N_INSNS (4),            /* fp_mult_df */
1127       COSTS_N_INSNS (24),           /* fp_div_sf */
1128       COSTS_N_INSNS (32),           /* fp_div_df */
1129       COSTS_N_INSNS (3),            /* int_mult_si */
1130       COSTS_N_INSNS (4),            /* int_mult_di */
1131       COSTS_N_INSNS (36),           /* int_div_si */
1132       COSTS_N_INSNS (68),           /* int_div_di */
1133                        1,           /* branch_cost */
1134                        4            /* memory_latency */
1135     },
1136     { /* SR71000 */
1137       DEFAULT_COSTS
1138     },
1139   };
1140
1141 /* If a MIPS16e SAVE or RESTORE instruction saves or restores register
1142    mips16e_s2_s8_regs[X], it must also save the registers in indexes
1143    X + 1 onwards.  Likewise mips16e_a0_a3_regs.  */
1144 static const unsigned char mips16e_s2_s8_regs[] = {
1145   30, 23, 22, 21, 20, 19, 18
1146 };
1147 static const unsigned char mips16e_a0_a3_regs[] = {
1148   4, 5, 6, 7
1149 };
1150
1151 /* A list of the registers that can be saved by the MIPS16e SAVE instruction,
1152    ordered from the uppermost in memory to the lowest in memory.  */
1153 static const unsigned char mips16e_save_restore_regs[] = {
1154   31, 30, 23, 22, 21, 20, 19, 18, 17, 16, 7, 6, 5, 4
1155 };
1156 \f
1157 /* Nonzero if -march should decide the default value of MASK_SOFT_FLOAT.  */
1158 #ifndef MIPS_MARCH_CONTROLS_SOFT_FLOAT
1159 #define MIPS_MARCH_CONTROLS_SOFT_FLOAT 0
1160 #endif
1161 \f
1162 /* Initialize the GCC target structure.  */
1163 #undef TARGET_ASM_ALIGNED_HI_OP
1164 #define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
1165 #undef TARGET_ASM_ALIGNED_SI_OP
1166 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
1167 #undef TARGET_ASM_ALIGNED_DI_OP
1168 #define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
1169
1170 #undef TARGET_ASM_FUNCTION_PROLOGUE
1171 #define TARGET_ASM_FUNCTION_PROLOGUE mips_output_function_prologue
1172 #undef TARGET_ASM_FUNCTION_EPILOGUE
1173 #define TARGET_ASM_FUNCTION_EPILOGUE mips_output_function_epilogue
1174 #undef TARGET_ASM_SELECT_RTX_SECTION
1175 #define TARGET_ASM_SELECT_RTX_SECTION mips_select_rtx_section
1176 #undef TARGET_ASM_FUNCTION_RODATA_SECTION
1177 #define TARGET_ASM_FUNCTION_RODATA_SECTION mips_function_rodata_section
1178
1179 #undef TARGET_SCHED_REORDER
1180 #define TARGET_SCHED_REORDER mips_sched_reorder
1181 #undef TARGET_SCHED_VARIABLE_ISSUE
1182 #define TARGET_SCHED_VARIABLE_ISSUE mips_variable_issue
1183 #undef TARGET_SCHED_ADJUST_COST
1184 #define TARGET_SCHED_ADJUST_COST mips_adjust_cost
1185 #undef TARGET_SCHED_ISSUE_RATE
1186 #define TARGET_SCHED_ISSUE_RATE mips_issue_rate
1187 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
1188 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
1189   mips_multipass_dfa_lookahead
1190
1191 #undef TARGET_DEFAULT_TARGET_FLAGS
1192 #define TARGET_DEFAULT_TARGET_FLAGS             \
1193   (TARGET_DEFAULT                               \
1194    | TARGET_CPU_DEFAULT                         \
1195    | TARGET_ENDIAN_DEFAULT                      \
1196    | TARGET_FP_EXCEPTIONS_DEFAULT               \
1197    | MASK_CHECK_ZERO_DIV                        \
1198    | MASK_FUSED_MADD)
1199 #undef TARGET_HANDLE_OPTION
1200 #define TARGET_HANDLE_OPTION mips_handle_option
1201
1202 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
1203 #define TARGET_FUNCTION_OK_FOR_SIBCALL mips_function_ok_for_sibcall
1204
1205 #undef TARGET_VALID_POINTER_MODE
1206 #define TARGET_VALID_POINTER_MODE mips_valid_pointer_mode
1207 #undef TARGET_RTX_COSTS
1208 #define TARGET_RTX_COSTS mips_rtx_costs
1209 #undef TARGET_ADDRESS_COST
1210 #define TARGET_ADDRESS_COST mips_address_cost
1211
1212 #undef TARGET_IN_SMALL_DATA_P
1213 #define TARGET_IN_SMALL_DATA_P mips_in_small_data_p
1214
1215 #undef TARGET_MACHINE_DEPENDENT_REORG
1216 #define TARGET_MACHINE_DEPENDENT_REORG mips_reorg
1217
1218 #undef TARGET_ASM_FILE_START
1219 #define TARGET_ASM_FILE_START mips_file_start
1220 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
1221 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
1222
1223 #undef TARGET_INIT_LIBFUNCS
1224 #define TARGET_INIT_LIBFUNCS mips_init_libfuncs
1225
1226 #undef TARGET_BUILD_BUILTIN_VA_LIST
1227 #define TARGET_BUILD_BUILTIN_VA_LIST mips_build_builtin_va_list
1228 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
1229 #define TARGET_GIMPLIFY_VA_ARG_EXPR mips_gimplify_va_arg_expr
1230
1231 #undef TARGET_PROMOTE_FUNCTION_ARGS
1232 #define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_tree_true
1233 #undef TARGET_PROMOTE_FUNCTION_RETURN
1234 #define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_tree_true
1235 #undef TARGET_PROMOTE_PROTOTYPES
1236 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
1237
1238 #undef TARGET_RETURN_IN_MEMORY
1239 #define TARGET_RETURN_IN_MEMORY mips_return_in_memory
1240 #undef TARGET_RETURN_IN_MSB
1241 #define TARGET_RETURN_IN_MSB mips_return_in_msb
1242
1243 #undef TARGET_ASM_OUTPUT_MI_THUNK
1244 #define TARGET_ASM_OUTPUT_MI_THUNK mips_output_mi_thunk
1245 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
1246 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
1247
1248 #undef TARGET_SETUP_INCOMING_VARARGS
1249 #define TARGET_SETUP_INCOMING_VARARGS mips_setup_incoming_varargs
1250 #undef TARGET_STRICT_ARGUMENT_NAMING
1251 #define TARGET_STRICT_ARGUMENT_NAMING mips_strict_argument_naming
1252 #undef TARGET_MUST_PASS_IN_STACK
1253 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
1254 #undef TARGET_PASS_BY_REFERENCE
1255 #define TARGET_PASS_BY_REFERENCE mips_pass_by_reference
1256 #undef TARGET_CALLEE_COPIES
1257 #define TARGET_CALLEE_COPIES mips_callee_copies
1258 #undef TARGET_ARG_PARTIAL_BYTES
1259 #define TARGET_ARG_PARTIAL_BYTES mips_arg_partial_bytes
1260
1261 #undef TARGET_MODE_REP_EXTENDED
1262 #define TARGET_MODE_REP_EXTENDED mips_mode_rep_extended
1263
1264 #undef TARGET_VECTOR_MODE_SUPPORTED_P
1265 #define TARGET_VECTOR_MODE_SUPPORTED_P mips_vector_mode_supported_p
1266
1267 #undef TARGET_INIT_BUILTINS
1268 #define TARGET_INIT_BUILTINS mips_init_builtins
1269 #undef TARGET_EXPAND_BUILTIN
1270 #define TARGET_EXPAND_BUILTIN mips_expand_builtin
1271
1272 #undef TARGET_HAVE_TLS
1273 #define TARGET_HAVE_TLS HAVE_AS_TLS
1274
1275 #undef TARGET_CANNOT_FORCE_CONST_MEM
1276 #define TARGET_CANNOT_FORCE_CONST_MEM mips_cannot_force_const_mem
1277
1278 #undef TARGET_ENCODE_SECTION_INFO
1279 #define TARGET_ENCODE_SECTION_INFO mips_encode_section_info
1280
1281 #undef TARGET_ATTRIBUTE_TABLE
1282 #define TARGET_ATTRIBUTE_TABLE mips_attribute_table
1283
1284 #undef TARGET_EXTRA_LIVE_ON_ENTRY
1285 #define TARGET_EXTRA_LIVE_ON_ENTRY mips_extra_live_on_entry
1286
1287 #undef TARGET_MIN_ANCHOR_OFFSET
1288 #define TARGET_MIN_ANCHOR_OFFSET -32768
1289 #undef TARGET_MAX_ANCHOR_OFFSET
1290 #define TARGET_MAX_ANCHOR_OFFSET 32767
1291 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
1292 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P mips_use_blocks_for_constant_p
1293 #undef TARGET_USE_ANCHORS_FOR_SYMBOL_P
1294 #define TARGET_USE_ANCHORS_FOR_SYMBOL_P mips_use_anchors_for_symbol_p
1295
1296 #undef  TARGET_COMP_TYPE_ATTRIBUTES
1297 #define TARGET_COMP_TYPE_ATTRIBUTES mips_comp_type_attributes
1298
1299 struct gcc_target targetm = TARGET_INITIALIZER;
1300
1301
1302 /* Predicates to test for presence of "near" and "far"/"long_call"
1303    attributes on the given TYPE.  */
1304
1305 static bool
1306 mips_near_type_p (tree type)
1307 {
1308   return lookup_attribute ("near", TYPE_ATTRIBUTES (type)) != NULL;
1309 }
1310
1311 static bool
1312 mips_far_type_p (tree type)
1313 {
1314   return (lookup_attribute ("long_call", TYPE_ATTRIBUTES (type)) != NULL
1315           || lookup_attribute ("far", TYPE_ATTRIBUTES (type)) != NULL);
1316 }
1317
1318
1319 /* Return 0 if the attributes for two types are incompatible, 1 if they
1320    are compatible, and 2 if they are nearly compatible (which causes a
1321    warning to be generated).  */
1322
1323 static int
1324 mips_comp_type_attributes (tree type1, tree type2)
1325 {
1326   /* Check for mismatch of non-default calling convention.  */
1327   if (TREE_CODE (type1) != FUNCTION_TYPE)
1328     return 1;
1329
1330   /* Disallow mixed near/far attributes.  */
1331   if (mips_far_type_p (type1) && mips_near_type_p (type2))
1332     return 0;
1333   if (mips_near_type_p (type1) && mips_far_type_p (type2))
1334     return 0;
1335
1336   return 1;
1337 }
1338 \f
1339 /* If X is a PLUS of a CONST_INT, return the two terms in *BASE_PTR
1340    and *OFFSET_PTR.  Return X in *BASE_PTR and 0 in *OFFSET_PTR otherwise.  */
1341
1342 static void
1343 mips_split_plus (rtx x, rtx *base_ptr, HOST_WIDE_INT *offset_ptr)
1344 {
1345   if (GET_CODE (x) == PLUS && GET_CODE (XEXP (x, 1)) == CONST_INT)
1346     {
1347       *base_ptr = XEXP (x, 0);
1348       *offset_ptr = INTVAL (XEXP (x, 1));
1349     }
1350   else
1351     {
1352       *base_ptr = x;
1353       *offset_ptr = 0;
1354     }
1355 }
1356 \f
1357 /* Return true if SYMBOL_REF X is associated with a global symbol
1358    (in the STB_GLOBAL sense).  */
1359
1360 static bool
1361 mips_global_symbol_p (rtx x)
1362 {
1363   tree decl;
1364
1365   decl = SYMBOL_REF_DECL (x);
1366   if (!decl)
1367     return !SYMBOL_REF_LOCAL_P (x);
1368
1369   /* Weakref symbols are not TREE_PUBLIC, but their targets are global
1370      or weak symbols.  Relocations in the object file will be against
1371      the target symbol, so it's that symbol's binding that matters here.  */
1372   return DECL_P (decl) && (TREE_PUBLIC (decl) || DECL_WEAK (decl));
1373 }
1374
1375 /* Return true if SYMBOL_REF X binds locally.  */
1376
1377 static bool
1378 mips_symbol_binds_local_p (rtx x)
1379 {
1380   return (SYMBOL_REF_DECL (x)
1381           ? targetm.binds_local_p (SYMBOL_REF_DECL (x))
1382           : SYMBOL_REF_LOCAL_P (x));
1383 }
1384
1385 /* Classify symbol X, which must be a SYMBOL_REF or a LABEL_REF.  */
1386
1387 static enum mips_symbol_type
1388 mips_classify_symbol (rtx x)
1389 {
1390   if (TARGET_RTP_PIC)
1391     return SYMBOL_GOT_DISP;
1392
1393   if (GET_CODE (x) == LABEL_REF)
1394     {
1395       if (TARGET_MIPS16)
1396         return SYMBOL_CONSTANT_POOL;
1397       if (TARGET_ABICALLS && !TARGET_ABSOLUTE_ABICALLS)
1398         return SYMBOL_GOT_PAGE_OFST;
1399       return SYMBOL_GENERAL;
1400     }
1401
1402   gcc_assert (GET_CODE (x) == SYMBOL_REF);
1403
1404   if (SYMBOL_REF_TLS_MODEL (x))
1405     return SYMBOL_TLS;
1406
1407   if (CONSTANT_POOL_ADDRESS_P (x))
1408     {
1409       if (TARGET_MIPS16)
1410         return SYMBOL_CONSTANT_POOL;
1411
1412       if (GET_MODE_SIZE (get_pool_mode (x)) <= mips_section_threshold)
1413         return SYMBOL_SMALL_DATA;
1414     }
1415
1416   /* Do not use small-data accesses for weak symbols; they may end up
1417      being zero.  */
1418   if (SYMBOL_REF_SMALL_P (x)
1419       && !SYMBOL_REF_WEAK (x))
1420     return SYMBOL_SMALL_DATA;
1421
1422   if (TARGET_ABICALLS)
1423     {
1424       /* Don't use GOT accesses for locally-binding symbols; we can use
1425          %hi and %lo instead.  */
1426       if (TARGET_ABSOLUTE_ABICALLS && mips_symbol_binds_local_p (x))
1427         return SYMBOL_GENERAL;
1428
1429       /* There are three cases to consider:
1430
1431             - o32 PIC (either with or without explicit relocs)
1432             - n32/n64 PIC without explicit relocs
1433             - n32/n64 PIC with explicit relocs
1434
1435          In the first case, both local and global accesses will use an
1436          R_MIPS_GOT16 relocation.  We must correctly predict which of
1437          the two semantics (local or global) the assembler and linker
1438          will apply.  The choice depends on the symbol's binding rather
1439          than its visibility.
1440
1441          In the second case, the assembler will not use R_MIPS_GOT16
1442          relocations, but it chooses between local and global accesses
1443          in the same way as for o32 PIC.
1444
1445          In the third case we have more freedom since both forms of
1446          access will work for any kind of symbol.  However, there seems
1447          little point in doing things differently.  */
1448       if (mips_global_symbol_p (x))
1449         return SYMBOL_GOT_DISP;
1450
1451       return SYMBOL_GOT_PAGE_OFST;
1452     }
1453
1454   return SYMBOL_GENERAL;
1455 }
1456
1457 /* Return true if OFFSET is within the range [0, ALIGN), where ALIGN
1458    is the alignment (in bytes) of SYMBOL_REF X.  */
1459
1460 static bool
1461 mips_offset_within_alignment_p (rtx x, HOST_WIDE_INT offset)
1462 {
1463   /* If for some reason we can't get the alignment for the
1464      symbol, initializing this to one means we will only accept
1465      a zero offset.  */
1466   HOST_WIDE_INT align = 1;
1467   tree t;
1468
1469   /* Get the alignment of the symbol we're referring to.  */
1470   t = SYMBOL_REF_DECL (x);
1471   if (t)
1472     align = DECL_ALIGN_UNIT (t);
1473
1474   return offset >= 0 && offset < align;
1475 }
1476
1477 /* Return true if X is a symbolic constant that can be calculated in
1478    the same way as a bare symbol.  If it is, store the type of the
1479    symbol in *SYMBOL_TYPE.  */
1480
1481 bool
1482 mips_symbolic_constant_p (rtx x, enum mips_symbol_type *symbol_type)
1483 {
1484   rtx offset;
1485
1486   split_const (x, &x, &offset);
1487   if (UNSPEC_ADDRESS_P (x))
1488     {
1489       *symbol_type = UNSPEC_ADDRESS_TYPE (x);
1490       x = UNSPEC_ADDRESS (x);
1491     }
1492   else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF)
1493     {
1494       *symbol_type = mips_classify_symbol (x);
1495       if (*symbol_type == SYMBOL_TLS)
1496         return false;
1497     }
1498   else
1499     return false;
1500
1501   if (offset == const0_rtx)
1502     return true;
1503
1504   /* Check whether a nonzero offset is valid for the underlying
1505      relocations.  */
1506   switch (*symbol_type)
1507     {
1508     case SYMBOL_GENERAL:
1509     case SYMBOL_64_HIGH:
1510     case SYMBOL_64_MID:
1511     case SYMBOL_64_LOW:
1512       /* If the target has 64-bit pointers and the object file only
1513          supports 32-bit symbols, the values of those symbols will be
1514          sign-extended.  In this case we can't allow an arbitrary offset
1515          in case the 32-bit value X + OFFSET has a different sign from X.  */
1516       if (Pmode == DImode && !ABI_HAS_64BIT_SYMBOLS)
1517         return offset_within_block_p (x, INTVAL (offset));
1518
1519       /* In other cases the relocations can handle any offset.  */
1520       return true;
1521
1522     case SYMBOL_CONSTANT_POOL:
1523       /* Allow constant pool references to be converted to LABEL+CONSTANT.
1524          In this case, we no longer have access to the underlying constant,
1525          but the original symbol-based access was known to be valid.  */
1526       if (GET_CODE (x) == LABEL_REF)
1527         return true;
1528
1529       /* Fall through.  */
1530
1531     case SYMBOL_SMALL_DATA:
1532       /* Make sure that the offset refers to something within the
1533          same object block.  This should guarantee that the final
1534          PC- or GP-relative offset is within the 16-bit limit.  */
1535       return offset_within_block_p (x, INTVAL (offset));
1536
1537     case SYMBOL_GOT_PAGE_OFST:
1538     case SYMBOL_GOTOFF_PAGE:
1539       /* If the symbol is global, the GOT entry will contain the symbol's
1540          address, and we will apply a 16-bit offset after loading it.
1541          If the symbol is local, the linker should provide enough local
1542          GOT entries for a 16-bit offset, but larger offsets may lead
1543          to GOT overflow.  */
1544       return SMALL_INT (offset);
1545
1546     case SYMBOL_TPREL:
1547     case SYMBOL_DTPREL:
1548       /* There is no carry between the HI and LO REL relocations, so the
1549          offset is only valid if we know it won't lead to such a carry.  */
1550       return mips_offset_within_alignment_p (x, INTVAL (offset));
1551
1552     case SYMBOL_GOT_DISP:
1553     case SYMBOL_GOTOFF_DISP:
1554     case SYMBOL_GOTOFF_CALL:
1555     case SYMBOL_GOTOFF_LOADGP:
1556     case SYMBOL_TLSGD:
1557     case SYMBOL_TLSLDM:
1558     case SYMBOL_GOTTPREL:
1559     case SYMBOL_TLS:
1560     case SYMBOL_HALF:
1561       return false;
1562     }
1563   gcc_unreachable ();
1564 }
1565
1566
1567 /* This function is used to implement REG_MODE_OK_FOR_BASE_P.  */
1568
1569 int
1570 mips_regno_mode_ok_for_base_p (int regno, enum machine_mode mode, int strict)
1571 {
1572   if (!HARD_REGISTER_NUM_P (regno))
1573     {
1574       if (!strict)
1575         return true;
1576       regno = reg_renumber[regno];
1577     }
1578
1579   /* These fake registers will be eliminated to either the stack or
1580      hard frame pointer, both of which are usually valid base registers.
1581      Reload deals with the cases where the eliminated form isn't valid.  */
1582   if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
1583     return true;
1584
1585   /* In mips16 mode, the stack pointer can only address word and doubleword
1586      values, nothing smaller.  There are two problems here:
1587
1588        (a) Instantiating virtual registers can introduce new uses of the
1589            stack pointer.  If these virtual registers are valid addresses,
1590            the stack pointer should be too.
1591
1592        (b) Most uses of the stack pointer are not made explicit until
1593            FRAME_POINTER_REGNUM and ARG_POINTER_REGNUM have been eliminated.
1594            We don't know until that stage whether we'll be eliminating to the
1595            stack pointer (which needs the restriction) or the hard frame
1596            pointer (which doesn't).
1597
1598      All in all, it seems more consistent to only enforce this restriction
1599      during and after reload.  */
1600   if (TARGET_MIPS16 && regno == STACK_POINTER_REGNUM)
1601     return !strict || GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
1602
1603   return TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
1604 }
1605
1606
1607 /* Return true if X is a valid base register for the given mode.
1608    Allow only hard registers if STRICT.  */
1609
1610 static bool
1611 mips_valid_base_register_p (rtx x, enum machine_mode mode, int strict)
1612 {
1613   if (!strict && GET_CODE (x) == SUBREG)
1614     x = SUBREG_REG (x);
1615
1616   return (REG_P (x)
1617           && mips_regno_mode_ok_for_base_p (REGNO (x), mode, strict));
1618 }
1619
1620
1621 /* Return true if symbols of type SYMBOL_TYPE can directly address a value
1622    with mode MODE.  This is used for both symbolic and LO_SUM addresses.  */
1623
1624 static bool
1625 mips_symbolic_address_p (enum mips_symbol_type symbol_type,
1626                          enum machine_mode mode)
1627 {
1628   switch (symbol_type)
1629     {
1630     case SYMBOL_GENERAL:
1631       return !TARGET_MIPS16;
1632
1633     case SYMBOL_SMALL_DATA:
1634       return true;
1635
1636     case SYMBOL_CONSTANT_POOL:
1637       /* PC-relative addressing is only available for lw and ld.  */
1638       return GET_MODE_SIZE (mode) == 4 || GET_MODE_SIZE (mode) == 8;
1639
1640     case SYMBOL_GOT_PAGE_OFST:
1641       return true;
1642
1643     case SYMBOL_GOT_DISP:
1644       /* The address will have to be loaded from the GOT first.  */
1645       return false;
1646
1647     case SYMBOL_GOTOFF_PAGE:
1648     case SYMBOL_GOTOFF_DISP:
1649     case SYMBOL_GOTOFF_CALL:
1650     case SYMBOL_GOTOFF_LOADGP:
1651     case SYMBOL_TLS:
1652     case SYMBOL_TLSGD:
1653     case SYMBOL_TLSLDM:
1654     case SYMBOL_DTPREL:
1655     case SYMBOL_GOTTPREL:
1656     case SYMBOL_TPREL:
1657     case SYMBOL_64_HIGH:
1658     case SYMBOL_64_MID:
1659     case SYMBOL_64_LOW:
1660     case SYMBOL_HALF:
1661       return true;
1662     }
1663   gcc_unreachable ();
1664 }
1665
1666
1667 /* Return true if X is a valid address for machine mode MODE.  If it is,
1668    fill in INFO appropriately.  STRICT is true if we should only accept
1669    hard base registers.  */
1670
1671 static bool
1672 mips_classify_address (struct mips_address_info *info, rtx x,
1673                        enum machine_mode mode, int strict)
1674 {
1675   switch (GET_CODE (x))
1676     {
1677     case REG:
1678     case SUBREG:
1679       info->type = ADDRESS_REG;
1680       info->reg = x;
1681       info->offset = const0_rtx;
1682       return mips_valid_base_register_p (info->reg, mode, strict);
1683
1684     case PLUS:
1685       info->type = ADDRESS_REG;
1686       info->reg = XEXP (x, 0);
1687       info->offset = XEXP (x, 1);
1688       return (mips_valid_base_register_p (info->reg, mode, strict)
1689               && const_arith_operand (info->offset, VOIDmode));
1690
1691     case LO_SUM:
1692       info->type = ADDRESS_LO_SUM;
1693       info->reg = XEXP (x, 0);
1694       info->offset = XEXP (x, 1);
1695       return (mips_valid_base_register_p (info->reg, mode, strict)
1696               && mips_symbolic_constant_p (info->offset, &info->symbol_type)
1697               && mips_symbolic_address_p (info->symbol_type, mode)
1698               && mips_lo_relocs[info->symbol_type] != 0);
1699
1700     case CONST_INT:
1701       /* Small-integer addresses don't occur very often, but they
1702          are legitimate if $0 is a valid base register.  */
1703       info->type = ADDRESS_CONST_INT;
1704       return !TARGET_MIPS16 && SMALL_INT (x);
1705
1706     case CONST:
1707     case LABEL_REF:
1708     case SYMBOL_REF:
1709       info->type = ADDRESS_SYMBOLIC;
1710       return (mips_symbolic_constant_p (x, &info->symbol_type)
1711               && mips_symbolic_address_p (info->symbol_type, mode)
1712               && !mips_split_p[info->symbol_type]);
1713
1714     default:
1715       return false;
1716     }
1717 }
1718
1719 /* Return true if X is a thread-local symbol.  */
1720
1721 static bool
1722 mips_tls_operand_p (rtx x)
1723 {
1724   return GET_CODE (x) == SYMBOL_REF && SYMBOL_REF_TLS_MODEL (x) != 0;
1725 }
1726
1727 /* Return true if X can not be forced into a constant pool.  */
1728
1729 static int
1730 mips_tls_symbol_ref_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
1731 {
1732   return mips_tls_operand_p (*x);
1733 }
1734
1735 /* Return true if X can not be forced into a constant pool.  */
1736
1737 static bool
1738 mips_cannot_force_const_mem (rtx x)
1739 {
1740   rtx base, offset;
1741
1742   if (!TARGET_MIPS16)
1743     {
1744       /* As an optimization, reject constants that mips_legitimize_move
1745          can expand inline.
1746
1747          Suppose we have a multi-instruction sequence that loads constant C
1748          into register R.  If R does not get allocated a hard register, and
1749          R is used in an operand that allows both registers and memory
1750          references, reload will consider forcing C into memory and using
1751          one of the instruction's memory alternatives.  Returning false
1752          here will force it to use an input reload instead.  */
1753       if (GET_CODE (x) == CONST_INT)
1754         return true;
1755
1756       split_const (x, &base, &offset);
1757       if (symbolic_operand (base, VOIDmode) && SMALL_INT (offset))
1758         return true;
1759     }
1760
1761   if (TARGET_HAVE_TLS && for_each_rtx (&x, &mips_tls_symbol_ref_1, 0))
1762     return true;
1763
1764   return false;
1765 }
1766
1767 /* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  MIPS16 uses per-function
1768    constant pools, but normal-mode code doesn't need to.  */
1769
1770 static bool
1771 mips_use_blocks_for_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED,
1772                                 rtx x ATTRIBUTE_UNUSED)
1773 {
1774   return !TARGET_MIPS16;
1775 }
1776 \f
1777 /* Return the number of instructions needed to load a symbol of the
1778    given type into a register.  If valid in an address, the same number
1779    of instructions are needed for loads and stores.  Treat extended
1780    mips16 instructions as two instructions.  */
1781
1782 static int
1783 mips_symbol_insns (enum mips_symbol_type type)
1784 {
1785   switch (type)
1786     {
1787     case SYMBOL_GENERAL:
1788       /* In mips16 code, general symbols must be fetched from the
1789          constant pool.  */
1790       if (TARGET_MIPS16)
1791         return 0;
1792
1793       /* When using 64-bit symbols, we need 5 preparatory instructions,
1794          such as:
1795
1796              lui     $at,%highest(symbol)
1797              daddiu  $at,$at,%higher(symbol)
1798              dsll    $at,$at,16
1799              daddiu  $at,$at,%hi(symbol)
1800              dsll    $at,$at,16
1801
1802          The final address is then $at + %lo(symbol).  With 32-bit
1803          symbols we just need a preparatory lui.  */
1804       return (ABI_HAS_64BIT_SYMBOLS ? 6 : 2);
1805
1806     case SYMBOL_SMALL_DATA:
1807     case SYMBOL_HALF:
1808       return 1;
1809
1810     case SYMBOL_CONSTANT_POOL:
1811       /* This case is for mips16 only.  Assume we'll need an
1812          extended instruction.  */
1813       return 2;
1814
1815     case SYMBOL_GOT_PAGE_OFST:
1816     case SYMBOL_GOT_DISP:
1817       /* Unless -funit-at-a-time is in effect, we can't be sure whether
1818          the local/global classification is accurate.  See override_options
1819          for details.
1820
1821          The worst cases are:
1822
1823          (1) For local symbols when generating o32 or o64 code.  The assembler
1824              will use:
1825
1826                  lw           $at,%got(symbol)
1827                  nop
1828
1829              ...and the final address will be $at + %lo(symbol).
1830
1831          (2) For global symbols when -mxgot.  The assembler will use:
1832
1833                  lui     $at,%got_hi(symbol)
1834                  (d)addu $at,$at,$gp
1835
1836              ...and the final address will be $at + %got_lo(symbol).  */
1837       return 3;
1838
1839     case SYMBOL_GOTOFF_PAGE:
1840     case SYMBOL_GOTOFF_DISP:
1841     case SYMBOL_GOTOFF_CALL:
1842     case SYMBOL_GOTOFF_LOADGP:
1843     case SYMBOL_64_HIGH:
1844     case SYMBOL_64_MID:
1845     case SYMBOL_64_LOW:
1846     case SYMBOL_TLSGD:
1847     case SYMBOL_TLSLDM:
1848     case SYMBOL_DTPREL:
1849     case SYMBOL_GOTTPREL:
1850     case SYMBOL_TPREL:
1851       /* Check whether the offset is a 16- or 32-bit value.  */
1852       return mips_split_p[type] ? 2 : 1;
1853
1854     case SYMBOL_TLS:
1855       /* We don't treat a bare TLS symbol as a constant.  */
1856       return 0;
1857     }
1858   gcc_unreachable ();
1859 }
1860
1861 /* Return true if X is a legitimate $sp-based address for mode MDOE.  */
1862
1863 bool
1864 mips_stack_address_p (rtx x, enum machine_mode mode)
1865 {
1866   struct mips_address_info addr;
1867
1868   return (mips_classify_address (&addr, x, mode, false)
1869           && addr.type == ADDRESS_REG
1870           && addr.reg == stack_pointer_rtx);
1871 }
1872
1873 /* Return true if a value at OFFSET bytes from BASE can be accessed
1874    using an unextended mips16 instruction.  MODE is the mode of the
1875    value.
1876
1877    Usually the offset in an unextended instruction is a 5-bit field.
1878    The offset is unsigned and shifted left once for HIs, twice
1879    for SIs, and so on.  An exception is SImode accesses off the
1880    stack pointer, which have an 8-bit immediate field.  */
1881
1882 static bool
1883 mips16_unextended_reference_p (enum machine_mode mode, rtx base, rtx offset)
1884 {
1885   if (TARGET_MIPS16
1886       && GET_CODE (offset) == CONST_INT
1887       && INTVAL (offset) >= 0
1888       && (INTVAL (offset) & (GET_MODE_SIZE (mode) - 1)) == 0)
1889     {
1890       if (GET_MODE_SIZE (mode) == 4 && base == stack_pointer_rtx)
1891         return INTVAL (offset) < 256 * GET_MODE_SIZE (mode);
1892       return INTVAL (offset) < 32 * GET_MODE_SIZE (mode);
1893     }
1894   return false;
1895 }
1896
1897
1898 /* Return the number of instructions needed to load or store a value
1899    of mode MODE at X.  Return 0 if X isn't valid for MODE.
1900
1901    For mips16 code, count extended instructions as two instructions.  */
1902
1903 int
1904 mips_address_insns (rtx x, enum machine_mode mode)
1905 {
1906   struct mips_address_info addr;
1907   int factor;
1908
1909   if (mode == BLKmode)
1910     /* BLKmode is used for single unaligned loads and stores.  */
1911     factor = 1;
1912   else
1913     /* Each word of a multi-word value will be accessed individually.  */
1914     factor = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
1915
1916   if (mips_classify_address (&addr, x, mode, false))
1917     switch (addr.type)
1918       {
1919       case ADDRESS_REG:
1920         if (TARGET_MIPS16
1921             && !mips16_unextended_reference_p (mode, addr.reg, addr.offset))
1922           return factor * 2;
1923         return factor;
1924
1925       case ADDRESS_LO_SUM:
1926         return (TARGET_MIPS16 ? factor * 2 : factor);
1927
1928       case ADDRESS_CONST_INT:
1929         return factor;
1930
1931       case ADDRESS_SYMBOLIC:
1932         return factor * mips_symbol_insns (addr.symbol_type);
1933       }
1934   return 0;
1935 }
1936
1937
1938 /* Likewise for constant X.  */
1939
1940 int
1941 mips_const_insns (rtx x)
1942 {
1943   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
1944   enum mips_symbol_type symbol_type;
1945   rtx offset;
1946
1947   switch (GET_CODE (x))
1948     {
1949     case HIGH:
1950       if (TARGET_MIPS16
1951           || !mips_symbolic_constant_p (XEXP (x, 0), &symbol_type)
1952           || !mips_split_p[symbol_type])
1953         return 0;
1954
1955       return 1;
1956
1957     case CONST_INT:
1958       if (TARGET_MIPS16)
1959         /* Unsigned 8-bit constants can be loaded using an unextended
1960            LI instruction.  Unsigned 16-bit constants can be loaded
1961            using an extended LI.  Negative constants must be loaded
1962            using LI and then negated.  */
1963         return (INTVAL (x) >= 0 && INTVAL (x) < 256 ? 1
1964                 : SMALL_OPERAND_UNSIGNED (INTVAL (x)) ? 2
1965                 : INTVAL (x) > -256 && INTVAL (x) < 0 ? 2
1966                 : SMALL_OPERAND_UNSIGNED (-INTVAL (x)) ? 3
1967                 : 0);
1968
1969       return mips_build_integer (codes, INTVAL (x));
1970
1971     case CONST_DOUBLE:
1972     case CONST_VECTOR:
1973       return (!TARGET_MIPS16 && x == CONST0_RTX (GET_MODE (x)) ? 1 : 0);
1974
1975     case CONST:
1976       if (CONST_GP_P (x))
1977         return 1;
1978
1979       /* See if we can refer to X directly.  */
1980       if (mips_symbolic_constant_p (x, &symbol_type))
1981         return mips_symbol_insns (symbol_type);
1982
1983       /* Otherwise try splitting the constant into a base and offset.
1984          16-bit offsets can be added using an extra addiu.  Larger offsets
1985          must be calculated separately and then added to the base.  */
1986       split_const (x, &x, &offset);
1987       if (offset != 0)
1988         {
1989           int n = mips_const_insns (x);
1990           if (n != 0)
1991             {
1992               if (SMALL_INT (offset))
1993                 return n + 1;
1994               else
1995                 return n + 1 + mips_build_integer (codes, INTVAL (offset));
1996             }
1997         }
1998       return 0;
1999
2000     case SYMBOL_REF:
2001     case LABEL_REF:
2002       return mips_symbol_insns (mips_classify_symbol (x));
2003
2004     default:
2005       return 0;
2006     }
2007 }
2008
2009
2010 /* Return the number of instructions needed for memory reference X.
2011    Count extended mips16 instructions as two instructions.  */
2012
2013 int
2014 mips_fetch_insns (rtx x)
2015 {
2016   gcc_assert (MEM_P (x));
2017   return mips_address_insns (XEXP (x, 0), GET_MODE (x));
2018 }
2019
2020
2021 /* Return the number of instructions needed for an integer division.  */
2022
2023 int
2024 mips_idiv_insns (void)
2025 {
2026   int count;
2027
2028   count = 1;
2029   if (TARGET_CHECK_ZERO_DIV)
2030     {
2031       if (GENERATE_DIVIDE_TRAPS)
2032         count++;
2033       else
2034         count += 2;
2035     }
2036
2037   if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
2038     count++;
2039   return count;
2040 }
2041 \f
2042 /* This function is used to implement GO_IF_LEGITIMATE_ADDRESS.  It
2043    returns a nonzero value if X is a legitimate address for a memory
2044    operand of the indicated MODE.  STRICT is nonzero if this function
2045    is called during reload.  */
2046
2047 bool
2048 mips_legitimate_address_p (enum machine_mode mode, rtx x, int strict)
2049 {
2050   struct mips_address_info addr;
2051
2052   return mips_classify_address (&addr, x, mode, strict);
2053 }
2054
2055
2056 /* Copy VALUE to a register and return that register.  If new psuedos
2057    are allowed, copy it into a new register, otherwise use DEST.  */
2058
2059 static rtx
2060 mips_force_temporary (rtx dest, rtx value)
2061 {
2062   if (!no_new_pseudos)
2063     return force_reg (Pmode, value);
2064   else
2065     {
2066       emit_move_insn (copy_rtx (dest), value);
2067       return dest;
2068     }
2069 }
2070
2071
2072 /* Return a LO_SUM expression for ADDR.  TEMP is as for mips_force_temporary
2073    and is used to load the high part into a register.  */
2074
2075 rtx
2076 mips_split_symbol (rtx temp, rtx addr)
2077 {
2078   rtx high;
2079
2080   if (!TARGET_MIPS16)
2081     high = mips_force_temporary (temp, gen_rtx_HIGH (Pmode, copy_rtx (addr)));
2082   else if (no_new_pseudos)
2083     {
2084       emit_insn (gen_load_const_gp (copy_rtx (temp)));
2085       high = temp;
2086     }
2087   else
2088     high = mips16_gp_pseudo_reg ();
2089   return gen_rtx_LO_SUM (Pmode, high, addr);
2090 }
2091
2092
2093 /* Return an UNSPEC address with underlying address ADDRESS and symbol
2094    type SYMBOL_TYPE.  */
2095
2096 rtx
2097 mips_unspec_address (rtx address, enum mips_symbol_type symbol_type)
2098 {
2099   rtx base, offset;
2100
2101   split_const (address, &base, &offset);
2102   base = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, base),
2103                          UNSPEC_ADDRESS_FIRST + symbol_type);
2104   if (offset != const0_rtx)
2105     base = gen_rtx_PLUS (Pmode, base, offset);
2106   return gen_rtx_CONST (Pmode, base);
2107 }
2108
2109
2110 /* If mips_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
2111    high part to BASE and return the result.  Just return BASE otherwise.
2112    TEMP is available as a temporary register if needed.
2113
2114    The returned expression can be used as the first operand to a LO_SUM.  */
2115
2116 static rtx
2117 mips_unspec_offset_high (rtx temp, rtx base, rtx addr,
2118                          enum mips_symbol_type symbol_type)
2119 {
2120   if (mips_split_p[symbol_type])
2121     {
2122       addr = gen_rtx_HIGH (Pmode, mips_unspec_address (addr, symbol_type));
2123       addr = mips_force_temporary (temp, addr);
2124       return mips_force_temporary (temp, gen_rtx_PLUS (Pmode, addr, base));
2125     }
2126   return base;
2127 }
2128
2129
2130 /* Return a legitimate address for REG + OFFSET.  TEMP is as for
2131    mips_force_temporary; it is only needed when OFFSET is not a
2132    SMALL_OPERAND.  */
2133
2134 static rtx
2135 mips_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
2136 {
2137   if (!SMALL_OPERAND (offset))
2138     {
2139       rtx high;
2140       if (TARGET_MIPS16)
2141         {
2142           /* Load the full offset into a register so that we can use
2143              an unextended instruction for the address itself.  */
2144           high = GEN_INT (offset);
2145           offset = 0;
2146         }
2147       else
2148         {
2149           /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.  */
2150           high = GEN_INT (CONST_HIGH_PART (offset));
2151           offset = CONST_LOW_PART (offset);
2152         }
2153       high = mips_force_temporary (temp, high);
2154       reg = mips_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
2155     }
2156   return plus_constant (reg, offset);
2157 }
2158
2159 /* Emit a call to __tls_get_addr.  SYM is the TLS symbol we are
2160    referencing, and TYPE is the symbol type to use (either global
2161    dynamic or local dynamic).  V0 is an RTX for the return value
2162    location.  The entire insn sequence is returned.  */
2163
2164 static GTY(()) rtx mips_tls_symbol;
2165
2166 static rtx
2167 mips_call_tls_get_addr (rtx sym, enum mips_symbol_type type, rtx v0)
2168 {
2169   rtx insn, loc, tga, a0;
2170
2171   a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
2172
2173   if (!mips_tls_symbol)
2174     mips_tls_symbol = init_one_libfunc ("__tls_get_addr");
2175
2176   loc = mips_unspec_address (sym, type);
2177
2178   start_sequence ();
2179
2180   emit_insn (gen_rtx_SET (Pmode, a0,
2181                           gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, loc)));
2182   tga = gen_rtx_MEM (Pmode, mips_tls_symbol);
2183   insn = emit_call_insn (gen_call_value (v0, tga, const0_rtx, const0_rtx));
2184   CONST_OR_PURE_CALL_P (insn) = 1;
2185   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), v0);
2186   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
2187   insn = get_insns ();
2188
2189   end_sequence ();
2190
2191   return insn;
2192 }
2193
2194 /* Generate the code to access LOC, a thread local SYMBOL_REF.  The
2195    return value will be a valid address and move_operand (either a REG
2196    or a LO_SUM).  */
2197
2198 static rtx
2199 mips_legitimize_tls_address (rtx loc)
2200 {
2201   rtx dest, insn, v0, v1, tmp1, tmp2, eqv;
2202   enum tls_model model;
2203
2204   v0 = gen_rtx_REG (Pmode, GP_RETURN);
2205   v1 = gen_rtx_REG (Pmode, GP_RETURN + 1);
2206
2207   model = SYMBOL_REF_TLS_MODEL (loc);
2208   /* Only TARGET_ABICALLS code can have more than one module; other
2209      code must be be static and should not use a GOT.  All TLS models
2210      reduce to local exec in this situation.  */
2211   if (!TARGET_ABICALLS)
2212     model = TLS_MODEL_LOCAL_EXEC;
2213
2214   switch (model)
2215     {
2216     case TLS_MODEL_GLOBAL_DYNAMIC:
2217       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSGD, v0);
2218       dest = gen_reg_rtx (Pmode);
2219       emit_libcall_block (insn, dest, v0, loc);
2220       break;
2221
2222     case TLS_MODEL_LOCAL_DYNAMIC:
2223       insn = mips_call_tls_get_addr (loc, SYMBOL_TLSLDM, v0);
2224       tmp1 = gen_reg_rtx (Pmode);
2225
2226       /* Attach a unique REG_EQUIV, to allow the RTL optimizers to
2227          share the LDM result with other LD model accesses.  */
2228       eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
2229                             UNSPEC_TLS_LDM);
2230       emit_libcall_block (insn, tmp1, v0, eqv);
2231
2232       tmp2 = mips_unspec_offset_high (NULL, tmp1, loc, SYMBOL_DTPREL);
2233       dest = gen_rtx_LO_SUM (Pmode, tmp2,
2234                              mips_unspec_address (loc, SYMBOL_DTPREL));
2235       break;
2236
2237     case TLS_MODEL_INITIAL_EXEC:
2238       tmp1 = gen_reg_rtx (Pmode);
2239       tmp2 = mips_unspec_address (loc, SYMBOL_GOTTPREL);
2240       if (Pmode == DImode)
2241         {
2242           emit_insn (gen_tls_get_tp_di (v1));
2243           emit_insn (gen_load_gotdi (tmp1, pic_offset_table_rtx, tmp2));
2244         }
2245       else
2246         {
2247           emit_insn (gen_tls_get_tp_si (v1));
2248           emit_insn (gen_load_gotsi (tmp1, pic_offset_table_rtx, tmp2));
2249         }
2250       dest = gen_reg_rtx (Pmode);
2251       emit_insn (gen_add3_insn (dest, tmp1, v1));
2252       break;
2253
2254     case TLS_MODEL_LOCAL_EXEC:
2255       if (Pmode == DImode)
2256         emit_insn (gen_tls_get_tp_di (v1));
2257       else
2258         emit_insn (gen_tls_get_tp_si (v1));
2259
2260       tmp1 = mips_unspec_offset_high (NULL, v1, loc, SYMBOL_TPREL);
2261       dest = gen_rtx_LO_SUM (Pmode, tmp1,
2262                              mips_unspec_address (loc, SYMBOL_TPREL));
2263       break;
2264
2265     default:
2266       gcc_unreachable ();
2267     }
2268
2269   return dest;
2270 }
2271
2272 /* This function is used to implement LEGITIMIZE_ADDRESS.  If *XLOC can
2273    be legitimized in a way that the generic machinery might not expect,
2274    put the new address in *XLOC and return true.  MODE is the mode of
2275    the memory being accessed.  */
2276
2277 bool
2278 mips_legitimize_address (rtx *xloc, enum machine_mode mode)
2279 {
2280   enum mips_symbol_type symbol_type;
2281
2282   if (mips_tls_operand_p (*xloc))
2283     {
2284       *xloc = mips_legitimize_tls_address (*xloc);
2285       return true;
2286     }
2287
2288   /* See if the address can split into a high part and a LO_SUM.  */
2289   if (mips_symbolic_constant_p (*xloc, &symbol_type)
2290       && mips_symbolic_address_p (symbol_type, mode)
2291       && mips_split_p[symbol_type])
2292     {
2293       *xloc = mips_split_symbol (0, *xloc);
2294       return true;
2295     }
2296
2297   if (GET_CODE (*xloc) == PLUS && GET_CODE (XEXP (*xloc, 1)) == CONST_INT)
2298     {
2299       /* Handle REG + CONSTANT using mips_add_offset.  */
2300       rtx reg;
2301
2302       reg = XEXP (*xloc, 0);
2303       if (!mips_valid_base_register_p (reg, mode, 0))
2304         reg = copy_to_mode_reg (Pmode, reg);
2305       *xloc = mips_add_offset (0, reg, INTVAL (XEXP (*xloc, 1)));
2306       return true;
2307     }
2308
2309   return false;
2310 }
2311
2312
2313 /* Subroutine of mips_build_integer (with the same interface).
2314    Assume that the final action in the sequence should be a left shift.  */
2315
2316 static unsigned int
2317 mips_build_shift (struct mips_integer_op *codes, HOST_WIDE_INT value)
2318 {
2319   unsigned int i, shift;
2320
2321   /* Shift VALUE right until its lowest bit is set.  Shift arithmetically
2322      since signed numbers are easier to load than unsigned ones.  */
2323   shift = 0;
2324   while ((value & 1) == 0)
2325     value /= 2, shift++;
2326
2327   i = mips_build_integer (codes, value);
2328   codes[i].code = ASHIFT;
2329   codes[i].value = shift;
2330   return i + 1;
2331 }
2332
2333
2334 /* As for mips_build_shift, but assume that the final action will be
2335    an IOR or PLUS operation.  */
2336
2337 static unsigned int
2338 mips_build_lower (struct mips_integer_op *codes, unsigned HOST_WIDE_INT value)
2339 {
2340   unsigned HOST_WIDE_INT high;
2341   unsigned int i;
2342
2343   high = value & ~(unsigned HOST_WIDE_INT) 0xffff;
2344   if (!LUI_OPERAND (high) && (value & 0x18000) == 0x18000)
2345     {
2346       /* The constant is too complex to load with a simple lui/ori pair
2347          so our goal is to clear as many trailing zeros as possible.
2348          In this case, we know bit 16 is set and that the low 16 bits
2349          form a negative number.  If we subtract that number from VALUE,
2350          we will clear at least the lowest 17 bits, maybe more.  */
2351       i = mips_build_integer (codes, CONST_HIGH_PART (value));
2352       codes[i].code = PLUS;
2353       codes[i].value = CONST_LOW_PART (value);
2354     }
2355   else
2356     {
2357       i = mips_build_integer (codes, high);
2358       codes[i].code = IOR;
2359       codes[i].value = value & 0xffff;
2360     }
2361   return i + 1;
2362 }
2363
2364
2365 /* Fill CODES with a sequence of rtl operations to load VALUE.
2366    Return the number of operations needed.  */
2367
2368 static unsigned int
2369 mips_build_integer (struct mips_integer_op *codes,
2370                     unsigned HOST_WIDE_INT value)
2371 {
2372   if (SMALL_OPERAND (value)
2373       || SMALL_OPERAND_UNSIGNED (value)
2374       || LUI_OPERAND (value))
2375     {
2376       /* The value can be loaded with a single instruction.  */
2377       codes[0].code = UNKNOWN;
2378       codes[0].value = value;
2379       return 1;
2380     }
2381   else if ((value & 1) != 0 || LUI_OPERAND (CONST_HIGH_PART (value)))
2382     {
2383       /* Either the constant is a simple LUI/ORI combination or its
2384          lowest bit is set.  We don't want to shift in this case.  */
2385       return mips_build_lower (codes, value);
2386     }
2387   else if ((value & 0xffff) == 0)
2388     {
2389       /* The constant will need at least three actions.  The lowest
2390          16 bits are clear, so the final action will be a shift.  */
2391       return mips_build_shift (codes, value);
2392     }
2393   else
2394     {
2395       /* The final action could be a shift, add or inclusive OR.
2396          Rather than use a complex condition to select the best
2397          approach, try both mips_build_shift and mips_build_lower
2398          and pick the one that gives the shortest sequence.
2399          Note that this case is only used once per constant.  */
2400       struct mips_integer_op alt_codes[MIPS_MAX_INTEGER_OPS];
2401       unsigned int cost, alt_cost;
2402
2403       cost = mips_build_shift (codes, value);
2404       alt_cost = mips_build_lower (alt_codes, value);
2405       if (alt_cost < cost)
2406         {
2407           memcpy (codes, alt_codes, alt_cost * sizeof (codes[0]));
2408           cost = alt_cost;
2409         }
2410       return cost;
2411     }
2412 }
2413
2414
2415 /* Load VALUE into DEST, using TEMP as a temporary register if need be.  */
2416
2417 void
2418 mips_move_integer (rtx dest, rtx temp, unsigned HOST_WIDE_INT value)
2419 {
2420   struct mips_integer_op codes[MIPS_MAX_INTEGER_OPS];
2421   enum machine_mode mode;
2422   unsigned int i, cost;
2423   rtx x;
2424
2425   mode = GET_MODE (dest);
2426   cost = mips_build_integer (codes, value);
2427
2428   /* Apply each binary operation to X.  Invariant: X is a legitimate
2429      source operand for a SET pattern.  */
2430   x = GEN_INT (codes[0].value);
2431   for (i = 1; i < cost; i++)
2432     {
2433       if (no_new_pseudos)
2434         {
2435           emit_insn (gen_rtx_SET (VOIDmode, temp, x));
2436           x = temp;
2437         }
2438       else
2439         x = force_reg (mode, x);
2440       x = gen_rtx_fmt_ee (codes[i].code, mode, x, GEN_INT (codes[i].value));
2441     }
2442
2443   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
2444 }
2445
2446
2447 /* Subroutine of mips_legitimize_move.  Move constant SRC into register
2448    DEST given that SRC satisfies immediate_operand but doesn't satisfy
2449    move_operand.  */
2450
2451 static void
2452 mips_legitimize_const_move (enum machine_mode mode, rtx dest, rtx src)
2453 {
2454   rtx base, offset;
2455
2456   /* Split moves of big integers into smaller pieces.  */
2457   if (splittable_const_int_operand (src, mode))
2458     {
2459       mips_move_integer (dest, dest, INTVAL (src));
2460       return;
2461     }
2462
2463   /* Split moves of symbolic constants into high/low pairs.  */
2464   if (splittable_symbolic_operand (src, mode))
2465     {
2466       emit_insn (gen_rtx_SET (VOIDmode, dest, mips_split_symbol (dest, src)));
2467       return;
2468     }
2469
2470   if (mips_tls_operand_p (src))
2471     {
2472       emit_move_insn (dest, mips_legitimize_tls_address (src));
2473       return;
2474     }
2475
2476   /* If we have (const (plus symbol offset)), load the symbol first
2477      and then add in the offset.  This is usually better than forcing
2478      the constant into memory, at least in non-mips16 code.  */
2479   split_const (src, &base, &offset);
2480   if (!TARGET_MIPS16
2481       && offset != const0_rtx
2482       && (!no_new_pseudos || SMALL_INT (offset)))
2483     {
2484       base = mips_force_temporary (dest, base);
2485       emit_move_insn (dest, mips_add_offset (0, base, INTVAL (offset)));
2486       return;
2487     }
2488
2489   src = force_const_mem (mode, src);
2490
2491   /* When using explicit relocs, constant pool references are sometimes
2492      not legitimate addresses.  */
2493   if (!memory_operand (src, VOIDmode))
2494     src = replace_equiv_address (src, mips_split_symbol (dest, XEXP (src, 0)));
2495   emit_move_insn (dest, src);
2496 }
2497
2498
2499 /* If (set DEST SRC) is not a valid instruction, emit an equivalent
2500    sequence that is valid.  */
2501
2502 bool
2503 mips_legitimize_move (enum machine_mode mode, rtx dest, rtx src)
2504 {
2505   if (!register_operand (dest, mode) && !reg_or_0_operand (src, mode))
2506     {
2507       emit_move_insn (dest, force_reg (mode, src));
2508       return true;
2509     }
2510
2511   /* Check for individual, fully-reloaded mflo and mfhi instructions.  */
2512   if (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
2513       && REG_P (src) && MD_REG_P (REGNO (src))
2514       && REG_P (dest) && GP_REG_P (REGNO (dest)))
2515     {
2516       int other_regno = REGNO (src) == HI_REGNUM ? LO_REGNUM : HI_REGNUM;
2517       if (GET_MODE_SIZE (mode) <= 4)
2518         emit_insn (gen_mfhilo_si (gen_rtx_REG (SImode, REGNO (dest)),
2519                                   gen_rtx_REG (SImode, REGNO (src)),
2520                                   gen_rtx_REG (SImode, other_regno)));
2521       else
2522         emit_insn (gen_mfhilo_di (gen_rtx_REG (DImode, REGNO (dest)),
2523                                   gen_rtx_REG (DImode, REGNO (src)),
2524                                   gen_rtx_REG (DImode, other_regno)));
2525       return true;
2526     }
2527
2528   /* We need to deal with constants that would be legitimate
2529      immediate_operands but not legitimate move_operands.  */
2530   if (CONSTANT_P (src) && !move_operand (src, mode))
2531     {
2532       mips_legitimize_const_move (mode, dest, src);
2533       set_unique_reg_note (get_last_insn (), REG_EQUAL, copy_rtx (src));
2534       return true;
2535     }
2536   return false;
2537 }
2538 \f
2539 /* We need a lot of little routines to check constant values on the
2540    mips16.  These are used to figure out how long the instruction will
2541    be.  It would be much better to do this using constraints, but
2542    there aren't nearly enough letters available.  */
2543
2544 static int
2545 m16_check_op (rtx op, int low, int high, int mask)
2546 {
2547   return (GET_CODE (op) == CONST_INT
2548           && INTVAL (op) >= low
2549           && INTVAL (op) <= high
2550           && (INTVAL (op) & mask) == 0);
2551 }
2552
2553 int
2554 m16_uimm3_b (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2555 {
2556   return m16_check_op (op, 0x1, 0x8, 0);
2557 }
2558
2559 int
2560 m16_simm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2561 {
2562   return m16_check_op (op, - 0x8, 0x7, 0);
2563 }
2564
2565 int
2566 m16_nsimm4_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2567 {
2568   return m16_check_op (op, - 0x7, 0x8, 0);
2569 }
2570
2571 int
2572 m16_simm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2573 {
2574   return m16_check_op (op, - 0x10, 0xf, 0);
2575 }
2576
2577 int
2578 m16_nsimm5_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2579 {
2580   return m16_check_op (op, - 0xf, 0x10, 0);
2581 }
2582
2583 int
2584 m16_uimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2585 {
2586   return m16_check_op (op, (- 0x10) << 2, 0xf << 2, 3);
2587 }
2588
2589 int
2590 m16_nuimm5_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2591 {
2592   return m16_check_op (op, (- 0xf) << 2, 0x10 << 2, 3);
2593 }
2594
2595 int
2596 m16_simm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2597 {
2598   return m16_check_op (op, - 0x80, 0x7f, 0);
2599 }
2600
2601 int
2602 m16_nsimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2603 {
2604   return m16_check_op (op, - 0x7f, 0x80, 0);
2605 }
2606
2607 int
2608 m16_uimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2609 {
2610   return m16_check_op (op, 0x0, 0xff, 0);
2611 }
2612
2613 int
2614 m16_nuimm8_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2615 {
2616   return m16_check_op (op, - 0xff, 0x0, 0);
2617 }
2618
2619 int
2620 m16_uimm8_m1_1 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2621 {
2622   return m16_check_op (op, - 0x1, 0xfe, 0);
2623 }
2624
2625 int
2626 m16_uimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2627 {
2628   return m16_check_op (op, 0x0, 0xff << 2, 3);
2629 }
2630
2631 int
2632 m16_nuimm8_4 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2633 {
2634   return m16_check_op (op, (- 0xff) << 2, 0x0, 3);
2635 }
2636
2637 int
2638 m16_simm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2639 {
2640   return m16_check_op (op, (- 0x80) << 3, 0x7f << 3, 7);
2641 }
2642
2643 int
2644 m16_nsimm8_8 (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
2645 {
2646   return m16_check_op (op, (- 0x7f) << 3, 0x80 << 3, 7);
2647 }
2648 \f
2649 static bool
2650 mips_rtx_costs (rtx x, int code, int outer_code, int *total)
2651 {
2652   enum machine_mode mode = GET_MODE (x);
2653   bool float_mode_p = FLOAT_MODE_P (mode);
2654
2655   switch (code)
2656     {
2657     case CONST_INT:
2658       if (TARGET_MIPS16)
2659         {
2660           /* A number between 1 and 8 inclusive is efficient for a shift.
2661              Otherwise, we will need an extended instruction.  */
2662           if ((outer_code) == ASHIFT || (outer_code) == ASHIFTRT
2663               || (outer_code) == LSHIFTRT)
2664             {
2665               if (INTVAL (x) >= 1 && INTVAL (x) <= 8)
2666                 *total = 0;
2667               else
2668                 *total = COSTS_N_INSNS (1);
2669               return true;
2670             }
2671
2672           /* We can use cmpi for an xor with an unsigned 16-bit value.  */
2673           if ((outer_code) == XOR
2674               && INTVAL (x) >= 0 && INTVAL (x) < 0x10000)
2675             {
2676               *total = 0;
2677               return true;
2678             }
2679
2680           /* We may be able to use slt or sltu for a comparison with a
2681              signed 16-bit value.  (The boundary conditions aren't quite
2682              right, but this is just a heuristic anyhow.)  */
2683           if (((outer_code) == LT || (outer_code) == LE
2684                || (outer_code) == GE || (outer_code) == GT
2685                || (outer_code) == LTU || (outer_code) == LEU
2686                || (outer_code) == GEU || (outer_code) == GTU)
2687               && INTVAL (x) >= -0x8000 && INTVAL (x) < 0x8000)
2688             {
2689               *total = 0;
2690               return true;
2691             }
2692
2693           /* Equality comparisons with 0 are cheap.  */
2694           if (((outer_code) == EQ || (outer_code) == NE)
2695               && INTVAL (x) == 0)
2696             {
2697               *total = 0;
2698               return true;
2699             }
2700
2701           /* Constants in the range 0...255 can be loaded with an unextended
2702              instruction.  They are therefore as cheap as a register move.
2703
2704              Given the choice between "li R1,0...255" and "move R1,R2"
2705              (where R2 is a known constant), it is usually better to use "li",
2706              since we do not want to unnecessarily extend the lifetime
2707              of R2.  */
2708           if (outer_code == SET
2709               && INTVAL (x) >= 0
2710               && INTVAL (x) < 256)
2711             {
2712               *total = 0;
2713               return true;
2714             }
2715         }
2716       else
2717         {
2718           /* These can be used anywhere. */
2719           *total = 0;
2720           return true;
2721         }
2722
2723       /* Otherwise fall through to the handling below because
2724          we'll need to construct the constant.  */
2725
2726     case CONST:
2727     case SYMBOL_REF:
2728     case LABEL_REF:
2729     case CONST_DOUBLE:
2730       if (LEGITIMATE_CONSTANT_P (x))
2731         {
2732           *total = COSTS_N_INSNS (1);
2733           return true;
2734         }
2735       else
2736         {
2737           /* The value will need to be fetched from the constant pool.  */
2738           *total = CONSTANT_POOL_COST;
2739           return true;
2740         }
2741
2742     case MEM:
2743       {
2744         /* If the address is legitimate, return the number of
2745            instructions it needs, otherwise use the default handling.  */
2746         int n = mips_address_insns (XEXP (x, 0), GET_MODE (x));
2747         if (n > 0)
2748           {
2749             *total = COSTS_N_INSNS (n + 1);
2750             return true;
2751           }
2752         return false;
2753       }
2754
2755     case FFS:
2756       *total = COSTS_N_INSNS (6);
2757       return true;
2758
2759     case NOT:
2760       *total = COSTS_N_INSNS ((mode == DImode && !TARGET_64BIT) ? 2 : 1);
2761       return true;
2762
2763     case AND:
2764     case IOR:
2765     case XOR:
2766       if (mode == DImode && !TARGET_64BIT)
2767         {
2768           *total = COSTS_N_INSNS (2);
2769           return true;
2770         }
2771       return false;
2772
2773     case ASHIFT:
2774     case ASHIFTRT:
2775     case LSHIFTRT:
2776       if (mode == DImode && !TARGET_64BIT)
2777         {
2778           *total = COSTS_N_INSNS ((GET_CODE (XEXP (x, 1)) == CONST_INT)
2779                                   ? 4 : 12);
2780           return true;
2781         }
2782       return false;
2783
2784     case ABS:
2785       if (float_mode_p)
2786         *total = COSTS_N_INSNS (1);
2787       else
2788         *total = COSTS_N_INSNS (4);
2789       return true;
2790
2791     case LO_SUM:
2792       *total = COSTS_N_INSNS (1);
2793       return true;
2794
2795     case PLUS:
2796     case MINUS:
2797       if (float_mode_p)
2798         {
2799           *total = mips_cost->fp_add;
2800           return true;
2801         }
2802
2803       else if (mode == DImode && !TARGET_64BIT)
2804         {
2805           *total = COSTS_N_INSNS (4);
2806           return true;
2807         }
2808       return false;
2809
2810     case NEG:
2811       if (mode == DImode && !TARGET_64BIT)
2812         {
2813           *total = COSTS_N_INSNS (4);
2814           return true;
2815         }
2816       return false;
2817
2818     case MULT:
2819       if (mode == SFmode)
2820         *total = mips_cost->fp_mult_sf;
2821
2822       else if (mode == DFmode)
2823         *total = mips_cost->fp_mult_df;
2824
2825       else if (mode == SImode)
2826         *total = mips_cost->int_mult_si;
2827
2828       else
2829         *total = mips_cost->int_mult_di;
2830
2831       return true;
2832
2833     case DIV:
2834     case MOD:
2835       if (float_mode_p)
2836         {
2837           if (mode == SFmode)
2838             *total = mips_cost->fp_div_sf;
2839           else
2840             *total = mips_cost->fp_div_df;
2841
2842           return true;
2843         }
2844       /* Fall through.  */
2845
2846     case UDIV:
2847     case UMOD:
2848       if (mode == DImode)
2849         *total = mips_cost->int_div_di;
2850       else
2851         *total = mips_cost->int_div_si;
2852
2853       return true;
2854
2855     case SIGN_EXTEND:
2856       /* A sign extend from SImode to DImode in 64-bit mode is often
2857          zero instructions, because the result can often be used
2858          directly by another instruction; we'll call it one.  */
2859       if (TARGET_64BIT && mode == DImode
2860           && GET_MODE (XEXP (x, 0)) == SImode)
2861         *total = COSTS_N_INSNS (1);
2862       else
2863         *total = COSTS_N_INSNS (2);
2864       return true;
2865
2866     case ZERO_EXTEND:
2867       if (TARGET_64BIT && mode == DImode
2868           && GET_MODE (XEXP (x, 0)) == SImode)
2869         *total = COSTS_N_INSNS (2);
2870       else
2871         *total = COSTS_N_INSNS (1);
2872       return true;
2873
2874     case FLOAT:
2875     case UNSIGNED_FLOAT:
2876     case FIX:
2877     case FLOAT_EXTEND:
2878     case FLOAT_TRUNCATE:
2879     case SQRT:
2880       *total = mips_cost->fp_add;
2881       return true;
2882
2883     default:
2884       return false;
2885     }
2886 }
2887
2888 /* Provide the costs of an addressing mode that contains ADDR.
2889    If ADDR is not a valid address, its cost is irrelevant.  */
2890
2891 static int
2892 mips_address_cost (rtx addr)
2893 {
2894   return mips_address_insns (addr, SImode);
2895 }
2896 \f
2897 /* Return one word of double-word value OP, taking into account the fixed
2898    endianness of certain registers.  HIGH_P is true to select the high part,
2899    false to select the low part.  */
2900
2901 rtx
2902 mips_subword (rtx op, int high_p)
2903 {
2904   unsigned int byte;
2905   enum machine_mode mode;
2906
2907   mode = GET_MODE (op);
2908   if (mode == VOIDmode)
2909     mode = DImode;
2910
2911   if (TARGET_BIG_ENDIAN ? !high_p : high_p)
2912     byte = UNITS_PER_WORD;
2913   else
2914     byte = 0;
2915
2916   if (REG_P (op))
2917     {
2918       if (FP_REG_P (REGNO (op)))
2919         return gen_rtx_REG (word_mode, high_p ? REGNO (op) + 1 : REGNO (op));
2920       if (ACC_HI_REG_P (REGNO (op)))
2921         return gen_rtx_REG (word_mode, high_p ? REGNO (op) : REGNO (op) + 1);
2922     }
2923
2924   if (MEM_P (op))
2925     return mips_rewrite_small_data (adjust_address (op, word_mode, byte));
2926
2927   return simplify_gen_subreg (word_mode, op, mode, byte);
2928 }
2929
2930
2931 /* Return true if a 64-bit move from SRC to DEST should be split into two.  */
2932
2933 bool
2934 mips_split_64bit_move_p (rtx dest, rtx src)
2935 {
2936   if (TARGET_64BIT)
2937     return false;
2938
2939   /* FP->FP moves can be done in a single instruction.  */
2940   if (FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
2941     return false;
2942
2943   /* Check for floating-point loads and stores.  They can be done using
2944      ldc1 and sdc1 on MIPS II and above.  */
2945   if (mips_isa > 1)
2946     {
2947       if (FP_REG_RTX_P (dest) && MEM_P (src))
2948         return false;
2949       if (FP_REG_RTX_P (src) && MEM_P (dest))
2950         return false;
2951     }
2952   return true;
2953 }
2954
2955
2956 /* Split a 64-bit move from SRC to DEST assuming that
2957    mips_split_64bit_move_p holds.
2958
2959    Moves into and out of FPRs cause some difficulty here.  Such moves
2960    will always be DFmode, since paired FPRs are not allowed to store
2961    DImode values.  The most natural representation would be two separate
2962    32-bit moves, such as:
2963
2964         (set (reg:SI $f0) (mem:SI ...))
2965         (set (reg:SI $f1) (mem:SI ...))
2966
2967    However, the second insn is invalid because odd-numbered FPRs are
2968    not allowed to store independent values.  Use the patterns load_df_low,
2969    load_df_high and store_df_high instead.  */
2970
2971 void
2972 mips_split_64bit_move (rtx dest, rtx src)
2973 {
2974   if (FP_REG_RTX_P (dest))
2975     {
2976       /* Loading an FPR from memory or from GPRs.  */
2977       if (ISA_HAS_MXHC1)
2978         {
2979           dest = gen_lowpart (DFmode, dest);
2980           emit_insn (gen_load_df_low (dest, mips_subword (src, 0)));
2981           emit_insn (gen_mthc1 (dest, mips_subword (src, 1),
2982                                 copy_rtx (dest)));
2983         }
2984       else
2985         {
2986           emit_insn (gen_load_df_low (copy_rtx (dest),
2987                                       mips_subword (src, 0)));
2988           emit_insn (gen_load_df_high (dest, mips_subword (src, 1),
2989                                        copy_rtx (dest)));
2990         }
2991     }
2992   else if (FP_REG_RTX_P (src))
2993     {
2994       /* Storing an FPR into memory or GPRs.  */
2995       if (ISA_HAS_MXHC1)
2996         {
2997           src = gen_lowpart (DFmode, src);
2998           emit_move_insn (mips_subword (dest, 0), mips_subword (src, 0));
2999           emit_insn (gen_mfhc1 (mips_subword (dest, 1), src));
3000         }
3001       else
3002         {
3003           emit_move_insn (mips_subword (dest, 0), mips_subword (src, 0));
3004           emit_insn (gen_store_df_high (mips_subword (dest, 1), src));
3005         }
3006     }
3007   else
3008     {
3009       /* The operation can be split into two normal moves.  Decide in
3010          which order to do them.  */
3011       rtx low_dest;
3012
3013       low_dest = mips_subword (dest, 0);
3014       if (REG_P (low_dest)
3015           && reg_overlap_mentioned_p (low_dest, src))
3016         {
3017           emit_move_insn (mips_subword (dest, 1), mips_subword (src, 1));
3018           emit_move_insn (low_dest, mips_subword (src, 0));
3019         }
3020       else
3021         {
3022           emit_move_insn (low_dest, mips_subword (src, 0));
3023           emit_move_insn (mips_subword (dest, 1), mips_subword (src, 1));
3024         }
3025     }
3026 }
3027 \f
3028 /* Return the appropriate instructions to move SRC into DEST.  Assume
3029    that SRC is operand 1 and DEST is operand 0.  */
3030
3031 const char *
3032 mips_output_move (rtx dest, rtx src)
3033 {
3034   enum rtx_code dest_code, src_code;
3035   bool dbl_p;
3036
3037   dest_code = GET_CODE (dest);
3038   src_code = GET_CODE (src);
3039   dbl_p = (GET_MODE_SIZE (GET_MODE (dest)) == 8);
3040
3041   if (dbl_p && mips_split_64bit_move_p (dest, src))
3042     return "#";
3043
3044   if ((src_code == REG && GP_REG_P (REGNO (src)))
3045       || (!TARGET_MIPS16 && src == CONST0_RTX (GET_MODE (dest))))
3046     {
3047       if (dest_code == REG)
3048         {
3049           if (GP_REG_P (REGNO (dest)))
3050             return "move\t%0,%z1";
3051
3052           if (MD_REG_P (REGNO (dest)))
3053             return "mt%0\t%z1";
3054
3055           if (DSP_ACC_REG_P (REGNO (dest)))
3056             {
3057               static char retval[] = "mt__\t%z1,%q0";
3058               retval[2] = reg_names[REGNO (dest)][4];
3059               retval[3] = reg_names[REGNO (dest)][5];
3060               return retval;
3061             }
3062
3063           if (FP_REG_P (REGNO (dest)))
3064             return (dbl_p ? "dmtc1\t%z1,%0" : "mtc1\t%z1,%0");
3065
3066           if (ALL_COP_REG_P (REGNO (dest)))
3067             {
3068               static char retval[] = "dmtc_\t%z1,%0";
3069
3070               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
3071               return (dbl_p ? retval : retval + 1);
3072             }
3073         }
3074       if (dest_code == MEM)
3075         return (dbl_p ? "sd\t%z1,%0" : "sw\t%z1,%0");
3076     }
3077   if (dest_code == REG && GP_REG_P (REGNO (dest)))
3078     {
3079       if (src_code == REG)
3080         {
3081           if (DSP_ACC_REG_P (REGNO (src)))
3082             {
3083               static char retval[] = "mf__\t%0,%q1";
3084               retval[2] = reg_names[REGNO (src)][4];
3085               retval[3] = reg_names[REGNO (src)][5];
3086               return retval;
3087             }
3088
3089           if (ST_REG_P (REGNO (src)) && ISA_HAS_8CC)
3090             return "lui\t%0,0x3f80\n\tmovf\t%0,%.,%1";
3091
3092           if (FP_REG_P (REGNO (src)))
3093             return (dbl_p ? "dmfc1\t%0,%1" : "mfc1\t%0,%1");
3094
3095           if (ALL_COP_REG_P (REGNO (src)))
3096             {
3097               static char retval[] = "dmfc_\t%0,%1";
3098
3099               retval[4] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
3100               return (dbl_p ? retval : retval + 1);
3101             }
3102         }
3103
3104       if (src_code == MEM)
3105         return (dbl_p ? "ld\t%0,%1" : "lw\t%0,%1");
3106
3107       if (src_code == CONST_INT)
3108         {
3109           /* Don't use the X format, because that will give out of
3110              range numbers for 64-bit hosts and 32-bit targets.  */
3111           if (!TARGET_MIPS16)
3112             return "li\t%0,%1\t\t\t# %X1";
3113
3114           if (INTVAL (src) >= 0 && INTVAL (src) <= 0xffff)
3115             return "li\t%0,%1";
3116
3117           if (INTVAL (src) < 0 && INTVAL (src) >= -0xffff)
3118             return "#";
3119         }
3120
3121       if (src_code == HIGH)
3122         return "lui\t%0,%h1";
3123
3124       if (CONST_GP_P (src))
3125         return "move\t%0,%1";
3126
3127       if (symbolic_operand (src, VOIDmode))
3128         return (dbl_p ? "dla\t%0,%1" : "la\t%0,%1");
3129     }
3130   if (src_code == REG && FP_REG_P (REGNO (src)))
3131     {
3132       if (dest_code == REG && FP_REG_P (REGNO (dest)))
3133         {
3134           if (GET_MODE (dest) == V2SFmode)
3135             return "mov.ps\t%0,%1";
3136           else
3137             return (dbl_p ? "mov.d\t%0,%1" : "mov.s\t%0,%1");
3138         }
3139
3140       if (dest_code == MEM)
3141         return (dbl_p ? "sdc1\t%1,%0" : "swc1\t%1,%0");
3142     }
3143   if (dest_code == REG && FP_REG_P (REGNO (dest)))
3144     {
3145       if (src_code == MEM)
3146         return (dbl_p ? "ldc1\t%0,%1" : "lwc1\t%0,%1");
3147     }
3148   if (dest_code == REG && ALL_COP_REG_P (REGNO (dest)) && src_code == MEM)
3149     {
3150       static char retval[] = "l_c_\t%0,%1";
3151
3152       retval[1] = (dbl_p ? 'd' : 'w');
3153       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (dest));
3154       return retval;
3155     }
3156   if (dest_code == MEM && src_code == REG && ALL_COP_REG_P (REGNO (src)))
3157     {
3158       static char retval[] = "s_c_\t%1,%0";
3159
3160       retval[1] = (dbl_p ? 'd' : 'w');
3161       retval[3] = COPNUM_AS_CHAR_FROM_REGNUM (REGNO (src));
3162       return retval;
3163     }
3164   gcc_unreachable ();
3165 }
3166 \f
3167 /* Restore $gp from its save slot.  Valid only when using o32 or
3168    o64 abicalls.  */
3169
3170 void
3171 mips_restore_gp (void)
3172 {
3173   rtx address, slot;
3174
3175   gcc_assert (TARGET_ABICALLS && TARGET_OLDABI);
3176
3177   address = mips_add_offset (pic_offset_table_rtx,
3178                              frame_pointer_needed
3179                              ? hard_frame_pointer_rtx
3180                              : stack_pointer_rtx,
3181                              current_function_outgoing_args_size);
3182   slot = gen_rtx_MEM (Pmode, address);
3183
3184   emit_move_insn (pic_offset_table_rtx, slot);
3185   if (!TARGET_EXPLICIT_RELOCS)
3186     emit_insn (gen_blockage ());
3187 }
3188 \f
3189 /* Emit an instruction of the form (set TARGET (CODE OP0 OP1)).  */
3190
3191 static void
3192 mips_emit_binary (enum rtx_code code, rtx target, rtx op0, rtx op1)
3193 {
3194   emit_insn (gen_rtx_SET (VOIDmode, target,
3195                           gen_rtx_fmt_ee (code, GET_MODE (target), op0, op1)));
3196 }
3197
3198 /* Return true if CMP1 is a suitable second operand for relational
3199    operator CODE.  See also the *sCC patterns in mips.md.  */
3200
3201 static bool
3202 mips_relational_operand_ok_p (enum rtx_code code, rtx cmp1)
3203 {
3204   switch (code)
3205     {
3206     case GT:
3207     case GTU:
3208       return reg_or_0_operand (cmp1, VOIDmode);
3209
3210     case GE:
3211     case GEU:
3212       return !TARGET_MIPS16 && cmp1 == const1_rtx;
3213
3214     case LT:
3215     case LTU:
3216       return arith_operand (cmp1, VOIDmode);
3217
3218     case LE:
3219       return sle_operand (cmp1, VOIDmode);
3220
3221     case LEU:
3222       return sleu_operand (cmp1, VOIDmode);
3223
3224     default:
3225       gcc_unreachable ();
3226     }
3227 }
3228
3229 /* Canonicalize LE or LEU comparisons into LT comparisons when
3230    possible to avoid extra instructions or inverting the
3231    comparison.  */
3232
3233 static bool
3234 mips_canonicalize_comparison (enum rtx_code *code, rtx *cmp1,
3235                               enum machine_mode mode)
3236 {
3237   HOST_WIDE_INT original, plus_one;
3238
3239   if (GET_CODE (*cmp1) != CONST_INT)
3240     return false;
3241
3242   original = INTVAL (*cmp1);
3243   plus_one = trunc_int_for_mode ((unsigned HOST_WIDE_INT) original + 1, mode);
3244
3245   switch (*code)
3246     {
3247     case LE:
3248       if (original < plus_one)
3249         {
3250           *code = LT;
3251           *cmp1 = force_reg (mode, GEN_INT (plus_one));
3252           return true;
3253         }
3254       break;
3255
3256     case LEU:
3257       if (plus_one != 0)
3258         {
3259           *code = LTU;
3260           *cmp1 = force_reg (mode, GEN_INT (plus_one));
3261           return true;
3262         }
3263       break;
3264
3265     default:
3266       return false;
3267    }
3268
3269   return false;
3270
3271 }
3272
3273 /* Compare CMP0 and CMP1 using relational operator CODE and store the
3274    result in TARGET.  CMP0 and TARGET are register_operands that have
3275    the same integer mode.  If INVERT_PTR is nonnull, it's OK to set
3276    TARGET to the inverse of the result and flip *INVERT_PTR instead.  */
3277
3278 static void
3279 mips_emit_int_relational (enum rtx_code code, bool *invert_ptr,
3280                           rtx target, rtx cmp0, rtx cmp1)
3281 {
3282   /* First see if there is a MIPS instruction that can do this operation
3283      with CMP1 in its current form. If not, try to canonicalize the
3284      comparison to LT. If that fails, try doing the same for the
3285      inverse operation.  If that also fails, force CMP1 into a register
3286      and try again.  */
3287   if (mips_relational_operand_ok_p (code, cmp1))
3288     mips_emit_binary (code, target, cmp0, cmp1);
3289   else if (mips_canonicalize_comparison (&code, &cmp1, GET_MODE (target)))
3290     mips_emit_binary (code, target, cmp0, cmp1);
3291   else
3292     {
3293       enum rtx_code inv_code = reverse_condition (code);
3294       if (!mips_relational_operand_ok_p (inv_code, cmp1))
3295         {
3296           cmp1 = force_reg (GET_MODE (cmp0), cmp1);
3297           mips_emit_int_relational (code, invert_ptr, target, cmp0, cmp1);
3298         }
3299       else if (invert_ptr == 0)
3300         {
3301           rtx inv_target = gen_reg_rtx (GET_MODE (target));
3302           mips_emit_binary (inv_code, inv_target, cmp0, cmp1);
3303           mips_emit_binary (XOR, target, inv_target, const1_rtx);
3304         }
3305       else
3306         {
3307           *invert_ptr = !*invert_ptr;
3308           mips_emit_binary (inv_code, target, cmp0, cmp1);
3309         }
3310     }
3311 }
3312
3313 /* Return a register that is zero iff CMP0 and CMP1 are equal.
3314    The register will have the same mode as CMP0.  */
3315
3316 static rtx
3317 mips_zero_if_equal (rtx cmp0, rtx cmp1)
3318 {
3319   if (cmp1 == const0_rtx)
3320     return cmp0;
3321
3322   if (uns_arith_operand (cmp1, VOIDmode))
3323     return expand_binop (GET_MODE (cmp0), xor_optab,
3324                          cmp0, cmp1, 0, 0, OPTAB_DIRECT);
3325
3326   return expand_binop (GET_MODE (cmp0), sub_optab,
3327                        cmp0, cmp1, 0, 0, OPTAB_DIRECT);
3328 }
3329
3330 /* Convert *CODE into a code that can be used in a floating-point
3331    scc instruction (c.<cond>.<fmt>).  Return true if the values of
3332    the condition code registers will be inverted, with 0 indicating
3333    that the condition holds.  */
3334
3335 static bool
3336 mips_reverse_fp_cond_p (enum rtx_code *code)
3337 {
3338   switch (*code)
3339     {
3340     case NE:
3341     case LTGT:
3342     case ORDERED:
3343       *code = reverse_condition_maybe_unordered (*code);
3344       return true;
3345
3346     default:
3347       return false;
3348     }
3349 }
3350
3351 /* Convert a comparison into something that can be used in a branch or
3352    conditional move.  cmp_operands[0] and cmp_operands[1] are the values
3353    being compared and *CODE is the code used to compare them.
3354
3355    Update *CODE, *OP0 and *OP1 so that they describe the final comparison.
3356    If NEED_EQ_NE_P, then only EQ/NE comparisons against zero are possible,
3357    otherwise any standard branch condition can be used.  The standard branch
3358    conditions are:
3359
3360       - EQ/NE between two registers.
3361       - any comparison between a register and zero.  */
3362
3363 static void
3364 mips_emit_compare (enum rtx_code *code, rtx *op0, rtx *op1, bool need_eq_ne_p)
3365 {
3366   if (GET_MODE_CLASS (GET_MODE (cmp_operands[0])) == MODE_INT)
3367     {
3368       if (!need_eq_ne_p && cmp_operands[1] == const0_rtx)
3369         {
3370           *op0 = cmp_operands[0];
3371           *op1 = cmp_operands[1];
3372         }
3373       else if (*code == EQ || *code == NE)
3374         {
3375           if (need_eq_ne_p)
3376             {
3377               *op0 = mips_zero_if_equal (cmp_operands[0], cmp_operands[1]);
3378               *op1 = const0_rtx;
3379             }
3380           else
3381             {
3382               *op0 = cmp_operands[0];
3383               *op1 = force_reg (GET_MODE (*op0), cmp_operands[1]);
3384             }
3385         }
3386       else
3387         {
3388           /* The comparison needs a separate scc instruction.  Store the
3389              result of the scc in *OP0 and compare it against zero.  */
3390           bool invert = false;
3391           *op0 = gen_reg_rtx (GET_MODE (cmp_operands[0]));
3392           *op1 = const0_rtx;
3393           mips_emit_int_relational (*code, &invert, *op0,
3394                                     cmp_operands[0], cmp_operands[1]);
3395           *code = (invert ? EQ : NE);
3396         }
3397     }
3398   else
3399     {
3400       enum rtx_code cmp_code;
3401
3402       /* Floating-point tests use a separate c.cond.fmt comparison to
3403          set a condition code register.  The branch or conditional move
3404          will then compare that register against zero.
3405
3406          Set CMP_CODE to the code of the comparison instruction and
3407          *CODE to the code that the branch or move should use.  */
3408       cmp_code = *code;
3409       *code = mips_reverse_fp_cond_p (&cmp_code) ? EQ : NE;
3410       *op0 = (ISA_HAS_8CC
3411               ? gen_reg_rtx (CCmode)
3412               : gen_rtx_REG (CCmode, FPSW_REGNUM));
3413       *op1 = const0_rtx;
3414       mips_emit_binary (cmp_code, *op0, cmp_operands[0], cmp_operands[1]);
3415     }
3416 }
3417 \f
3418 /* Try comparing cmp_operands[0] and cmp_operands[1] using rtl code CODE.
3419    Store the result in TARGET and return true if successful.
3420
3421    On 64-bit targets, TARGET may be wider than cmp_operands[0].  */
3422
3423 bool
3424 mips_emit_scc (enum rtx_code code, rtx target)
3425 {
3426   if (GET_MODE_CLASS (GET_MODE (cmp_operands[0])) != MODE_INT)
3427     return false;
3428
3429   target = gen_lowpart (GET_MODE (cmp_operands[0]), target);
3430   if (code == EQ || code == NE)
3431     {
3432       rtx zie = mips_zero_if_equal (cmp_operands[0], cmp_operands[1]);
3433       mips_emit_binary (code, target, zie, const0_rtx);
3434     }
3435   else
3436     mips_emit_int_relational (code, 0, target,
3437                               cmp_operands[0], cmp_operands[1]);
3438   return true;
3439 }
3440
3441 /* Emit the common code for doing conditional branches.
3442    operand[0] is the label to jump to.
3443    The comparison operands are saved away by cmp{si,di,sf,df}.  */
3444
3445 void
3446 gen_conditional_branch (rtx *operands, enum rtx_code code)
3447 {
3448   rtx op0, op1, condition;
3449
3450   mips_emit_compare (&code, &op0, &op1, TARGET_MIPS16);
3451   condition = gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
3452   emit_jump_insn (gen_condjump (condition, operands[0]));
3453 }
3454
3455 /* Implement:
3456
3457    (set temp (COND:CCV2 CMP_OP0 CMP_OP1))
3458    (set DEST (unspec [TRUE_SRC FALSE_SRC temp] UNSPEC_MOVE_TF_PS))  */
3459
3460 void
3461 mips_expand_vcondv2sf (rtx dest, rtx true_src, rtx false_src,
3462                        enum rtx_code cond, rtx cmp_op0, rtx cmp_op1)
3463 {
3464   rtx cmp_result;
3465   bool reversed_p;
3466
3467   reversed_p = mips_reverse_fp_cond_p (&cond);
3468   cmp_result = gen_reg_rtx (CCV2mode);
3469   emit_insn (gen_scc_ps (cmp_result,
3470                          gen_rtx_fmt_ee (cond, VOIDmode, cmp_op0, cmp_op1)));
3471   if (reversed_p)
3472     emit_insn (gen_mips_cond_move_tf_ps (dest, false_src, true_src,
3473                                          cmp_result));
3474   else
3475     emit_insn (gen_mips_cond_move_tf_ps (dest, true_src, false_src,
3476                                          cmp_result));
3477 }
3478
3479 /* Emit the common code for conditional moves.  OPERANDS is the array
3480    of operands passed to the conditional move define_expand.  */
3481
3482 void
3483 gen_conditional_move (rtx *operands)
3484 {
3485   enum rtx_code code;
3486   rtx op0, op1;
3487
3488   code = GET_CODE (operands[1]);
3489   mips_emit_compare (&code, &op0, &op1, true);
3490   emit_insn (gen_rtx_SET (VOIDmode, operands[0],
3491                           gen_rtx_IF_THEN_ELSE (GET_MODE (operands[0]),
3492                                                 gen_rtx_fmt_ee (code,
3493                                                                 GET_MODE (op0),
3494                                                                 op0, op1),
3495                                                 operands[2], operands[3])));
3496 }
3497
3498 /* Emit a conditional trap.  OPERANDS is the array of operands passed to
3499    the conditional_trap expander.  */
3500
3501 void
3502 mips_gen_conditional_trap (rtx *operands)
3503 {
3504   rtx op0, op1;
3505   enum rtx_code cmp_code = GET_CODE (operands[0]);
3506   enum machine_mode mode = GET_MODE (cmp_operands[0]);
3507
3508   /* MIPS conditional trap machine instructions don't have GT or LE
3509      flavors, so we must invert the comparison and convert to LT and
3510      GE, respectively.  */
3511   switch (cmp_code)
3512     {
3513     case GT: cmp_code = LT; break;
3514     case LE: cmp_code = GE; break;
3515     case GTU: cmp_code = LTU; break;
3516     case LEU: cmp_code = GEU; break;
3517     default: break;
3518     }
3519   if (cmp_code == GET_CODE (operands[0]))
3520     {
3521       op0 = cmp_operands[0];
3522       op1 = cmp_operands[1];
3523     }
3524   else
3525     {
3526       op0 = cmp_operands[1];
3527       op1 = cmp_operands[0];
3528     }
3529   op0 = force_reg (mode, op0);
3530   if (!arith_operand (op1, mode))
3531     op1 = force_reg (mode, op1);
3532
3533   emit_insn (gen_rtx_TRAP_IF (VOIDmode,
3534                               gen_rtx_fmt_ee (cmp_code, mode, op0, op1),
3535                               operands[1]));
3536 }
3537 \f
3538 /* Return true if calls to X can use R_MIPS_CALL* relocations.  */
3539
3540 static bool
3541 mips_ok_for_lazy_binding_p (rtx x)
3542 {
3543   return (TARGET_USE_GOT
3544           && GET_CODE (x) == SYMBOL_REF
3545           && !mips_symbol_binds_local_p (x));
3546 }
3547
3548 /* Load function address ADDR into register DEST.  SIBCALL_P is true
3549    if the address is needed for a sibling call.  */
3550
3551 static void
3552 mips_load_call_address (rtx dest, rtx addr, int sibcall_p)
3553 {
3554   /* If we're generating PIC, and this call is to a global function,
3555      try to allow its address to be resolved lazily.  This isn't
3556      possible if TARGET_CALL_SAVED_GP since the value of $gp on entry
3557      to the stub would be our caller's gp, not ours.  */
3558   if (TARGET_EXPLICIT_RELOCS
3559       && !(sibcall_p && TARGET_CALL_SAVED_GP)
3560       && mips_ok_for_lazy_binding_p (addr))
3561     {
3562       rtx high, lo_sum_symbol;
3563
3564       high = mips_unspec_offset_high (dest, pic_offset_table_rtx,
3565                                       addr, SYMBOL_GOTOFF_CALL);
3566       lo_sum_symbol = mips_unspec_address (addr, SYMBOL_GOTOFF_CALL);
3567       if (Pmode == SImode)
3568         emit_insn (gen_load_callsi (dest, high, lo_sum_symbol));
3569       else
3570         emit_insn (gen_load_calldi (dest, high, lo_sum_symbol));
3571     }
3572   else
3573     emit_move_insn (dest, addr);
3574 }
3575
3576
3577 /* Expand a call or call_value instruction.  RESULT is where the
3578    result will go (null for calls), ADDR is the address of the
3579    function, ARGS_SIZE is the size of the arguments and AUX is
3580    the value passed to us by mips_function_arg.  SIBCALL_P is true
3581    if we are expanding a sibling call, false if we're expanding
3582    a normal call.  */
3583
3584 void
3585 mips_expand_call (rtx result, rtx addr, rtx args_size, rtx aux, int sibcall_p)
3586 {
3587   rtx orig_addr, pattern, insn;
3588
3589   orig_addr = addr;
3590   if (!call_insn_operand (addr, VOIDmode))
3591     {
3592       addr = gen_reg_rtx (Pmode);
3593       mips_load_call_address (addr, orig_addr, sibcall_p);
3594     }
3595
3596   if (mips16_hard_float
3597       && build_mips16_call_stub (result, addr, args_size,
3598                                  aux == 0 ? 0 : (int) GET_MODE (aux)))
3599     return;
3600
3601   if (result == 0)
3602     pattern = (sibcall_p
3603                ? gen_sibcall_internal (addr, args_size)
3604                : gen_call_internal (addr, args_size));
3605   else if (GET_CODE (result) == PARALLEL && XVECLEN (result, 0) == 2)
3606     {
3607       rtx reg1, reg2;
3608
3609       reg1 = XEXP (XVECEXP (result, 0, 0), 0);
3610       reg2 = XEXP (XVECEXP (result, 0, 1), 0);
3611       pattern =
3612         (sibcall_p
3613          ? gen_sibcall_value_multiple_internal (reg1, addr, args_size, reg2)
3614          : gen_call_value_multiple_internal (reg1, addr, args_size, reg2));
3615     }
3616   else
3617     pattern = (sibcall_p
3618                ? gen_sibcall_value_internal (result, addr, args_size)
3619                : gen_call_value_internal (result, addr, args_size));
3620
3621   insn = emit_call_insn (pattern);
3622
3623   /* Lazy-binding stubs require $gp to be valid on entry.  */
3624   if (mips_ok_for_lazy_binding_p (orig_addr))
3625     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
3626 }
3627
3628
3629 /* We can handle any sibcall when TARGET_SIBCALLS is true.  */
3630
3631 static bool
3632 mips_function_ok_for_sibcall (tree decl ATTRIBUTE_UNUSED,
3633                               tree exp ATTRIBUTE_UNUSED)
3634 {
3635   return TARGET_SIBCALLS;
3636 }
3637 \f
3638 /* Emit code to move general operand SRC into condition-code
3639    register DEST.  SCRATCH is a scratch TFmode float register.
3640    The sequence is:
3641
3642         FP1 = SRC
3643         FP2 = 0.0f
3644         DEST = FP2 < FP1
3645
3646    where FP1 and FP2 are single-precision float registers
3647    taken from SCRATCH.  */
3648
3649 void
3650 mips_emit_fcc_reload (rtx dest, rtx src, rtx scratch)
3651 {
3652   rtx fp1, fp2;
3653
3654   /* Change the source to SFmode.  */
3655   if (MEM_P (src))
3656     src = adjust_address (src, SFmode, 0);
3657   else if (REG_P (src) || GET_CODE (src) == SUBREG)
3658     src = gen_rtx_REG (SFmode, true_regnum (src));
3659
3660   fp1 = gen_rtx_REG (SFmode, REGNO (scratch));
3661   fp2 = gen_rtx_REG (SFmode, REGNO (scratch) + MAX_FPRS_PER_FMT);
3662
3663   emit_move_insn (copy_rtx (fp1), src);
3664   emit_move_insn (copy_rtx (fp2), CONST0_RTX (SFmode));
3665   emit_insn (gen_slt_sf (dest, fp2, fp1));
3666 }
3667 \f
3668 /* Emit code to change the current function's return address to
3669    ADDRESS.  SCRATCH is available as a scratch register, if needed.
3670    ADDRESS and SCRATCH are both word-mode GPRs.  */
3671
3672 void
3673 mips_set_return_address (rtx address, rtx scratch)
3674 {
3675   rtx slot_address;
3676
3677   compute_frame_size (get_frame_size ());
3678   gcc_assert ((cfun->machine->frame.mask >> 31) & 1);
3679   slot_address = mips_add_offset (scratch, stack_pointer_rtx,
3680                                   cfun->machine->frame.gp_sp_offset);
3681
3682   emit_move_insn (gen_rtx_MEM (GET_MODE (address), slot_address), address);
3683 }
3684 \f
3685 /* Emit straight-line code to move LENGTH bytes from SRC to DEST.
3686    Assume that the areas do not overlap.  */
3687
3688 static void
3689 mips_block_move_straight (rtx dest, rtx src, HOST_WIDE_INT length)
3690 {
3691   HOST_WIDE_INT offset, delta;
3692   unsigned HOST_WIDE_INT bits;
3693   int i;
3694   enum machine_mode mode;
3695   rtx *regs;
3696
3697   /* Work out how many bits to move at a time.  If both operands have
3698      half-word alignment, it is usually better to move in half words.
3699      For instance, lh/lh/sh/sh is usually better than lwl/lwr/swl/swr
3700      and lw/lw/sw/sw is usually better than ldl/ldr/sdl/sdr.
3701      Otherwise move word-sized chunks.  */
3702   if (MEM_ALIGN (src) == BITS_PER_WORD / 2
3703       && MEM_ALIGN (dest) == BITS_PER_WORD / 2)
3704     bits = BITS_PER_WORD / 2;
3705   else
3706     bits = BITS_PER_WORD;
3707
3708   mode = mode_for_size (bits, MODE_INT, 0);
3709   delta = bits / BITS_PER_UNIT;
3710
3711   /* Allocate a buffer for the temporary registers.  */
3712   regs = alloca (sizeof (rtx) * length / delta);
3713
3714   /* Load as many BITS-sized chunks as possible.  Use a normal load if
3715      the source has enough alignment, otherwise use left/right pairs.  */
3716   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
3717     {
3718       regs[i] = gen_reg_rtx (mode);
3719       if (MEM_ALIGN (src) >= bits)
3720         emit_move_insn (regs[i], adjust_address (src, mode, offset));
3721       else
3722         {
3723           rtx part = adjust_address (src, BLKmode, offset);
3724           if (!mips_expand_unaligned_load (regs[i], part, bits, 0))
3725             gcc_unreachable ();
3726         }
3727     }
3728
3729   /* Copy the chunks to the destination.  */
3730   for (offset = 0, i = 0; offset + delta <= length; offset += delta, i++)
3731     if (MEM_ALIGN (dest) >= bits)
3732       emit_move_insn (adjust_address (dest, mode, offset), regs[i]);
3733     else
3734       {
3735         rtx part = adjust_address (dest, BLKmode, offset);
3736         if (!mips_expand_unaligned_store (part, regs[i], bits, 0))
3737           gcc_unreachable ();
3738       }
3739
3740   /* Mop up any left-over bytes.  */
3741   if (offset < length)
3742     {
3743       src = adjust_address (src, BLKmode, offset);
3744       dest = adjust_address (dest, BLKmode, offset);
3745       move_by_pieces (dest, src, length - offset,
3746                       MIN (MEM_ALIGN (src), MEM_ALIGN (dest)), 0);
3747     }
3748 }
3749 \f
3750 #define MAX_MOVE_REGS 4
3751 #define MAX_MOVE_BYTES (MAX_MOVE_REGS * UNITS_PER_WORD)
3752
3753
3754 /* Helper function for doing a loop-based block operation on memory
3755    reference MEM.  Each iteration of the loop will operate on LENGTH
3756    bytes of MEM.
3757
3758    Create a new base register for use within the loop and point it to
3759    the start of MEM.  Create a new memory reference that uses this
3760    register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
3761
3762 static void
3763 mips_adjust_block_mem (rtx mem, HOST_WIDE_INT length,
3764                        rtx *loop_reg, rtx *loop_mem)
3765 {
3766   *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
3767
3768   /* Although the new mem does not refer to a known location,
3769      it does keep up to LENGTH bytes of alignment.  */
3770   *loop_mem = change_address (mem, BLKmode, *loop_reg);
3771   set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
3772 }
3773
3774
3775 /* Move LENGTH bytes from SRC to DEST using a loop that moves MAX_MOVE_BYTES
3776    per iteration.  LENGTH must be at least MAX_MOVE_BYTES.  Assume that the
3777    memory regions do not overlap.  */
3778
3779 static void
3780 mips_block_move_loop (rtx dest, rtx src, HOST_WIDE_INT length)
3781 {
3782   rtx label, src_reg, dest_reg, final_src;
3783   HOST_WIDE_INT leftover;
3784
3785   leftover = length % MAX_MOVE_BYTES;
3786   length -= leftover;
3787
3788   /* Create registers and memory references for use within the loop.  */
3789   mips_adjust_block_mem (src, MAX_MOVE_BYTES, &src_reg, &src);
3790   mips_adjust_block_mem (dest, MAX_MOVE_BYTES, &dest_reg, &dest);
3791
3792   /* Calculate the value that SRC_REG should have after the last iteration
3793      of the loop.  */
3794   final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
3795                                    0, 0, OPTAB_WIDEN);
3796
3797   /* Emit the start of the loop.  */
3798   label = gen_label_rtx ();
3799   emit_label (label);
3800
3801   /* Emit the loop body.  */
3802   mips_block_move_straight (dest, src, MAX_MOVE_BYTES);
3803
3804   /* Move on to the next block.  */
3805   emit_move_insn (src_reg, plus_constant (src_reg, MAX_MOVE_BYTES));
3806   emit_move_insn (dest_reg, plus_constant (dest_reg, MAX_MOVE_BYTES));
3807
3808   /* Emit the loop condition.  */
3809   if (Pmode == DImode)
3810     emit_insn (gen_cmpdi (src_reg, final_src));
3811   else
3812     emit_insn (gen_cmpsi (src_reg, final_src));
3813   emit_jump_insn (gen_bne (label));
3814
3815   /* Mop up any left-over bytes.  */
3816   if (leftover)
3817     mips_block_move_straight (dest, src, leftover);
3818 }
3819 \f
3820 /* Expand a movmemsi instruction.  */
3821
3822 bool
3823 mips_expand_block_move (rtx dest, rtx src, rtx length)
3824 {
3825   if (GET_CODE (length) == CONST_INT)
3826     {
3827       if (INTVAL (length) <= 2 * MAX_MOVE_BYTES)
3828         {
3829           mips_block_move_straight (dest, src, INTVAL (length));
3830           return true;
3831         }
3832       else if (optimize)
3833         {
3834           mips_block_move_loop (dest, src, INTVAL (length));
3835           return true;
3836         }
3837     }
3838   return false;
3839 }
3840 \f
3841 /* Argument support functions.  */
3842
3843 /* Initialize CUMULATIVE_ARGS for a function.  */
3844
3845 void
3846 init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
3847                       rtx libname ATTRIBUTE_UNUSED)
3848 {
3849   static CUMULATIVE_ARGS zero_cum;
3850   tree param, next_param;
3851
3852   *cum = zero_cum;
3853   cum->prototype = (fntype && TYPE_ARG_TYPES (fntype));
3854
3855   /* Determine if this function has variable arguments.  This is
3856      indicated by the last argument being 'void_type_mode' if there
3857      are no variable arguments.  The standard MIPS calling sequence
3858      passes all arguments in the general purpose registers in this case.  */
3859
3860   for (param = fntype ? TYPE_ARG_TYPES (fntype) : 0;
3861        param != 0; param = next_param)
3862     {
3863       next_param = TREE_CHAIN (param);
3864       if (next_param == 0 && TREE_VALUE (param) != void_type_node)
3865         cum->gp_reg_found = 1;
3866     }
3867 }
3868
3869
3870 /* Fill INFO with information about a single argument.  CUM is the
3871    cumulative state for earlier arguments.  MODE is the mode of this
3872    argument and TYPE is its type (if known).  NAMED is true if this
3873    is a named (fixed) argument rather than a variable one.  */
3874
3875 static void
3876 mips_arg_info (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
3877                tree type, int named, struct mips_arg_info *info)
3878 {
3879   bool doubleword_aligned_p;
3880   unsigned int num_bytes, num_words, max_regs;
3881
3882   /* Work out the size of the argument.  */
3883   num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
3884   num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
3885
3886   /* Decide whether it should go in a floating-point register, assuming
3887      one is free.  Later code checks for availability.
3888
3889      The checks against UNITS_PER_FPVALUE handle the soft-float and
3890      single-float cases.  */
3891   switch (mips_abi)
3892     {
3893     case ABI_EABI:
3894       /* The EABI conventions have traditionally been defined in terms
3895          of TYPE_MODE, regardless of the actual type.  */
3896       info->fpr_p = ((GET_MODE_CLASS (mode) == MODE_FLOAT
3897                       || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
3898                      && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
3899       break;
3900
3901     case ABI_32:
3902     case ABI_O64:
3903       /* Only leading floating-point scalars are passed in
3904          floating-point registers.  We also handle vector floats the same
3905          say, which is OK because they are not covered by the standard ABI.  */
3906       info->fpr_p = (!cum->gp_reg_found
3907                      && cum->arg_number < 2
3908                      && (type == 0 || SCALAR_FLOAT_TYPE_P (type)
3909                          || VECTOR_FLOAT_TYPE_P (type))
3910                      && (GET_MODE_CLASS (mode) == MODE_FLOAT
3911                          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
3912                      && GET_MODE_SIZE (mode) <= UNITS_PER_FPVALUE);
3913       break;
3914
3915     case ABI_N32:
3916     case ABI_64:
3917       /* Scalar and complex floating-point types are passed in
3918          floating-point registers.  */
3919       info->fpr_p = (named
3920                      && (type == 0 || FLOAT_TYPE_P (type))
3921                      && (GET_MODE_CLASS (mode) == MODE_FLOAT
3922                          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
3923                          || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
3924                      && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FPVALUE);
3925
3926       /* ??? According to the ABI documentation, the real and imaginary
3927          parts of complex floats should be passed in individual registers.
3928          The real and imaginary parts of stack arguments are supposed
3929          to be contiguous and there should be an extra word of padding
3930          at the end.
3931
3932          This has two problems.  First, it makes it impossible to use a
3933          single "void *" va_list type, since register and stack arguments
3934          are passed differently.  (At the time of writing, MIPSpro cannot
3935          handle complex float varargs correctly.)  Second, it's unclear
3936          what should happen when there is only one register free.
3937
3938          For now, we assume that named complex floats should go into FPRs
3939          if there are two FPRs free, otherwise they should be passed in the
3940          same way as a struct containing two floats.  */
3941       if (info->fpr_p
3942           && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
3943           && GET_MODE_UNIT_SIZE (mode) < UNITS_PER_FPVALUE)
3944         {
3945           if (cum->num_gprs >= MAX_ARGS_IN_REGISTERS - 1)
3946             info->fpr_p = false;
3947           else
3948             num_words = 2;
3949         }
3950       break;
3951
3952     default:
3953       gcc_unreachable ();
3954     }
3955
3956   /* See whether the argument has doubleword alignment.  */
3957   doubleword_aligned_p = FUNCTION_ARG_BOUNDARY (mode, type) > BITS_PER_WORD;
3958
3959   /* Set REG_OFFSET to the register count we're interested in.
3960      The EABI allocates the floating-point registers separately,
3961      but the other ABIs allocate them like integer registers.  */
3962   info->reg_offset = (mips_abi == ABI_EABI && info->fpr_p
3963                       ? cum->num_fprs
3964                       : cum->num_gprs);
3965
3966   /* Advance to an even register if the argument is doubleword-aligned.  */
3967   if (doubleword_aligned_p)
3968     info->reg_offset += info->reg_offset & 1;
3969
3970   /* Work out the offset of a stack argument.  */
3971   info->stack_offset = cum->stack_words;
3972   if (doubleword_aligned_p)
3973     info->stack_offset += info->stack_offset & 1;
3974
3975   max_regs = MAX_ARGS_IN_REGISTERS - info->reg_offset;
3976
3977   /* Partition the argument between registers and stack.  */
3978   info->reg_words = MIN (num_words, max_regs);
3979   info->stack_words = num_words - info->reg_words;
3980 }
3981
3982
3983 /* INFO describes an argument that is passed in a single-register value.
3984    Return the register it uses, assuming that FPRs are available if
3985    HARD_FLOAT_P.  */
3986
3987 static unsigned int
3988 mips_arg_regno (const struct mips_arg_info *info, bool hard_float_p)
3989 {
3990   if (!info->fpr_p || !hard_float_p)
3991     return GP_ARG_FIRST + info->reg_offset;
3992   else if (mips_abi == ABI_32 && TARGET_DOUBLE_FLOAT && info->reg_offset > 0)
3993     /* In o32, the second argument is always passed in $f14
3994        for TARGET_DOUBLE_FLOAT, regardless of whether the
3995        first argument was a word or doubleword.  */
3996     return FP_ARG_FIRST + 2;
3997   else
3998     return FP_ARG_FIRST + info->reg_offset;
3999 }
4000
4001 /* Implement FUNCTION_ARG_ADVANCE.  */
4002
4003 void
4004 function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4005                       tree type, int named)
4006 {
4007   struct mips_arg_info info;
4008
4009   mips_arg_info (cum, mode, type, named, &info);
4010
4011   if (!info.fpr_p)
4012     cum->gp_reg_found = true;
4013
4014   /* See the comment above the cumulative args structure in mips.h
4015      for an explanation of what this code does.  It assumes the O32
4016      ABI, which passes at most 2 arguments in float registers.  */
4017   if (cum->arg_number < 2 && info.fpr_p)
4018     cum->fp_code += (mode == SFmode ? 1 : 2) << (cum->arg_number * 2);
4019
4020   if (mips_abi != ABI_EABI || !info.fpr_p)
4021     cum->num_gprs = info.reg_offset + info.reg_words;
4022   else if (info.reg_words > 0)
4023     cum->num_fprs += MAX_FPRS_PER_FMT;
4024
4025   if (info.stack_words > 0)
4026     cum->stack_words = info.stack_offset + info.stack_words;
4027
4028   cum->arg_number++;
4029 }
4030
4031 /* Implement FUNCTION_ARG.  */
4032
4033 struct rtx_def *
4034 function_arg (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
4035               tree type, int named)
4036 {
4037   struct mips_arg_info info;
4038
4039   /* We will be called with a mode of VOIDmode after the last argument
4040      has been seen.  Whatever we return will be passed to the call
4041      insn.  If we need a mips16 fp_code, return a REG with the code
4042      stored as the mode.  */
4043   if (mode == VOIDmode)
4044     {
4045       if (TARGET_MIPS16 && cum->fp_code != 0)
4046         return gen_rtx_REG ((enum machine_mode) cum->fp_code, 0);
4047
4048       else
4049         return 0;
4050     }
4051
4052   mips_arg_info (cum, mode, type, named, &info);
4053
4054   /* Return straight away if the whole argument is passed on the stack.  */
4055   if (info.reg_offset == MAX_ARGS_IN_REGISTERS)
4056     return 0;
4057
4058   if (type != 0
4059       && TREE_CODE (type) == RECORD_TYPE
4060       && TARGET_NEWABI
4061       && TYPE_SIZE_UNIT (type)
4062       && host_integerp (TYPE_SIZE_UNIT (type), 1)
4063       && named)
4064     {
4065       /* The Irix 6 n32/n64 ABIs say that if any 64-bit chunk of the
4066          structure contains a double in its entirety, then that 64-bit
4067          chunk is passed in a floating point register.  */
4068       tree field;
4069
4070       /* First check to see if there is any such field.  */
4071       for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4072         if (TREE_CODE (field) == FIELD_DECL
4073             && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
4074             && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD
4075             && host_integerp (bit_position (field), 0)
4076             && int_bit_position (field) % BITS_PER_WORD == 0)
4077           break;
4078
4079       if (field != 0)
4080         {
4081           /* Now handle the special case by returning a PARALLEL
4082              indicating where each 64-bit chunk goes.  INFO.REG_WORDS
4083              chunks are passed in registers.  */
4084           unsigned int i;
4085           HOST_WIDE_INT bitpos;
4086           rtx ret;
4087
4088           /* assign_parms checks the mode of ENTRY_PARM, so we must
4089              use the actual mode here.  */
4090           ret = gen_rtx_PARALLEL (mode, rtvec_alloc (info.reg_words));
4091
4092           bitpos = 0;
4093           field = TYPE_FIELDS (type);
4094           for (i = 0; i < info.reg_words; i++)
4095             {
4096               rtx reg;
4097
4098               for (; field; field = TREE_CHAIN (field))
4099                 if (TREE_CODE (field) == FIELD_DECL
4100                     && int_bit_position (field) >= bitpos)
4101                   break;
4102
4103               if (field
4104                   && int_bit_position (field) == bitpos
4105                   && TREE_CODE (TREE_TYPE (field)) == REAL_TYPE
4106                   && !TARGET_SOFT_FLOAT
4107                   && TYPE_PRECISION (TREE_TYPE (field)) == BITS_PER_WORD)
4108                 reg = gen_rtx_REG (DFmode, FP_ARG_FIRST + info.reg_offset + i);
4109               else
4110                 reg = gen_rtx_REG (DImode, GP_ARG_FIRST + info.reg_offset + i);
4111
4112               XVECEXP (ret, 0, i)
4113                 = gen_rtx_EXPR_LIST (VOIDmode, reg,
4114                                      GEN_INT (bitpos / BITS_PER_UNIT));
4115
4116               bitpos += BITS_PER_WORD;
4117             }
4118           return ret;
4119         }
4120     }
4121
4122   /* Handle the n32/n64 conventions for passing complex floating-point
4123      arguments in FPR pairs.  The real part goes in the lower register
4124      and the imaginary part goes in the upper register.  */
4125   if (TARGET_NEWABI
4126       && info.fpr_p
4127       && GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
4128     {
4129       rtx real, imag;
4130       enum machine_mode inner;
4131       int reg;
4132
4133       inner = GET_MODE_INNER (mode);
4134       reg = FP_ARG_FIRST + info.reg_offset;
4135       if (info.reg_words * UNITS_PER_WORD == GET_MODE_SIZE (inner))
4136         {
4137           /* Real part in registers, imaginary part on stack.  */
4138           gcc_assert (info.stack_words == info.reg_words);
4139           return gen_rtx_REG (inner, reg);
4140         }
4141       else
4142         {
4143           gcc_assert (info.stack_words == 0);
4144           real = gen_rtx_EXPR_LIST (VOIDmode,
4145                                     gen_rtx_REG (inner, reg),
4146                                     const0_rtx);
4147           imag = gen_rtx_EXPR_LIST (VOIDmode,
4148                                     gen_rtx_REG (inner,
4149                                                  reg + info.reg_words / 2),
4150                                     GEN_INT (GET_MODE_SIZE (inner)));
4151           return gen_rtx_PARALLEL (mode, gen_rtvec (2, real, imag));
4152         }
4153     }
4154
4155   return gen_rtx_REG (mode, mips_arg_regno (&info, TARGET_HARD_FLOAT));
4156 }
4157
4158
4159 /* Implement TARGET_ARG_PARTIAL_BYTES.  */
4160
4161 static int
4162 mips_arg_partial_bytes (CUMULATIVE_ARGS *cum,
4163                         enum machine_mode mode, tree type, bool named)
4164 {
4165   struct mips_arg_info info;
4166
4167   mips_arg_info (cum, mode, type, named, &info);
4168   return info.stack_words > 0 ? info.reg_words * UNITS_PER_WORD : 0;
4169 }
4170
4171
4172 /* Implement FUNCTION_ARG_BOUNDARY.  Every parameter gets at least
4173    PARM_BOUNDARY bits of alignment, but will be given anything up
4174    to STACK_BOUNDARY bits if the type requires it.  */
4175
4176 int
4177 function_arg_boundary (enum machine_mode mode, tree type)
4178 {
4179   unsigned int alignment;
4180
4181   alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
4182   if (alignment < PARM_BOUNDARY)
4183     alignment = PARM_BOUNDARY;
4184   if (alignment > STACK_BOUNDARY)
4185     alignment = STACK_BOUNDARY;
4186   return alignment;
4187 }
4188
4189 /* Return true if FUNCTION_ARG_PADDING (MODE, TYPE) should return
4190    upward rather than downward.  In other words, return true if the
4191    first byte of the stack slot has useful data, false if the last
4192    byte does.  */
4193
4194 bool
4195 mips_pad_arg_upward (enum machine_mode mode, tree type)
4196 {
4197   /* On little-endian targets, the first byte of every stack argument
4198      is passed in the first byte of the stack slot.  */
4199   if (!BYTES_BIG_ENDIAN)
4200     return true;
4201
4202   /* Otherwise, integral types are padded downward: the last byte of a
4203      stack argument is passed in the last byte of the stack slot.  */
4204   if (type != 0
4205       ? INTEGRAL_TYPE_P (type) || POINTER_TYPE_P (type)
4206       : GET_MODE_CLASS (mode) == MODE_INT)
4207     return false;
4208
4209   /* Big-endian o64 pads floating-point arguments downward.  */
4210   if (mips_abi == ABI_O64)
4211     if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
4212       return false;
4213
4214   /* Other types are padded upward for o32, o64, n32 and n64.  */
4215   if (mips_abi != ABI_EABI)
4216     return true;
4217
4218   /* Arguments smaller than a stack slot are padded downward.  */
4219   if (mode != BLKmode)
4220     return (GET_MODE_BITSIZE (mode) >= PARM_BOUNDARY);
4221   else
4222     return (int_size_in_bytes (type) >= (PARM_BOUNDARY / BITS_PER_UNIT));
4223 }
4224
4225
4226 /* Likewise BLOCK_REG_PADDING (MODE, TYPE, ...).  Return !BYTES_BIG_ENDIAN
4227    if the least significant byte of the register has useful data.  Return
4228    the opposite if the most significant byte does.  */
4229
4230 bool
4231 mips_pad_reg_upward (enum machine_mode mode, tree type)
4232 {
4233   /* No shifting is required for floating-point arguments.  */
4234   if (type != 0 ? FLOAT_TYPE_P (type) : GET_MODE_CLASS (mode) == MODE_FLOAT)
4235     return !BYTES_BIG_ENDIAN;
4236
4237   /* Otherwise, apply the same padding to register arguments as we do
4238      to stack arguments.  */
4239   return mips_pad_arg_upward (mode, type);
4240 }
4241 \f
4242 static void
4243 mips_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4244                              tree type, int *pretend_size ATTRIBUTE_UNUSED,
4245                              int no_rtl)
4246 {
4247   CUMULATIVE_ARGS local_cum;
4248   int gp_saved, fp_saved;
4249
4250   /* The caller has advanced CUM up to, but not beyond, the last named
4251      argument.  Advance a local copy of CUM past the last "real" named
4252      argument, to find out how many registers are left over.  */
4253
4254   local_cum = *cum;
4255   FUNCTION_ARG_ADVANCE (local_cum, mode, type, 1);
4256
4257   /* Found out how many registers we need to save.  */
4258   gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
4259   fp_saved = (EABI_FLOAT_VARARGS_P
4260               ? MAX_ARGS_IN_REGISTERS - local_cum.num_fprs
4261               : 0);
4262
4263   if (!no_rtl)
4264     {
4265       if (gp_saved > 0)
4266         {
4267           rtx ptr, mem;
4268
4269           ptr = plus_constant (virtual_incoming_args_rtx,
4270                                REG_PARM_STACK_SPACE (cfun->decl)
4271                                - gp_saved * UNITS_PER_WORD);
4272           mem = gen_rtx_MEM (BLKmode, ptr);
4273           set_mem_alias_set (mem, get_varargs_alias_set ());
4274
4275           move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
4276                                mem, gp_saved);
4277         }
4278       if (fp_saved > 0)
4279         {
4280           /* We can't use move_block_from_reg, because it will use
4281              the wrong mode.  */
4282           enum machine_mode mode;
4283           int off, i;
4284
4285           /* Set OFF to the offset from virtual_incoming_args_rtx of
4286              the first float register.  The FP save area lies below
4287              the integer one, and is aligned to UNITS_PER_FPVALUE bytes.  */
4288           off = -gp_saved * UNITS_PER_WORD;
4289           off &= ~(UNITS_PER_FPVALUE - 1);
4290           off -= fp_saved * UNITS_PER_FPREG;
4291
4292           mode = TARGET_SINGLE_FLOAT ? SFmode : DFmode;
4293
4294           for (i = local_cum.num_fprs; i < MAX_ARGS_IN_REGISTERS;
4295                i += MAX_FPRS_PER_FMT)
4296             {
4297               rtx ptr, mem;
4298
4299               ptr = plus_constant (virtual_incoming_args_rtx, off);
4300               mem = gen_rtx_MEM (mode, ptr);
4301               set_mem_alias_set (mem, get_varargs_alias_set ());
4302               emit_move_insn (mem, gen_rtx_REG (mode, FP_ARG_FIRST + i));
4303               off += UNITS_PER_HWFPVALUE;
4304             }
4305         }
4306     }
4307   if (REG_PARM_STACK_SPACE (cfun->decl) == 0)
4308     cfun->machine->varargs_size = (gp_saved * UNITS_PER_WORD
4309                                    + fp_saved * UNITS_PER_FPREG);
4310 }
4311
4312 /* Create the va_list data type.
4313    We keep 3 pointers, and two offsets.
4314    Two pointers are to the overflow area, which starts at the CFA.
4315      One of these is constant, for addressing into the GPR save area below it.
4316      The other is advanced up the stack through the overflow region.
4317    The third pointer is to the GPR save area.  Since the FPR save area
4318      is just below it, we can address FPR slots off this pointer.
4319    We also keep two one-byte offsets, which are to be subtracted from the
4320      constant pointers to yield addresses in the GPR and FPR save areas.
4321      These are downcounted as float or non-float arguments are used,
4322      and when they get to zero, the argument must be obtained from the
4323      overflow region.
4324    If !EABI_FLOAT_VARARGS_P, then no FPR save area exists, and a single
4325      pointer is enough.  It's started at the GPR save area, and is
4326      advanced, period.
4327    Note that the GPR save area is not constant size, due to optimization
4328      in the prologue.  Hence, we can't use a design with two pointers
4329      and two offsets, although we could have designed this with two pointers
4330      and three offsets.  */
4331
4332 static tree
4333 mips_build_builtin_va_list (void)
4334 {
4335   if (EABI_FLOAT_VARARGS_P)
4336     {
4337       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff, f_res, record;
4338       tree array, index;
4339
4340       record = (*lang_hooks.types.make_type) (RECORD_TYPE);
4341
4342       f_ovfl = build_decl (FIELD_DECL, get_identifier ("__overflow_argptr"),
4343                           ptr_type_node);
4344       f_gtop = build_decl (FIELD_DECL, get_identifier ("__gpr_top"),
4345                           ptr_type_node);
4346       f_ftop = build_decl (FIELD_DECL, get_identifier ("__fpr_top"),
4347                           ptr_type_node);
4348       f_goff = build_decl (FIELD_DECL, get_identifier ("__gpr_offset"),
4349                           unsigned_char_type_node);
4350       f_foff = build_decl (FIELD_DECL, get_identifier ("__fpr_offset"),
4351                           unsigned_char_type_node);
4352       /* Explicitly pad to the size of a pointer, so that -Wpadded won't
4353          warn on every user file.  */
4354       index = build_int_cst (NULL_TREE, GET_MODE_SIZE (ptr_mode) - 2 - 1);
4355       array = build_array_type (unsigned_char_type_node,
4356                                 build_index_type (index));
4357       f_res = build_decl (FIELD_DECL, get_identifier ("__reserved"), array);
4358
4359       DECL_FIELD_CONTEXT (f_ovfl) = record;
4360       DECL_FIELD_CONTEXT (f_gtop) = record;
4361       DECL_FIELD_CONTEXT (f_ftop) = record;
4362       DECL_FIELD_CONTEXT (f_goff) = record;
4363       DECL_FIELD_CONTEXT (f_foff) = record;
4364       DECL_FIELD_CONTEXT (f_res) = record;
4365
4366       TYPE_FIELDS (record) = f_ovfl;
4367       TREE_CHAIN (f_ovfl) = f_gtop;
4368       TREE_CHAIN (f_gtop) = f_ftop;
4369       TREE_CHAIN (f_ftop) = f_goff;
4370       TREE_CHAIN (f_goff) = f_foff;
4371       TREE_CHAIN (f_foff) = f_res;
4372
4373       layout_type (record);
4374       return record;
4375     }
4376   else if (TARGET_IRIX && TARGET_IRIX6)
4377     /* On IRIX 6, this type is 'char *'.  */
4378     return build_pointer_type (char_type_node);
4379   else
4380     /* Otherwise, we use 'void *'.  */
4381     return ptr_type_node;
4382 }
4383
4384 /* Implement va_start.  */
4385
4386 void
4387 mips_va_start (tree valist, rtx nextarg)
4388 {
4389   if (EABI_FLOAT_VARARGS_P)
4390     {
4391       const CUMULATIVE_ARGS *cum;
4392       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
4393       tree ovfl, gtop, ftop, goff, foff;
4394       tree t;
4395       int gpr_save_area_size;
4396       int fpr_save_area_size;
4397       int fpr_offset;
4398
4399       cum = &current_function_args_info;
4400       gpr_save_area_size
4401         = (MAX_ARGS_IN_REGISTERS - cum->num_gprs) * UNITS_PER_WORD;
4402       fpr_save_area_size
4403         = (MAX_ARGS_IN_REGISTERS - cum->num_fprs) * UNITS_PER_FPREG;
4404
4405       f_ovfl = TYPE_FIELDS (va_list_type_node);
4406       f_gtop = TREE_CHAIN (f_ovfl);
4407       f_ftop = TREE_CHAIN (f_gtop);
4408       f_goff = TREE_CHAIN (f_ftop);
4409       f_foff = TREE_CHAIN (f_goff);
4410
4411       ovfl = build3 (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl,
4412                      NULL_TREE);
4413       gtop = build3 (COMPONENT_REF, TREE_TYPE (f_gtop), valist, f_gtop,
4414                      NULL_TREE);
4415       ftop = build3 (COMPONENT_REF, TREE_TYPE (f_ftop), valist, f_ftop,
4416                      NULL_TREE);
4417       goff = build3 (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff,
4418                      NULL_TREE);
4419       foff = build3 (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff,
4420                      NULL_TREE);
4421
4422       /* Emit code to initialize OVFL, which points to the next varargs
4423          stack argument.  CUM->STACK_WORDS gives the number of stack
4424          words used by named arguments.  */
4425       t = make_tree (TREE_TYPE (ovfl), virtual_incoming_args_rtx);
4426       if (cum->stack_words > 0)
4427         t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl), t,
4428                     size_int (cum->stack_words * UNITS_PER_WORD));
4429       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ovfl), ovfl, t);
4430       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4431
4432       /* Emit code to initialize GTOP, the top of the GPR save area.  */
4433       t = make_tree (TREE_TYPE (gtop), virtual_incoming_args_rtx);
4434       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (gtop), gtop, t);
4435       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4436
4437       /* Emit code to initialize FTOP, the top of the FPR save area.
4438          This address is gpr_save_area_bytes below GTOP, rounded
4439          down to the next fp-aligned boundary.  */
4440       t = make_tree (TREE_TYPE (ftop), virtual_incoming_args_rtx);
4441       fpr_offset = gpr_save_area_size + UNITS_PER_FPVALUE - 1;
4442       fpr_offset &= ~(UNITS_PER_FPVALUE - 1);
4443       if (fpr_offset)
4444         t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ftop), t,
4445                     size_int (-fpr_offset));
4446       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ftop), ftop, t);
4447       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4448
4449       /* Emit code to initialize GOFF, the offset from GTOP of the
4450          next GPR argument.  */
4451       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (goff), goff,
4452                   build_int_cst (NULL_TREE, gpr_save_area_size));
4453       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4454
4455       /* Likewise emit code to initialize FOFF, the offset from FTOP
4456          of the next FPR argument.  */
4457       t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (foff), foff,
4458                   build_int_cst (NULL_TREE, fpr_save_area_size));
4459       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4460     }
4461   else
4462     {
4463       nextarg = plus_constant (nextarg, -cfun->machine->varargs_size);
4464       std_expand_builtin_va_start (valist, nextarg);
4465     }
4466 }
4467 \f
4468 /* Implement va_arg.  */
4469
4470 static tree
4471 mips_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
4472 {
4473   HOST_WIDE_INT size, rsize;
4474   tree addr;
4475   bool indirect;
4476
4477   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, 0);
4478
4479   if (indirect)
4480     type = build_pointer_type (type);
4481
4482   size = int_size_in_bytes (type);
4483   rsize = (size + UNITS_PER_WORD - 1) & -UNITS_PER_WORD;
4484
4485   if (mips_abi != ABI_EABI || !EABI_FLOAT_VARARGS_P)
4486     addr = std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
4487   else
4488     {
4489       /* Not a simple merged stack.      */
4490
4491       tree f_ovfl, f_gtop, f_ftop, f_goff, f_foff;
4492       tree ovfl, top, off, align;
4493       HOST_WIDE_INT osize;
4494       tree t, u;
4495
4496       f_ovfl = TYPE_FIELDS (va_list_type_node);
4497       f_gtop = TREE_CHAIN (f_ovfl);
4498       f_ftop = TREE_CHAIN (f_gtop);
4499       f_goff = TREE_CHAIN (f_ftop);
4500       f_foff = TREE_CHAIN (f_goff);
4501
4502       /* We maintain separate pointers and offsets for floating-point
4503          and integer arguments, but we need similar code in both cases.
4504          Let:
4505
4506          TOP be the top of the register save area;
4507          OFF be the offset from TOP of the next register;
4508          ADDR_RTX be the address of the argument;
4509          RSIZE be the number of bytes used to store the argument
4510          when it's in the register save area;
4511          OSIZE be the number of bytes used to store it when it's
4512          in the stack overflow area; and
4513          PADDING be (BYTES_BIG_ENDIAN ? OSIZE - RSIZE : 0)
4514
4515          The code we want is:
4516
4517          1: off &= -rsize;        // round down
4518          2: if (off != 0)
4519          3:   {
4520          4:      addr_rtx = top - off;
4521          5:      off -= rsize;
4522          6:   }
4523          7: else
4524          8:   {
4525          9:      ovfl += ((intptr_t) ovfl + osize - 1) & -osize;
4526          10:     addr_rtx = ovfl + PADDING;
4527          11:     ovfl += osize;
4528          14:   }
4529
4530          [1] and [9] can sometimes be optimized away.  */
4531
4532       ovfl = build3 (COMPONENT_REF, TREE_TYPE (f_ovfl), valist, f_ovfl,
4533                      NULL_TREE);
4534
4535       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_FLOAT
4536           && GET_MODE_SIZE (TYPE_MODE (type)) <= UNITS_PER_FPVALUE)
4537         {
4538           top = build3 (COMPONENT_REF, TREE_TYPE (f_ftop), valist, f_ftop,
4539                         NULL_TREE);
4540           off = build3 (COMPONENT_REF, TREE_TYPE (f_foff), valist, f_foff,
4541                         NULL_TREE);
4542
4543           /* When floating-point registers are saved to the stack,
4544              each one will take up UNITS_PER_HWFPVALUE bytes, regardless
4545              of the float's precision.  */
4546           rsize = UNITS_PER_HWFPVALUE;
4547
4548           /* Overflow arguments are padded to UNITS_PER_WORD bytes
4549              (= PARM_BOUNDARY bits).  This can be different from RSIZE
4550              in two cases:
4551
4552              (1) On 32-bit targets when TYPE is a structure such as:
4553
4554              struct s { float f; };
4555
4556              Such structures are passed in paired FPRs, so RSIZE
4557              will be 8 bytes.  However, the structure only takes
4558              up 4 bytes of memory, so OSIZE will only be 4.
4559
4560              (2) In combinations such as -mgp64 -msingle-float
4561              -fshort-double.  Doubles passed in registers
4562              will then take up 4 (UNITS_PER_HWFPVALUE) bytes,
4563              but those passed on the stack take up
4564              UNITS_PER_WORD bytes.  */
4565           osize = MAX (GET_MODE_SIZE (TYPE_MODE (type)), UNITS_PER_WORD);
4566         }
4567       else
4568         {
4569           top = build3 (COMPONENT_REF, TREE_TYPE (f_gtop), valist, f_gtop,
4570                         NULL_TREE);
4571           off = build3 (COMPONENT_REF, TREE_TYPE (f_goff), valist, f_goff,
4572                         NULL_TREE);
4573           if (rsize > UNITS_PER_WORD)
4574             {
4575               /* [1] Emit code for: off &= -rsize.      */
4576               t = build2 (BIT_AND_EXPR, TREE_TYPE (off), off,
4577                           build_int_cst (NULL_TREE, -rsize));
4578               t = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (off), off, t);
4579               gimplify_and_add (t, pre_p);
4580             }
4581           osize = rsize;
4582         }
4583
4584       /* [2] Emit code to branch if off == 0.  */
4585       t = build2 (NE_EXPR, boolean_type_node, off,
4586                   build_int_cst (TREE_TYPE (off), 0));
4587       addr = build3 (COND_EXPR, ptr_type_node, t, NULL_TREE, NULL_TREE);
4588
4589       /* [5] Emit code for: off -= rsize.  We do this as a form of
4590          post-increment not available to C.  Also widen for the
4591          coming pointer arithmetic.  */
4592       t = fold_convert (TREE_TYPE (off), build_int_cst (NULL_TREE, rsize));
4593       t = build2 (POSTDECREMENT_EXPR, TREE_TYPE (off), off, t);
4594       t = fold_convert (sizetype, t);
4595       t = fold_build1 (NEGATE_EXPR, sizetype, t);
4596
4597       /* [4] Emit code for: addr_rtx = top - off.  On big endian machines,
4598          the argument has RSIZE - SIZE bytes of leading padding.  */
4599       t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (top), top, t);
4600       if (BYTES_BIG_ENDIAN && rsize > size)
4601         {
4602           u = size_int (rsize - size);
4603           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (t), t, u);
4604         }
4605       COND_EXPR_THEN (addr) = t;
4606
4607       if (osize > UNITS_PER_WORD)
4608         {
4609           /* [9] Emit: ovfl += ((intptr_t) ovfl + osize - 1) & -osize.  */
4610           u = size_int (osize - 1);
4611           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (ovfl), ovfl, u);
4612           t = fold_convert (sizetype, t);
4613           u = size_int (-osize);
4614           t = build2 (BIT_AND_EXPR, sizetype, t, u);
4615           t = fold_convert (TREE_TYPE (ovfl), t);
4616           align = build2 (GIMPLE_MODIFY_STMT, TREE_TYPE (ovfl), ovfl, t);
4617         }
4618       else
4619         align = NULL;
4620
4621       /* [10, 11].      Emit code to store ovfl in addr_rtx, then
4622          post-increment ovfl by osize.  On big-endian machines,
4623          the argument has OSIZE - SIZE bytes of leading padding.  */
4624       u = fold_convert (TREE_TYPE (ovfl),
4625                         build_int_cst (NULL_TREE, osize));
4626       t = build2 (POSTINCREMENT_EXPR, TREE_TYPE (ovfl), ovfl, u);
4627       if (BYTES_BIG_ENDIAN && osize > size)
4628         {
4629           u = size_int (osize - size);
4630           t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (t), t, u);
4631         }
4632
4633       /* String [9] and [10,11] together.  */
4634       if (align)
4635         t = build2 (COMPOUND_EXPR, TREE_TYPE (t), align, t);
4636       COND_EXPR_ELSE (addr) = t;
4637
4638       addr = fold_convert (build_pointer_type (type), addr);
4639       addr = build_va_arg_indirect_ref (addr);
4640     }
4641
4642   if (indirect)
4643     addr = build_va_arg_indirect_ref (addr);
4644
4645   return addr;
4646 }
4647 \f
4648 /* Return true if it is possible to use left/right accesses for a
4649    bitfield of WIDTH bits starting BITPOS bits into *OP.  When
4650    returning true, update *OP, *LEFT and *RIGHT as follows:
4651
4652    *OP is a BLKmode reference to the whole field.
4653
4654    *LEFT is a QImode reference to the first byte if big endian or
4655    the last byte if little endian.  This address can be used in the
4656    left-side instructions (lwl, swl, ldl, sdl).
4657
4658    *RIGHT is a QImode reference to the opposite end of the field and
4659    can be used in the patterning right-side instruction.  */
4660
4661 static bool
4662 mips_get_unaligned_mem (rtx *op, unsigned int width, int bitpos,
4663                         rtx *left, rtx *right)
4664 {
4665   rtx first, last;
4666
4667   /* Check that the operand really is a MEM.  Not all the extv and
4668      extzv predicates are checked.  */
4669   if (!MEM_P (*op))
4670     return false;
4671
4672   /* Check that the size is valid.  */
4673   if (width != 32 && (!TARGET_64BIT || width != 64))
4674     return false;
4675
4676   /* We can only access byte-aligned values.  Since we are always passed
4677      a reference to the first byte of the field, it is not necessary to
4678      do anything with BITPOS after this check.  */
4679   if (bitpos % BITS_PER_UNIT != 0)
4680     return false;
4681
4682   /* Reject aligned bitfields: we want to use a normal load or store
4683      instead of a left/right pair.  */
4684   if (MEM_ALIGN (*op) >= width)
4685     return false;
4686
4687   /* Adjust *OP to refer to the whole field.  This also has the effect
4688      of legitimizing *OP's address for BLKmode, possibly simplifying it.  */
4689   *op = adjust_address (*op, BLKmode, 0);
4690   set_mem_size (*op, GEN_INT (width / BITS_PER_UNIT));
4691
4692   /* Get references to both ends of the field.  We deliberately don't
4693      use the original QImode *OP for FIRST since the new BLKmode one
4694      might have a simpler address.  */
4695   first = adjust_address (*op, QImode, 0);
4696   last = adjust_address (*op, QImode, width / BITS_PER_UNIT - 1);
4697
4698   /* Allocate to LEFT and RIGHT according to endianness.  LEFT should
4699      be the upper word and RIGHT the lower word.  */
4700   if (TARGET_BIG_ENDIAN)
4701     *left = first, *right = last;
4702   else
4703     *left = last, *right = first;
4704
4705   return true;
4706 }
4707
4708
4709 /* Try to emit the equivalent of (set DEST (zero_extract SRC WIDTH BITPOS)).
4710    Return true on success.  We only handle cases where zero_extract is
4711    equivalent to sign_extract.  */
4712
4713 bool
4714 mips_expand_unaligned_load (rtx dest, rtx src, unsigned int width, int bitpos)
4715 {
4716   rtx left, right, temp;
4717
4718   /* If TARGET_64BIT, the destination of a 32-bit load will be a
4719      paradoxical word_mode subreg.  This is the only case in which
4720      we allow the destination to be larger than the source.  */
4721   if (GET_CODE (dest) == SUBREG
4722       && GET_MODE (dest) == DImode
4723       && SUBREG_BYTE (dest) == 0
4724       && GET_MODE (SUBREG_REG (dest)) == SImode)
4725     dest = SUBREG_REG (dest);
4726
4727   /* After the above adjustment, the destination must be the same
4728      width as the source.  */
4729   if (GET_MODE_BITSIZE (GET_MODE (dest)) != width)
4730     return false;
4731
4732   if (!mips_get_unaligned_mem (&src, width, bitpos, &left, &right))
4733     return false;
4734
4735   temp = gen_reg_rtx (GET_MODE (dest));
4736   if (GET_MODE (dest) == DImode)
4737     {
4738       emit_insn (gen_mov_ldl (temp, src, left));
4739       emit_insn (gen_mov_ldr (dest, copy_rtx (src), right, temp));
4740     }
4741   else
4742     {
4743       emit_insn (gen_mov_lwl (temp, src, left));
4744       emit_insn (gen_mov_lwr (dest, copy_rtx (src), right, temp));
4745     }
4746   return true;
4747 }
4748
4749
4750 /* Try to expand (set (zero_extract DEST WIDTH BITPOS) SRC).  Return
4751    true on success.  */
4752
4753 bool
4754 mips_expand_unaligned_store (rtx dest, rtx src, unsigned int width, int bitpos)
4755 {
4756   rtx left, right;
4757   enum machine_mode mode;
4758
4759   if (!mips_get_unaligned_mem (&dest, width, bitpos, &left, &right))
4760     return false;
4761
4762   mode = mode_for_size (width, MODE_INT, 0);
4763   src = gen_lowpart (mode, src);
4764
4765   if (mode == DImode)
4766     {
4767       emit_insn (gen_mov_sdl (dest, src, left));
4768       emit_insn (gen_mov_sdr (copy_rtx (dest), copy_rtx (src), right));
4769     }
4770   else
4771     {
4772       emit_insn (gen_mov_swl (dest, src, left));
4773       emit_insn (gen_mov_swr (copy_rtx (dest), copy_rtx (src), right));
4774     }
4775   return true;
4776 }
4777
4778 /* Return true if X is a MEM with the same size as MODE.  */
4779
4780 bool
4781 mips_mem_fits_mode_p (enum machine_mode mode, rtx x)
4782 {
4783   rtx size;
4784
4785   if (!MEM_P (x))
4786     return false;
4787
4788   size = MEM_SIZE (x);
4789   return size && INTVAL (size) == GET_MODE_SIZE (mode);
4790 }
4791
4792 /* Return true if (zero_extract OP SIZE POSITION) can be used as the
4793    source of an "ext" instruction or the destination of an "ins"
4794    instruction.  OP must be a register operand and the following
4795    conditions must hold:
4796
4797      0 <= POSITION < GET_MODE_BITSIZE (GET_MODE (op))
4798      0 < SIZE <= GET_MODE_BITSIZE (GET_MODE (op))
4799      0 < POSITION + SIZE <= GET_MODE_BITSIZE (GET_MODE (op))
4800
4801    Also reject lengths equal to a word as they are better handled
4802    by the move patterns.  */
4803
4804 bool
4805 mips_use_ins_ext_p (rtx op, rtx size, rtx position)
4806 {
4807   HOST_WIDE_INT len, pos;
4808
4809   if (!ISA_HAS_EXT_INS
4810       || !register_operand (op, VOIDmode)
4811       || GET_MODE_BITSIZE (GET_MODE (op)) > BITS_PER_WORD)
4812     return false;
4813
4814   len = INTVAL (size);
4815   pos = INTVAL (position);
4816
4817   if (len <= 0 || len >= GET_MODE_BITSIZE (GET_MODE (op))
4818       || pos < 0 || pos + len > GET_MODE_BITSIZE (GET_MODE (op)))
4819     return false;
4820
4821   return true;
4822 }
4823
4824 /* Set up globals to generate code for the ISA or processor
4825    described by INFO.  */
4826
4827 static void
4828 mips_set_architecture (const struct mips_cpu_info *info)
4829 {
4830   if (info != 0)
4831     {
4832       mips_arch_info = info;
4833       mips_arch = info->cpu;
4834       mips_isa = info->isa;
4835     }
4836 }
4837
4838
4839 /* Likewise for tuning.  */
4840
4841 static void
4842 mips_set_tune (const struct mips_cpu_info *info)
4843 {
4844   if (info != 0)
4845     {
4846       mips_tune_info = info;
4847       mips_tune = info->cpu;
4848     }
4849 }
4850
4851 /* Implement TARGET_HANDLE_OPTION.  */
4852
4853 static bool
4854 mips_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
4855 {
4856   switch (code)
4857     {
4858     case OPT_mabi_:
4859       if (strcmp (arg, "32") == 0)
4860         mips_abi = ABI_32;
4861       else if (strcmp (arg, "o64") == 0)
4862         mips_abi = ABI_O64;
4863       else if (strcmp (arg, "n32") == 0)
4864         mips_abi = ABI_N32;
4865       else if (strcmp (arg, "64") == 0)
4866         mips_abi = ABI_64;
4867       else if (strcmp (arg, "eabi") == 0)
4868         mips_abi = ABI_EABI;
4869       else
4870         return false;
4871       return true;
4872
4873     case OPT_march_:
4874     case OPT_mtune_:
4875       return mips_parse_cpu (arg) != 0;
4876
4877     case OPT_mips:
4878       mips_isa_info = mips_parse_cpu (ACONCAT (("mips", arg, NULL)));
4879       return mips_isa_info != 0;
4880
4881     case OPT_mno_flush_func:
4882       mips_cache_flush_func = NULL;
4883       return true;
4884
4885     default:
4886       return true;
4887     }
4888 }
4889
4890 /* Set up the threshold for data to go into the small data area, instead
4891    of the normal data area, and detect any conflicts in the switches.  */
4892
4893 void
4894 override_options (void)
4895 {
4896   int i, start, regno;
4897   enum machine_mode mode;
4898
4899 #ifdef SUBTARGET_OVERRIDE_OPTIONS
4900   SUBTARGET_OVERRIDE_OPTIONS;
4901 #endif
4902
4903   mips_section_threshold = g_switch_set ? g_switch_value : MIPS_DEFAULT_GVALUE;
4904
4905   /* The following code determines the architecture and register size.
4906      Similar code was added to GAS 2.14 (see tc-mips.c:md_after_parse_args()).
4907      The GAS and GCC code should be kept in sync as much as possible.  */
4908
4909   if (mips_arch_string != 0)
4910     mips_set_architecture (mips_parse_cpu (mips_arch_string));
4911
4912   if (mips_isa_info != 0)
4913     {
4914       if (mips_arch_info == 0)
4915         mips_set_architecture (mips_isa_info);
4916       else if (mips_arch_info->isa != mips_isa_info->isa)
4917         error ("-%s conflicts with the other architecture options, "
4918                "which specify a %s processor",
4919                mips_isa_info->name,
4920                mips_cpu_info_from_isa (mips_arch_info->isa)->name);
4921     }
4922
4923   if (mips_arch_info == 0)
4924     {
4925 #ifdef MIPS_CPU_STRING_DEFAULT
4926       mips_set_architecture (mips_parse_cpu (MIPS_CPU_STRING_DEFAULT));
4927 #else
4928       mips_set_architecture (mips_cpu_info_from_isa (MIPS_ISA_DEFAULT));
4929 #endif
4930     }
4931
4932   if (ABI_NEEDS_64BIT_REGS && !ISA_HAS_64BIT_REGS)
4933     error ("-march=%s is not compatible with the selected ABI",
4934            mips_arch_info->name);
4935
4936   /* Optimize for mips_arch, unless -mtune selects a different processor.  */
4937   if (mips_tune_string != 0)
4938     mips_set_tune (mips_parse_cpu (mips_tune_string));
4939
4940   if (mips_tune_info == 0)
4941     mips_set_tune (mips_arch_info);
4942
4943   /* Set cost structure for the processor.  */
4944   if (optimize_size)
4945     mips_cost = &mips_rtx_cost_optimize_size;
4946   else
4947     mips_cost = &mips_rtx_cost_data[mips_tune];
4948
4949   if ((target_flags_explicit & MASK_64BIT) != 0)
4950     {
4951       /* The user specified the size of the integer registers.  Make sure
4952          it agrees with the ABI and ISA.  */
4953       if (TARGET_64BIT && !ISA_HAS_64BIT_REGS)
4954         error ("-mgp64 used with a 32-bit processor");
4955       else if (!TARGET_64BIT && ABI_NEEDS_64BIT_REGS)
4956         error ("-mgp32 used with a 64-bit ABI");
4957       else if (TARGET_64BIT && ABI_NEEDS_32BIT_REGS)
4958         error ("-mgp64 used with a 32-bit ABI");
4959     }
4960   else
4961     {
4962       /* Infer the integer register size from the ABI and processor.
4963          Restrict ourselves to 32-bit registers if that's all the
4964          processor has, or if the ABI cannot handle 64-bit registers.  */
4965       if (ABI_NEEDS_32BIT_REGS || !ISA_HAS_64BIT_REGS)
4966         target_flags &= ~MASK_64BIT;
4967       else
4968         target_flags |= MASK_64BIT;
4969     }
4970
4971   if ((target_flags_explicit & MASK_FLOAT64) != 0)
4972     {
4973       /* Really, -mfp32 and -mfp64 are ornamental options.  There's
4974          only one right answer here.  */
4975       if (TARGET_64BIT && TARGET_DOUBLE_FLOAT && !TARGET_FLOAT64)
4976         error ("unsupported combination: %s", "-mgp64 -mfp32 -mdouble-float");
4977       else if (!TARGET_64BIT && TARGET_FLOAT64
4978                && !(ISA_HAS_MXHC1 && mips_abi == ABI_32))
4979         error ("-mgp32 and -mfp64 can only be combined if the target"
4980                " supports the mfhc1 and mthc1 instructions");
4981       else if (TARGET_SINGLE_FLOAT && TARGET_FLOAT64)
4982         error ("unsupported combination: %s", "-mfp64 -msingle-float");
4983     }
4984   else
4985     {
4986       /* -msingle-float selects 32-bit float registers.  Otherwise the
4987          float registers should be the same size as the integer ones.  */
4988       if (TARGET_64BIT && TARGET_DOUBLE_FLOAT)
4989         target_flags |= MASK_FLOAT64;
4990       else
4991         target_flags &= ~MASK_FLOAT64;
4992     }
4993
4994   /* End of code shared with GAS.  */
4995
4996   if ((target_flags_explicit & MASK_LONG64) == 0)
4997     {
4998       if ((mips_abi == ABI_EABI && TARGET_64BIT) || mips_abi == ABI_64)
4999         target_flags |= MASK_LONG64;
5000       else
5001         target_flags &= ~MASK_LONG64;
5002     }
5003
5004   if (MIPS_MARCH_CONTROLS_SOFT_FLOAT
5005       && (target_flags_explicit & MASK_SOFT_FLOAT) == 0)
5006     {
5007       /* For some configurations, it is useful to have -march control
5008          the default setting of MASK_SOFT_FLOAT.  */
5009       switch ((int) mips_arch)
5010         {
5011         case PROCESSOR_R4100:
5012         case PROCESSOR_R4111:
5013         case PROCESSOR_R4120:
5014         case PROCESSOR_R4130:
5015           target_flags |= MASK_SOFT_FLOAT;
5016           break;
5017
5018         default:
5019           target_flags &= ~MASK_SOFT_FLOAT;
5020           break;
5021         }
5022     }
5023
5024   if (!TARGET_OLDABI)
5025     flag_pcc_struct_return = 0;
5026
5027   if ((target_flags_explicit & MASK_BRANCHLIKELY) == 0)
5028     {
5029       /* If neither -mbranch-likely nor -mno-branch-likely was given
5030          on the command line, set MASK_BRANCHLIKELY based on the target
5031          architecture.
5032
5033          By default, we enable use of Branch Likely instructions on
5034          all architectures which support them with the following
5035          exceptions: when creating MIPS32 or MIPS64 code, and when
5036          tuning for architectures where their use tends to hurt
5037          performance.
5038
5039          The MIPS32 and MIPS64 architecture specifications say "Software
5040          is strongly encouraged to avoid use of Branch Likely
5041          instructions, as they will be removed from a future revision
5042          of the [MIPS32 and MIPS64] architecture."  Therefore, we do not
5043          issue those instructions unless instructed to do so by
5044          -mbranch-likely.  */
5045       if (ISA_HAS_BRANCHLIKELY
5046           && !(ISA_MIPS32 || ISA_MIPS32R2 || ISA_MIPS64)
5047           && !(TUNE_MIPS5500 || TUNE_SB1))
5048         target_flags |= MASK_BRANCHLIKELY;
5049       else
5050         target_flags &= ~MASK_BRANCHLIKELY;
5051     }
5052   if (TARGET_BRANCHLIKELY && !ISA_HAS_BRANCHLIKELY)
5053     warning (0, "generation of Branch Likely instructions enabled, but not supported by architecture");
5054
5055   /* The effect of -mabicalls isn't defined for the EABI.  */
5056   if (mips_abi == ABI_EABI && TARGET_ABICALLS)
5057     {
5058       error ("unsupported combination: %s", "-mabicalls -mabi=eabi");
5059       target_flags &= ~MASK_ABICALLS;
5060     }
5061
5062   if (TARGET_ABICALLS)
5063     {
5064       /* We need to set flag_pic for executables as well as DSOs
5065          because we may reference symbols that are not defined in
5066          the final executable.  (MIPS does not use things like
5067          copy relocs, for example.)
5068
5069          Also, there is a body of code that uses __PIC__ to distinguish
5070          between -mabicalls and -mno-abicalls code.  */
5071       flag_pic = 1;
5072       if (mips_section_threshold > 0)
5073         warning (0, "%<-G%> is incompatible with %<-mabicalls%>");
5074     }
5075
5076   if (TARGET_VXWORKS_RTP && mips_section_threshold > 0)
5077     warning (0, "-G and -mrtp are incompatible");
5078
5079   /* mips_split_addresses is a half-way house between explicit
5080      relocations and the traditional assembler macros.  It can
5081      split absolute 32-bit symbolic constants into a high/lo_sum
5082      pair but uses macros for other sorts of access.
5083
5084      Like explicit relocation support for REL targets, it relies
5085      on GNU extensions in the assembler and the linker.
5086
5087      Although this code should work for -O0, it has traditionally
5088      been treated as an optimization.  */
5089   if (!TARGET_MIPS16 && TARGET_SPLIT_ADDRESSES
5090       && optimize && !flag_pic
5091       && !ABI_HAS_64BIT_SYMBOLS)
5092     mips_split_addresses = 1;
5093   else
5094     mips_split_addresses = 0;
5095
5096   /* -mvr4130-align is a "speed over size" optimization: it usually produces
5097      faster code, but at the expense of more nops.  Enable it at -O3 and
5098      above.  */
5099   if (optimize > 2 && (target_flags_explicit & MASK_VR4130_ALIGN) == 0)
5100     target_flags |= MASK_VR4130_ALIGN;
5101
5102   /* When compiling for the mips16, we cannot use floating point.  We
5103      record the original hard float value in mips16_hard_float.  */
5104   if (TARGET_MIPS16)
5105     {
5106       if (TARGET_SOFT_FLOAT)
5107         mips16_hard_float = 0;
5108       else
5109         mips16_hard_float = 1;
5110       target_flags |= MASK_SOFT_FLOAT;
5111
5112       /* Don't run the scheduler before reload, since it tends to
5113          increase register pressure.  */
5114       flag_schedule_insns = 0;
5115
5116       /* Don't do hot/cold partitioning.  The constant layout code expects
5117          the whole function to be in a single section.  */
5118       flag_reorder_blocks_and_partition = 0;
5119
5120       /* Silently disable -mexplicit-relocs since it doesn't apply
5121          to mips16 code.  Even so, it would overly pedantic to warn
5122          about "-mips16 -mexplicit-relocs", especially given that
5123          we use a %gprel() operator.  */
5124       target_flags &= ~MASK_EXPLICIT_RELOCS;
5125     }
5126
5127   /* When using explicit relocs, we call dbr_schedule from within
5128      mips_reorg.  */
5129   if (TARGET_EXPLICIT_RELOCS)
5130     {
5131       mips_flag_delayed_branch = flag_delayed_branch;
5132       flag_delayed_branch = 0;
5133     }
5134
5135 #ifdef MIPS_TFMODE_FORMAT
5136   REAL_MODE_FORMAT (TFmode) = &MIPS_TFMODE_FORMAT;
5137 #endif
5138
5139   /* Make sure that the user didn't turn off paired single support when
5140      MIPS-3D support is requested.  */
5141   if (TARGET_MIPS3D && (target_flags_explicit & MASK_PAIRED_SINGLE_FLOAT)
5142       && !TARGET_PAIRED_SINGLE_FLOAT)
5143     error ("-mips3d requires -mpaired-single");
5144
5145   /* If TARGET_MIPS3D, enable MASK_PAIRED_SINGLE_FLOAT.  */
5146   if (TARGET_MIPS3D)
5147     target_flags |= MASK_PAIRED_SINGLE_FLOAT;
5148
5149   /* Make sure that when TARGET_PAIRED_SINGLE_FLOAT is true, TARGET_FLOAT64
5150      and TARGET_HARD_FLOAT are both true.  */
5151   if (TARGET_PAIRED_SINGLE_FLOAT && !(TARGET_FLOAT64 && TARGET_HARD_FLOAT))
5152     error ("-mips3d/-mpaired-single must be used with -mfp64 -mhard-float");
5153
5154   /* Make sure that the ISA supports TARGET_PAIRED_SINGLE_FLOAT when it is
5155      enabled.  */
5156   if (TARGET_PAIRED_SINGLE_FLOAT && !ISA_MIPS64)
5157     error ("-mips3d/-mpaired-single must be used with -mips64");
5158
5159   /* If TARGET_DSPR2, enable MASK_DSP.  */
5160   if (TARGET_DSPR2)
5161     target_flags |= MASK_DSP;
5162
5163   if (TARGET_MIPS16 && TARGET_DSP)
5164     error ("-mips16 and -mdsp cannot be used together");
5165
5166   mips_print_operand_punct['?'] = 1;
5167   mips_print_operand_punct['#'] = 1;
5168   mips_print_operand_punct['/'] = 1;
5169   mips_print_operand_punct['&'] = 1;
5170   mips_print_operand_punct['!'] = 1;
5171   mips_print_operand_punct['*'] = 1;
5172   mips_print_operand_punct['@'] = 1;
5173   mips_print_operand_punct['.'] = 1;
5174   mips_print_operand_punct['('] = 1;
5175   mips_print_operand_punct[')'] = 1;
5176   mips_print_operand_punct['['] = 1;
5177   mips_print_operand_punct[']'] = 1;
5178   mips_print_operand_punct['<'] = 1;
5179   mips_print_operand_punct['>'] = 1;
5180   mips_print_operand_punct['{'] = 1;
5181   mips_print_operand_punct['}'] = 1;
5182   mips_print_operand_punct['^'] = 1;
5183   mips_print_operand_punct['$'] = 1;
5184   mips_print_operand_punct['+'] = 1;
5185   mips_print_operand_punct['~'] = 1;
5186
5187   /* Set up array to map GCC register number to debug register number.
5188      Ignore the special purpose register numbers.  */
5189
5190   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5191     mips_dbx_regno[i] = -1;
5192
5193   start = GP_DBX_FIRST - GP_REG_FIRST;
5194   for (i = GP_REG_FIRST; i <= GP_REG_LAST; i++)
5195     mips_dbx_regno[i] = i + start;
5196
5197   start = FP_DBX_FIRST - FP_REG_FIRST;
5198   for (i = FP_REG_FIRST; i <= FP_REG_LAST; i++)
5199     mips_dbx_regno[i] = i + start;
5200
5201   mips_dbx_regno[HI_REGNUM] = MD_DBX_FIRST + 0;
5202   mips_dbx_regno[LO_REGNUM] = MD_DBX_FIRST + 1;
5203
5204   /* Set up array giving whether a given register can hold a given mode.  */
5205
5206   for (mode = VOIDmode;
5207        mode != MAX_MACHINE_MODE;
5208        mode = (enum machine_mode) ((int)mode + 1))
5209     {
5210       register int size              = GET_MODE_SIZE (mode);
5211       register enum mode_class class = GET_MODE_CLASS (mode);
5212
5213       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
5214         {
5215           register int temp;
5216
5217           if (mode == CCV2mode)
5218             temp = (ISA_HAS_8CC
5219                     && ST_REG_P (regno)
5220                     && (regno - ST_REG_FIRST) % 2 == 0);
5221
5222           else if (mode == CCV4mode)
5223             temp = (ISA_HAS_8CC
5224                     && ST_REG_P (regno)
5225                     && (regno - ST_REG_FIRST) % 4 == 0);
5226
5227           else if (mode == CCmode)
5228             {
5229               if (! ISA_HAS_8CC)
5230                 temp = (regno == FPSW_REGNUM);
5231               else
5232                 temp = (ST_REG_P (regno) || GP_REG_P (regno)
5233                         || FP_REG_P (regno));
5234             }
5235
5236           else if (GP_REG_P (regno))
5237             temp = ((regno & 1) == 0 || size <= UNITS_PER_WORD);
5238
5239           else if (FP_REG_P (regno))
5240             temp = ((((regno % MAX_FPRS_PER_FMT) == 0)
5241                      || (MIN_FPRS_PER_FMT == 1
5242                          && size <= UNITS_PER_FPREG))
5243                     && (((class == MODE_FLOAT || class == MODE_COMPLEX_FLOAT
5244                           || class == MODE_VECTOR_FLOAT)
5245                          && size <= UNITS_PER_FPVALUE)
5246                         /* Allow integer modes that fit into a single
5247                            register.  We need to put integers into FPRs
5248                            when using instructions like cvt and trunc.
5249                            We can't allow sizes smaller than a word,
5250                            the FPU has no appropriate load/store
5251                            instructions for those.  */
5252                         || (class == MODE_INT
5253                             && size >= MIN_UNITS_PER_WORD
5254                             && size <= UNITS_PER_FPREG)
5255                         /* Allow TFmode for CCmode reloads.  */
5256                         || (ISA_HAS_8CC && mode == TFmode)));
5257
5258           else if (ACC_REG_P (regno))
5259             temp = (INTEGRAL_MODE_P (mode)
5260                     && (size <= UNITS_PER_WORD
5261                         || (ACC_HI_REG_P (regno)
5262                             && size == 2 * UNITS_PER_WORD)));
5263
5264           else if (ALL_COP_REG_P (regno))
5265             temp = (class == MODE_INT && size <= UNITS_PER_WORD);
5266           else
5267             temp = 0;
5268
5269           mips_hard_regno_mode_ok[(int)mode][regno] = temp;
5270         }
5271     }
5272
5273   /* Save GPR registers in word_mode sized hunks.  word_mode hasn't been
5274      initialized yet, so we can't use that here.  */
5275   gpr_mode = TARGET_64BIT ? DImode : SImode;
5276
5277   /* Provide default values for align_* for 64-bit targets.  */
5278   if (TARGET_64BIT && !TARGET_MIPS16)
5279     {
5280       if (align_loops == 0)
5281         align_loops = 8;
5282       if (align_jumps == 0)
5283         align_jumps = 8;
5284       if (align_functions == 0)
5285         align_functions = 8;
5286     }
5287
5288   /* Function to allocate machine-dependent function status.  */
5289   init_machine_status = &mips_init_machine_status;
5290
5291   if (ABI_HAS_64BIT_SYMBOLS)
5292     {
5293       if (TARGET_EXPLICIT_RELOCS)
5294         {
5295           mips_split_p[SYMBOL_64_HIGH] = true;
5296           mips_hi_relocs[SYMBOL_64_HIGH] = "%highest(";
5297           mips_lo_relocs[SYMBOL_64_HIGH] = "%higher(";
5298
5299           mips_split_p[SYMBOL_64_MID] = true;
5300           mips_hi_relocs[SYMBOL_64_MID] = "%higher(";
5301           mips_lo_relocs[SYMBOL_64_MID] = "%hi(";
5302
5303           mips_split_p[SYMBOL_64_LOW] = true;
5304           mips_hi_relocs[SYMBOL_64_LOW] = "%hi(";
5305           mips_lo_relocs[SYMBOL_64_LOW] = "%lo(";
5306
5307           mips_split_p[SYMBOL_GENERAL] = true;
5308           mips_lo_relocs[SYMBOL_GENERAL] = "%lo(";
5309         }
5310     }
5311   else
5312     {
5313       if (TARGET_EXPLICIT_RELOCS || mips_split_addresses)
5314         {
5315           mips_split_p[SYMBOL_GENERAL] = true;
5316           mips_hi_relocs[SYMBOL_GENERAL] = "%hi(";
5317           mips_lo_relocs[SYMBOL_GENERAL] = "%lo(";
5318         }
5319     }
5320
5321   if (TARGET_MIPS16)
5322     {
5323       /* The high part is provided by a pseudo copy of $gp.  */
5324       mips_split_p[SYMBOL_SMALL_DATA] = true;
5325       mips_lo_relocs[SYMBOL_SMALL_DATA] = "%gprel(";
5326     }
5327
5328   if (TARGET_EXPLICIT_RELOCS)
5329     {
5330       /* Small data constants are kept whole until after reload,
5331          then lowered by mips_rewrite_small_data.  */
5332       mips_lo_relocs[SYMBOL_SMALL_DATA] = "%gp_rel(";
5333
5334       mips_split_p[SYMBOL_GOT_PAGE_OFST] = true;
5335       if (TARGET_NEWABI)
5336         {
5337           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got_page(";
5338           mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%got_ofst(";
5339         }
5340       else
5341         {
5342           mips_lo_relocs[SYMBOL_GOTOFF_PAGE] = "%got(";
5343           mips_lo_relocs[SYMBOL_GOT_PAGE_OFST] = "%lo(";
5344         }
5345
5346       if (TARGET_XGOT)
5347         {
5348           /* The HIGH and LO_SUM are matched by special .md patterns.  */
5349           mips_split_p[SYMBOL_GOT_DISP] = true;
5350
5351           mips_split_p[SYMBOL_GOTOFF_DISP] = true;
5352           mips_hi_relocs[SYMBOL_GOTOFF_DISP] = "%got_hi(";
5353           mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_lo(";
5354
5355           mips_split_p[SYMBOL_GOTOFF_CALL] = true;
5356           mips_hi_relocs[SYMBOL_GOTOFF_CALL] = "%call_hi(";
5357           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call_lo(";
5358         }
5359       else
5360         {
5361           if (TARGET_NEWABI)
5362             mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got_disp(";
5363           else
5364             mips_lo_relocs[SYMBOL_GOTOFF_DISP] = "%got(";
5365           mips_lo_relocs[SYMBOL_GOTOFF_CALL] = "%call16(";
5366         }
5367     }
5368
5369   if (TARGET_NEWABI)
5370     {
5371       mips_split_p[SYMBOL_GOTOFF_LOADGP] = true;
5372       mips_hi_relocs[SYMBOL_GOTOFF_LOADGP] = "%hi(%neg(%gp_rel(";
5373       mips_lo_relocs[SYMBOL_GOTOFF_LOADGP] = "%lo(%neg(%gp_rel(";
5374     }
5375
5376   /* Thread-local relocation operators.  */
5377   mips_lo_relocs[SYMBOL_TLSGD] = "%tlsgd(";
5378   mips_lo_relocs[SYMBOL_TLSLDM] = "%tlsldm(";
5379   mips_split_p[SYMBOL_DTPREL] = 1;
5380   mips_hi_relocs[SYMBOL_DTPREL] = "%dtprel_hi(";
5381   mips_lo_relocs[SYMBOL_DTPREL] = "%dtprel_lo(";
5382   mips_lo_relocs[SYMBOL_GOTTPREL] = "%gottprel(";
5383   mips_split_p[SYMBOL_TPREL] = 1;
5384   mips_hi_relocs[SYMBOL_TPREL] = "%tprel_hi(";
5385   mips_lo_relocs[SYMBOL_TPREL] = "%tprel_lo(";
5386
5387   mips_lo_relocs[SYMBOL_HALF] = "%half(";
5388
5389   /* We don't have a thread pointer access instruction on MIPS16, or
5390      appropriate TLS relocations.  */
5391   if (TARGET_MIPS16)
5392     targetm.have_tls = false;
5393
5394   /* Default to working around R4000 errata only if the processor
5395      was selected explicitly.  */
5396   if ((target_flags_explicit & MASK_FIX_R4000) == 0
5397       && mips_matching_cpu_name_p (mips_arch_info->name, "r4000"))
5398     target_flags |= MASK_FIX_R4000;
5399
5400   /* Default to working around R4400 errata only if the processor
5401      was selected explicitly.  */
5402   if ((target_flags_explicit & MASK_FIX_R4400) == 0
5403       && mips_matching_cpu_name_p (mips_arch_info->name, "r4400"))
5404     target_flags |= MASK_FIX_R4400;
5405 }
5406
5407 /* Implement CONDITIONAL_REGISTER_USAGE.  */
5408
5409 void
5410 mips_conditional_register_usage (void)
5411 {
5412   if (!TARGET_DSP)
5413     {
5414       int regno;
5415
5416       for (regno = DSP_ACC_REG_FIRST; regno <= DSP_ACC_REG_LAST; regno++)
5417         fixed_regs[regno] = call_used_regs[regno] = 1;
5418     }
5419   if (!TARGET_HARD_FLOAT)
5420     {
5421       int regno;
5422
5423       for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
5424         fixed_regs[regno] = call_used_regs[regno] = 1;
5425       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
5426         fixed_regs[regno] = call_used_regs[regno] = 1;
5427     }
5428   else if (! ISA_HAS_8CC)
5429     {
5430       int regno;
5431
5432       /* We only have a single condition code register.  We
5433          implement this by hiding all the condition code registers,
5434          and generating RTL that refers directly to ST_REG_FIRST.  */
5435       for (regno = ST_REG_FIRST; regno <= ST_REG_LAST; regno++)
5436         fixed_regs[regno] = call_used_regs[regno] = 1;
5437     }
5438   /* In mips16 mode, we permit the $t temporary registers to be used
5439      for reload.  We prohibit the unused $s registers, since they
5440      are caller saved, and saving them via a mips16 register would
5441      probably waste more time than just reloading the value.  */
5442   if (TARGET_MIPS16)
5443     {
5444       fixed_regs[18] = call_used_regs[18] = 1;
5445       fixed_regs[19] = call_used_regs[19] = 1;
5446       fixed_regs[20] = call_used_regs[20] = 1;
5447       fixed_regs[21] = call_used_regs[21] = 1;
5448       fixed_regs[22] = call_used_regs[22] = 1;
5449       fixed_regs[23] = call_used_regs[23] = 1;
5450       fixed_regs[26] = call_used_regs[26] = 1;
5451       fixed_regs[27] = call_used_regs[27] = 1;
5452       fixed_regs[30] = call_used_regs[30] = 1;
5453     }
5454   /* fp20-23 are now caller saved.  */
5455   if (mips_abi == ABI_64)
5456     {
5457       int regno;
5458       for (regno = FP_REG_FIRST + 20; regno < FP_REG_FIRST + 24; regno++)
5459         call_really_used_regs[regno] = call_used_regs[regno] = 1;
5460     }
5461   /* Odd registers from fp21 to fp31 are now caller saved.  */
5462   if (mips_abi == ABI_N32)
5463     {
5464       int regno;
5465       for (regno = FP_REG_FIRST + 21; regno <= FP_REG_FIRST + 31; regno+=2)
5466         call_really_used_regs[regno] = call_used_regs[regno] = 1;
5467     }
5468 }
5469
5470 /* Allocate a chunk of memory for per-function machine-dependent data.  */
5471 static struct machine_function *
5472 mips_init_machine_status (void)
5473 {
5474   return ((struct machine_function *)
5475           ggc_alloc_cleared (sizeof (struct machine_function)));
5476 }
5477
5478 /* On the mips16, we want to allocate $24 (T_REG) before other
5479    registers for instructions for which it is possible.  This helps
5480    avoid shuffling registers around in order to set up for an xor,
5481    encouraging the compiler to use a cmp instead.  */
5482
5483 void
5484 mips_order_regs_for_local_alloc (void)
5485 {
5486   register int i;
5487
5488   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
5489     reg_alloc_order[i] = i;
5490
5491   if (TARGET_MIPS16)
5492     {
5493       /* It really doesn't matter where we put register 0, since it is
5494          a fixed register anyhow.  */
5495       reg_alloc_order[0] = 24;
5496       reg_alloc_order[24] = 0;
5497     }
5498 }
5499
5500 \f
5501 /* The MIPS debug format wants all automatic variables and arguments
5502    to be in terms of the virtual frame pointer (stack pointer before
5503    any adjustment in the function), while the MIPS 3.0 linker wants
5504    the frame pointer to be the stack pointer after the initial
5505    adjustment.  So, we do the adjustment here.  The arg pointer (which
5506    is eliminated) points to the virtual frame pointer, while the frame
5507    pointer (which may be eliminated) points to the stack pointer after
5508    the initial adjustments.  */
5509
5510 HOST_WIDE_INT
5511 mips_debugger_offset (rtx addr, HOST_WIDE_INT offset)
5512 {
5513   rtx offset2 = const0_rtx;
5514   rtx reg = eliminate_constant_term (addr, &offset2);
5515
5516   if (offset == 0)
5517     offset = INTVAL (offset2);
5518
5519   if (reg == stack_pointer_rtx || reg == frame_pointer_rtx
5520       || reg == hard_frame_pointer_rtx)
5521     {
5522       HOST_WIDE_INT frame_size = (!cfun->machine->frame.initialized)
5523                                   ? compute_frame_size (get_frame_size ())
5524                                   : cfun->machine->frame.total_size;
5525
5526       /* MIPS16 frame is smaller */
5527       if (frame_pointer_needed && TARGET_MIPS16)
5528         frame_size -= cfun->machine->frame.args_size;
5529
5530       offset = offset - frame_size;
5531     }
5532
5533   /* sdbout_parms does not want this to crash for unrecognized cases.  */
5534 #if 0
5535   else if (reg != arg_pointer_rtx)
5536     fatal_insn ("mips_debugger_offset called with non stack/frame/arg pointer",
5537                 addr);
5538 #endif
5539
5540   return offset;
5541 }
5542 \f
5543 /* Implement the PRINT_OPERAND macro.  The MIPS-specific operand codes are:
5544
5545    'X'  OP is CONST_INT, prints 32 bits in hexadecimal format = "0x%08x",
5546    'x'  OP is CONST_INT, prints 16 bits in hexadecimal format = "0x%04x",
5547    'h'  OP is HIGH, prints %hi(X),
5548    'd'  output integer constant in decimal,
5549    'z'  if the operand is 0, use $0 instead of normal operand.
5550    'D'  print second part of double-word register or memory operand.
5551    'L'  print low-order register of double-word register operand.
5552    'M'  print high-order register of double-word register operand.
5553    'C'  print part of opcode for a branch condition.
5554    'F'  print part of opcode for a floating-point branch condition.
5555    'N'  print part of opcode for a branch condition, inverted.
5556    'W'  print part of opcode for a floating-point branch condition, inverted.
5557    'T'  print 'f' for (eq:CC ...), 't' for (ne:CC ...),
5558               'z' for (eq:?I ...), 'n' for (ne:?I ...).
5559    't'  like 'T', but with the EQ/NE cases reversed
5560    'Y'  for a CONST_INT X, print mips_fp_conditions[X]
5561    'Z'  print the operand and a comma for ISA_HAS_8CC, otherwise print nothing
5562    'R'  print the reloc associated with LO_SUM
5563    'q'  print DSP accumulator registers
5564
5565    The punctuation characters are:
5566
5567    '('  Turn on .set noreorder
5568    ')'  Turn on .set reorder
5569    '['  Turn on .set noat
5570    ']'  Turn on .set at
5571    '<'  Turn on .set nomacro
5572    '>'  Turn on .set macro
5573    '{'  Turn on .set volatile (not GAS)
5574    '}'  Turn on .set novolatile (not GAS)
5575    '&'  Turn on .set noreorder if filling delay slots
5576    '*'  Turn on both .set noreorder and .set nomacro if filling delay slots
5577    '!'  Turn on .set nomacro if filling delay slots
5578    '#'  Print nop if in a .set noreorder section.
5579    '/'  Like '#', but does nothing within a delayed branch sequence
5580    '?'  Print 'l' if we are to use a branch likely instead of normal branch.
5581    '@'  Print the name of the assembler temporary register (at or $1).
5582    '.'  Print the name of the register with a hard-wired zero (zero or $0).
5583    '^'  Print the name of the pic call-through register (t9 or $25).
5584    '$'  Print the name of the stack pointer register (sp or $29).
5585    '+'  Print the name of the gp register (usually gp or $28).
5586    '~'  Output a branch alignment to LABEL_ALIGN(NULL).  */
5587
5588 void
5589 print_operand (FILE *file, rtx op, int letter)
5590 {
5591   register enum rtx_code code;
5592
5593   if (PRINT_OPERAND_PUNCT_VALID_P (letter))
5594     {
5595       switch (letter)
5596         {
5597         case '?':
5598           if (mips_branch_likely)
5599             putc ('l', file);
5600           break;
5601
5602         case '@':
5603           fputs (reg_names [GP_REG_FIRST + 1], file);
5604           break;
5605
5606         case '^':
5607           fputs (reg_names [PIC_FUNCTION_ADDR_REGNUM], file);
5608           break;
5609
5610         case '.':
5611           fputs (reg_names [GP_REG_FIRST + 0], file);
5612           break;
5613
5614         case '$':
5615           fputs (reg_names[STACK_POINTER_REGNUM], file);
5616           break;
5617
5618         case '+':
5619           fputs (reg_names[PIC_OFFSET_TABLE_REGNUM], file);
5620           break;
5621
5622         case '&':
5623           if (final_sequence != 0 && set_noreorder++ == 0)
5624             fputs (".set\tnoreorder\n\t", file);
5625           break;
5626
5627         case '*':
5628           if (final_sequence != 0)
5629             {
5630               if (set_noreorder++ == 0)
5631                 fputs (".set\tnoreorder\n\t", file);
5632
5633               if (set_nomacro++ == 0)
5634                 fputs (".set\tnomacro\n\t", file);
5635             }
5636           break;
5637
5638         case '!':
5639           if (final_sequence != 0 && set_nomacro++ == 0)
5640             fputs ("\n\t.set\tnomacro", file);
5641           break;
5642
5643         case '#':
5644           if (set_noreorder != 0)
5645             fputs ("\n\tnop", file);
5646           break;
5647
5648         case '/':
5649           /* Print an extra newline so that the delayed insn is separated
5650              from the following ones.  This looks neater and is consistent
5651              with non-nop delayed sequences.  */
5652           if (set_noreorder != 0 && final_sequence == 0)
5653             fputs ("\n\tnop\n", file);
5654           break;
5655
5656         case '(':
5657           if (set_noreorder++ == 0)
5658             fputs (".set\tnoreorder\n\t", file);
5659           break;
5660
5661         case ')':
5662           if (set_noreorder == 0)
5663             error ("internal error: %%) found without a %%( in assembler pattern");
5664
5665           else if (--set_noreorder == 0)
5666             fputs ("\n\t.set\treorder", file);
5667
5668           break;
5669
5670         case '[':
5671           if (set_noat++ == 0)
5672             fputs (".set\tnoat\n\t", file);
5673           break;
5674
5675         case ']':
5676           if (set_noat == 0)
5677             error ("internal error: %%] found without a %%[ in assembler pattern");
5678           else if (--set_noat == 0)
5679             fputs ("\n\t.set\tat", file);
5680
5681           break;
5682
5683         case '<':
5684           if (set_nomacro++ == 0)
5685             fputs (".set\tnomacro\n\t", file);
5686           break;
5687
5688         case '>':
5689           if (set_nomacro == 0)
5690             error ("internal error: %%> found without a %%< in assembler pattern");
5691           else if (--set_nomacro == 0)
5692             fputs ("\n\t.set\tmacro", file);
5693
5694           break;
5695
5696         case '{':
5697           if (set_volatile++ == 0)
5698             fputs ("#.set\tvolatile\n\t", file);
5699           break;
5700
5701         case '}':
5702           if (set_volatile == 0)
5703             error ("internal error: %%} found without a %%{ in assembler pattern");
5704           else if (--set_volatile == 0)
5705             fputs ("\n\t#.set\tnovolatile", file);
5706
5707           break;
5708
5709         case '~':
5710           {
5711             if (align_labels_log > 0)
5712               ASM_OUTPUT_ALIGN (file, align_labels_log);
5713           }
5714           break;
5715
5716         default:
5717           error ("PRINT_OPERAND: unknown punctuation '%c'", letter);
5718           break;
5719         }
5720
5721       return;
5722     }
5723
5724   if (! op)
5725     {
5726       error ("PRINT_OPERAND null pointer");
5727       return;
5728     }
5729
5730   code = GET_CODE (op);
5731
5732   if (letter == 'C')
5733     switch (code)
5734       {
5735       case EQ:  fputs ("eq",  file); break;
5736       case NE:  fputs ("ne",  file); break;
5737       case GT:  fputs ("gt",  file); break;
5738       case GE:  fputs ("ge",  file); break;
5739       case LT:  fputs ("lt",  file); break;
5740       case LE:  fputs ("le",  file); break;
5741       case GTU: fputs ("gtu", file); break;
5742       case GEU: fputs ("geu", file); break;
5743       case LTU: fputs ("ltu", file); break;
5744       case LEU: fputs ("leu", file); break;
5745       default:
5746         fatal_insn ("PRINT_OPERAND, invalid insn for %%C", op);
5747       }
5748
5749   else if (letter == 'N')
5750     switch (code)
5751       {
5752       case EQ:  fputs ("ne",  file); break;
5753       case NE:  fputs ("eq",  file); break;
5754       case GT:  fputs ("le",  file); break;
5755       case GE:  fputs ("lt",  file); break;
5756       case LT:  fputs ("ge",  file); break;
5757       case LE:  fputs ("gt",  file); break;
5758       case GTU: fputs ("leu", file); break;
5759       case GEU: fputs ("ltu", file); break;
5760       case LTU: fputs ("geu", file); break;
5761       case LEU: fputs ("gtu", file); break;
5762       default:
5763         fatal_insn ("PRINT_OPERAND, invalid insn for %%N", op);
5764       }
5765
5766   else if (letter == 'F')
5767     switch (code)
5768       {
5769       case EQ: fputs ("c1f", file); break;
5770       case NE: fputs ("c1t", file); break;
5771       default:
5772         fatal_insn ("PRINT_OPERAND, invalid insn for %%F", op);
5773       }
5774
5775   else if (letter == 'W')
5776     switch (code)
5777       {
5778       case EQ: fputs ("c1t", file); break;
5779       case NE: fputs ("c1f", file); break;
5780       default:
5781         fatal_insn ("PRINT_OPERAND, invalid insn for %%W", op);
5782       }
5783
5784   else if (letter == 'h')
5785     {
5786       if (GET_CODE (op) == HIGH)
5787         op = XEXP (op, 0);
5788
5789       print_operand_reloc (file, op, mips_hi_relocs);
5790     }
5791
5792   else if (letter == 'R')
5793     print_operand_reloc (file, op, mips_lo_relocs);
5794
5795   else if (letter == 'Y')
5796     {
5797       if (GET_CODE (op) == CONST_INT
5798           && ((unsigned HOST_WIDE_INT) INTVAL (op)
5799               < ARRAY_SIZE (mips_fp_conditions)))
5800         fputs (mips_fp_conditions[INTVAL (op)], file);
5801       else
5802         output_operand_lossage ("invalid %%Y value");
5803     }
5804
5805   else if (letter == 'Z')
5806     {
5807       if (ISA_HAS_8CC)
5808         {
5809           print_operand (file, op, 0);
5810           fputc (',', file);
5811         }
5812     }
5813
5814   else if (letter == 'q')
5815     {
5816       int regnum;
5817
5818       if (code != REG)
5819         fatal_insn ("PRINT_OPERAND, invalid insn for %%q", op);
5820
5821       regnum = REGNO (op);
5822       if (MD_REG_P (regnum))
5823         fprintf (file, "$ac0");
5824       else if (DSP_ACC_REG_P (regnum))
5825         fprintf (file, "$ac%c", reg_names[regnum][3]);
5826       else
5827         fatal_insn ("PRINT_OPERAND, invalid insn for %%q", op);
5828     }
5829
5830   else if (code == REG || code == SUBREG)
5831     {
5832       register int regnum;
5833
5834       if (code == REG)
5835         regnum = REGNO (op);
5836       else
5837         regnum = true_regnum (op);
5838
5839       if ((letter == 'M' && ! WORDS_BIG_ENDIAN)
5840           || (letter == 'L' && WORDS_BIG_ENDIAN)
5841           || letter == 'D')
5842         regnum++;
5843
5844       fprintf (file, "%s", reg_names[regnum]);
5845     }
5846
5847   else if (code == MEM)
5848     {
5849       if (letter == 'D')
5850         output_address (plus_constant (XEXP (op, 0), 4));
5851       else
5852         output_address (XEXP (op, 0));
5853     }
5854
5855   else if (letter == 'x' && GET_CODE (op) == CONST_INT)
5856     fprintf (file, HOST_WIDE_INT_PRINT_HEX, 0xffff & INTVAL(op));
5857
5858   else if (letter == 'X' && GET_CODE(op) == CONST_INT)
5859     fprintf (file, HOST_WIDE_INT_PRINT_HEX, INTVAL (op));
5860
5861   else if (letter == 'd' && GET_CODE(op) == CONST_INT)
5862     fprintf (file, HOST_WIDE_INT_PRINT_DEC, (INTVAL(op)));
5863
5864   else if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
5865     fputs (reg_names[GP_REG_FIRST], file);
5866
5867   else if (letter == 'd' || letter == 'x' || letter == 'X')
5868     output_operand_lossage ("invalid use of %%d, %%x, or %%X");
5869
5870   else if (letter == 'T' || letter == 't')
5871     {
5872       int truth = (code == NE) == (letter == 'T');
5873       fputc ("zfnt"[truth * 2 + (GET_MODE (op) == CCmode)], file);
5874     }
5875
5876   else if (CONST_GP_P (op))
5877     fputs (reg_names[GLOBAL_POINTER_REGNUM], file);
5878
5879   else
5880     output_addr_const (file, op);
5881 }
5882
5883
5884 /* Print symbolic operand OP, which is part of a HIGH or LO_SUM.
5885    RELOCS is the array of relocations to use.  */
5886
5887 static void
5888 print_operand_reloc (FILE *file, rtx op, const char **relocs)
5889 {
5890   enum mips_symbol_type symbol_type;
5891   const char *p;
5892   rtx base, offset;
5893
5894   if (!mips_symbolic_constant_p (op, &symbol_type) || relocs[symbol_type] == 0)
5895     fatal_insn ("PRINT_OPERAND, invalid operand for relocation", op);
5896
5897   /* If OP uses an UNSPEC address, we want to print the inner symbol.  */
5898   split_const (op, &base, &offset);
5899   if (UNSPEC_ADDRESS_P (base))
5900     op = plus_constant (UNSPEC_ADDRESS (base), INTVAL (offset));
5901
5902   fputs (relocs[symbol_type], file);
5903   output_addr_const (file, op);
5904   for (p = relocs[symbol_type]; *p != 0; p++)
5905     if (*p == '(')
5906       fputc (')', file);
5907 }
5908 \f
5909 /* Output address operand X to FILE.  */
5910
5911 void
5912 print_operand_address (FILE *file, rtx x)
5913 {
5914   struct mips_address_info addr;
5915
5916   if (mips_classify_address (&addr, x, word_mode, true))
5917     switch (addr.type)
5918       {
5919       case ADDRESS_REG:
5920         print_operand (file, addr.offset, 0);
5921         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
5922         return;
5923
5924       case ADDRESS_LO_SUM:
5925         print_operand (file, addr.offset, 'R');
5926         fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
5927         return;
5928
5929       case ADDRESS_CONST_INT:
5930         output_addr_const (file, x);
5931         fprintf (file, "(%s)", reg_names[0]);
5932         return;
5933
5934       case ADDRESS_SYMBOLIC:
5935         output_addr_const (file, x);
5936         return;
5937       }
5938   gcc_unreachable ();
5939 }
5940 \f
5941 /* When using assembler macros, keep track of all of small-data externs
5942    so that mips_file_end can emit the appropriate declarations for them.
5943
5944    In most cases it would be safe (though pointless) to emit .externs
5945    for other symbols too.  One exception is when an object is within
5946    the -G limit but declared by the user to be in a section other
5947    than .sbss or .sdata.  */
5948
5949 void
5950 mips_output_external (FILE *file, tree decl, const char *name)
5951 {
5952   default_elf_asm_output_external (file, decl, name);
5953
5954   /* We output the name if and only if TREE_SYMBOL_REFERENCED is
5955      set in order to avoid putting out names that are never really
5956      used. */
5957   if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
5958     {
5959       if (!TARGET_EXPLICIT_RELOCS && mips_in_small_data_p (decl))
5960         {
5961           fputs ("\t.extern\t", file);
5962           assemble_name (file, name);
5963           fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC "\n",
5964                    int_size_in_bytes (TREE_TYPE (decl)));
5965         }
5966       else if (TARGET_IRIX
5967                && mips_abi == ABI_32
5968                && TREE_CODE (decl) == FUNCTION_DECL)
5969         {
5970           /* In IRIX 5 or IRIX 6 for the O32 ABI, we must output a
5971              `.global name .text' directive for every used but
5972              undefined function.  If we don't, the linker may perform
5973              an optimization (skipping over the insns that set $gp)
5974              when it is unsafe.  */
5975           fputs ("\t.globl ", file);
5976           assemble_name (file, name);
5977           fputs (" .text\n", file);
5978         }
5979     }
5980 }
5981 \f
5982 /* Emit a new filename to a stream.  If we are smuggling stabs, try to
5983    put out a MIPS ECOFF file and a stab.  */
5984
5985 void
5986 mips_output_filename (FILE *stream, const char *name)
5987 {
5988
5989   /* If we are emitting DWARF-2, let dwarf2out handle the ".file"
5990      directives.  */
5991   if (write_symbols == DWARF2_DEBUG)
5992     return;
5993   else if (mips_output_filename_first_time)
5994     {
5995       mips_output_filename_first_time = 0;
5996       num_source_filenames += 1;
5997       current_function_file = name;
5998       fprintf (stream, "\t.file\t%d ", num_source_filenames);
5999       output_quoted_string (stream, name);
6000       putc ('\n', stream);
6001     }
6002
6003   /* If we are emitting stabs, let dbxout.c handle this (except for
6004      the mips_output_filename_first_time case).  */
6005   else if (write_symbols == DBX_DEBUG)
6006     return;
6007
6008   else if (name != current_function_file
6009            && strcmp (name, current_function_file) != 0)
6010     {
6011       num_source_filenames += 1;
6012       current_function_file = name;
6013       fprintf (stream, "\t.file\t%d ", num_source_filenames);
6014       output_quoted_string (stream, name);
6015       putc ('\n', stream);
6016     }
6017 }
6018 \f
6019 /* Output an ASCII string, in a space-saving way.  PREFIX is the string
6020    that should be written before the opening quote, such as "\t.ascii\t"
6021    for real string data or "\t# " for a comment.  */
6022
6023 void
6024 mips_output_ascii (FILE *stream, const char *string_param, size_t len,
6025                    const char *prefix)
6026 {
6027   size_t i;
6028   int cur_pos = 17;
6029   register const unsigned char *string =
6030     (const unsigned char *)string_param;
6031
6032   fprintf (stream, "%s\"", prefix);
6033   for (i = 0; i < len; i++)
6034     {
6035       register int c = string[i];
6036
6037       if (ISPRINT (c))
6038         {
6039           if (c == '\\' || c == '\"')
6040             {
6041               putc ('\\', stream);
6042               cur_pos++;
6043             }
6044           putc (c, stream);
6045           cur_pos++;
6046         }
6047       else
6048         {
6049           fprintf (stream, "\\%03o", c);
6050           cur_pos += 4;
6051         }
6052
6053       if (cur_pos > 72 && i+1 < len)
6054         {
6055           cur_pos = 17;
6056           fprintf (stream, "\"\n%s\"", prefix);
6057         }
6058     }
6059   fprintf (stream, "\"\n");
6060 }
6061 \f
6062 /* Implement TARGET_ASM_FILE_START.  */
6063
6064 static void
6065 mips_file_start (void)
6066 {
6067   default_file_start ();
6068
6069   if (!TARGET_IRIX)
6070     {
6071 #ifdef HAVE_AS_GNU_ATTRIBUTE
6072       fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n",
6073                TARGET_HARD_FLOAT_ABI ? (TARGET_DOUBLE_FLOAT ? 1 : 2) : 3);
6074 #endif
6075
6076       /* Generate a special section to describe the ABI switches used to
6077          produce the resultant binary.  This used to be done by the assembler
6078          setting bits in the ELF header's flags field, but we have run out of
6079          bits.  GDB needs this information in order to be able to correctly
6080          debug these binaries.  See the function mips_gdbarch_init() in
6081          gdb/mips-tdep.c.  This is unnecessary for the IRIX 5/6 ABIs and
6082          causes unnecessary IRIX 6 ld warnings.  */
6083       const char * abi_string = NULL;
6084
6085       switch (mips_abi)
6086         {
6087         case ABI_32:   abi_string = "abi32"; break;
6088         case ABI_N32:  abi_string = "abiN32"; break;
6089         case ABI_64:   abi_string = "abi64"; break;
6090         case ABI_O64:  abi_string = "abiO64"; break;
6091         case ABI_EABI: abi_string = TARGET_64BIT ? "eabi64" : "eabi32"; break;
6092         default:
6093           gcc_unreachable ();
6094         }
6095       /* Note - we use fprintf directly rather than calling switch_to_section
6096          because in this way we can avoid creating an allocated section.  We
6097          do not want this section to take up any space in the running
6098          executable.  */
6099       fprintf (asm_out_file, "\t.section .mdebug.%s\n", abi_string);
6100
6101       /* There is no ELF header flag to distinguish long32 forms of the
6102          EABI from long64 forms.  Emit a special section to help tools
6103          such as GDB.  Do the same for o64, which is sometimes used with
6104          -mlong64.  */
6105       if (mips_abi == ABI_EABI || mips_abi == ABI_O64)
6106         fprintf (asm_out_file, "\t.section .gcc_compiled_long%d\n",
6107                  TARGET_LONG64 ? 64 : 32);
6108
6109       /* Restore the default section.  */
6110       fprintf (asm_out_file, "\t.previous\n");
6111     }
6112
6113   /* Generate the pseudo ops that System V.4 wants.  */
6114   if (TARGET_ABICALLS)
6115     fprintf (asm_out_file, "\t.abicalls\n");
6116
6117   if (TARGET_MIPS16)
6118     fprintf (asm_out_file, "\t.set\tmips16\n");
6119
6120   if (flag_verbose_asm)
6121     fprintf (asm_out_file, "\n%s -G value = %d, Arch = %s, ISA = %d\n",
6122              ASM_COMMENT_START,
6123              mips_section_threshold, mips_arch_info->name, mips_isa);
6124 }
6125
6126 #ifdef BSS_SECTION_ASM_OP
6127 /* Implement ASM_OUTPUT_ALIGNED_BSS.  This differs from the default only
6128    in the use of sbss.  */
6129
6130 void
6131 mips_output_aligned_bss (FILE *stream, tree decl, const char *name,
6132                          unsigned HOST_WIDE_INT size, int align)
6133 {
6134   extern tree last_assemble_variable_decl;
6135
6136   if (mips_in_small_data_p (decl))
6137     switch_to_section (get_named_section (NULL, ".sbss", 0));
6138   else
6139     switch_to_section (bss_section);
6140   ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
6141   last_assemble_variable_decl = decl;
6142   ASM_DECLARE_OBJECT_NAME (stream, name, decl);
6143   ASM_OUTPUT_SKIP (stream, size != 0 ? size : 1);
6144 }
6145 #endif
6146 \f
6147 /* Implement ASM_OUTPUT_ALIGNED_DECL_COMMON.  This is usually the same as the
6148    elfos.h version, but we also need to handle -muninit-const-in-rodata.  */
6149
6150 void
6151 mips_output_aligned_decl_common (FILE *stream, tree decl, const char *name,
6152                                  unsigned HOST_WIDE_INT size,
6153                                  unsigned int align)
6154 {
6155   /* If the target wants uninitialized const declarations in
6156      .rdata then don't put them in .comm.  */
6157   if (TARGET_EMBEDDED_DATA && TARGET_UNINIT_CONST_IN_RODATA
6158       && TREE_CODE (decl) == VAR_DECL && TREE_READONLY (decl)
6159       && (DECL_INITIAL (decl) == 0 || DECL_INITIAL (decl) == error_mark_node))
6160     {
6161       if (TREE_PUBLIC (decl) && DECL_NAME (decl))
6162         targetm.asm_out.globalize_label (stream, name);
6163
6164       switch_to_section (readonly_data_section);
6165       ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
6166       mips_declare_object (stream, name, "",
6167                            ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED "\n",
6168                            size);
6169     }
6170   else
6171     mips_declare_common_object (stream, name, "\n\t.comm\t",
6172                                 size, align, true);
6173 }
6174
6175 /* Declare a common object of SIZE bytes using asm directive INIT_STRING.
6176    NAME is the name of the object and ALIGN is the required alignment
6177    in bytes.  TAKES_ALIGNMENT_P is true if the directive takes a third
6178    alignment argument.  */
6179
6180 void
6181 mips_declare_common_object (FILE *stream, const char *name,
6182                             const char *init_string,
6183                             unsigned HOST_WIDE_INT size,
6184                             unsigned int align, bool takes_alignment_p)
6185 {
6186   if (!takes_alignment_p)
6187     {
6188       size += (align / BITS_PER_UNIT) - 1;
6189       size -= size % (align / BITS_PER_UNIT);
6190       mips_declare_object (stream, name, init_string,
6191                            "," HOST_WIDE_INT_PRINT_UNSIGNED "\n", size);
6192     }
6193   else
6194     mips_declare_object (stream, name, init_string,
6195                          "," HOST_WIDE_INT_PRINT_UNSIGNED ",%u\n",
6196                          size, align / BITS_PER_UNIT);
6197 }
6198
6199 /* Emit either a label, .comm, or .lcomm directive.  When using assembler
6200    macros, mark the symbol as written so that mips_file_end won't emit an
6201    .extern for it.  STREAM is the output file, NAME is the name of the
6202    symbol, INIT_STRING is the string that should be written before the
6203    symbol and FINAL_STRING is the string that should be written after it.
6204    FINAL_STRING is a printf() format that consumes the remaining arguments.  */
6205
6206 void
6207 mips_declare_object (FILE *stream, const char *name, const char *init_string,
6208                      const char *final_string, ...)
6209 {
6210   va_list ap;
6211
6212   fputs (init_string, stream);
6213   assemble_name (stream, name);
6214   va_start (ap, final_string);
6215   vfprintf (stream, final_string, ap);
6216   va_end (ap);
6217
6218   if (!TARGET_EXPLICIT_RELOCS)
6219     {
6220       tree name_tree = get_identifier (name);
6221       TREE_ASM_WRITTEN (name_tree) = 1;
6222     }
6223 }
6224
6225 #ifdef ASM_OUTPUT_SIZE_DIRECTIVE
6226 extern int size_directive_output;
6227
6228 /* Implement ASM_DECLARE_OBJECT_NAME.  This is like most of the standard ELF
6229    definitions except that it uses mips_declare_object() to emit the label.  */
6230
6231 void
6232 mips_declare_object_name (FILE *stream, const char *name,
6233                           tree decl ATTRIBUTE_UNUSED)
6234 {
6235 #ifdef ASM_OUTPUT_TYPE_DIRECTIVE
6236   ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "object");
6237 #endif
6238
6239   size_directive_output = 0;
6240   if (!flag_inhibit_size_directive && DECL_SIZE (decl))
6241     {
6242       HOST_WIDE_INT size;
6243
6244       size_directive_output = 1;
6245       size = int_size_in_bytes (TREE_TYPE (decl));
6246       ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
6247     }
6248
6249   mips_declare_object (stream, name, "", ":\n");
6250 }
6251
6252 /* Implement ASM_FINISH_DECLARE_OBJECT.  This is generic ELF stuff.  */
6253
6254 void
6255 mips_finish_declare_object (FILE *stream, tree decl, int top_level, int at_end)
6256 {
6257   const char *name;
6258
6259   name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
6260   if (!flag_inhibit_size_directive
6261       && DECL_SIZE (decl) != 0
6262       && !at_end && top_level
6263       && DECL_INITIAL (decl) == error_mark_node
6264       && !size_directive_output)
6265     {
6266       HOST_WIDE_INT size;
6267
6268       size_directive_output = 1;
6269       size = int_size_in_bytes (TREE_TYPE (decl));
6270       ASM_OUTPUT_SIZE_DIRECTIVE (stream, name, size);
6271     }
6272 }
6273 #endif
6274 \f
6275 /* Return true if X is a small data address that can be rewritten
6276    as a LO_SUM.  */
6277
6278 static bool
6279 mips_rewrite_small_data_p (rtx x)
6280 {
6281   enum mips_symbol_type symbol_type;
6282
6283   return (TARGET_EXPLICIT_RELOCS
6284           && mips_symbolic_constant_p (x, &symbol_type)
6285           && symbol_type == SYMBOL_SMALL_DATA);
6286 }
6287
6288
6289 /* A for_each_rtx callback for mips_small_data_pattern_p.  */
6290
6291 static int
6292 mips_small_data_pattern_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
6293 {
6294   if (GET_CODE (*loc) == LO_SUM)
6295     return -1;
6296
6297   return mips_rewrite_small_data_p (*loc);
6298 }
6299
6300 /* Return true if OP refers to small data symbols directly, not through
6301    a LO_SUM.  */
6302
6303 bool
6304 mips_small_data_pattern_p (rtx op)
6305 {
6306   return for_each_rtx (&op, mips_small_data_pattern_1, 0);
6307 }
6308 \f
6309 /* A for_each_rtx callback, used by mips_rewrite_small_data.  */
6310
6311 static int
6312 mips_rewrite_small_data_1 (rtx *loc, void *data ATTRIBUTE_UNUSED)
6313 {
6314   if (mips_rewrite_small_data_p (*loc))
6315     *loc = gen_rtx_LO_SUM (Pmode, pic_offset_table_rtx, *loc);
6316
6317   if (GET_CODE (*loc) == LO_SUM)
6318     return -1;
6319
6320   return 0;
6321 }
6322
6323 /* If possible, rewrite OP so that it refers to small data using
6324    explicit relocations.  */
6325
6326 rtx
6327 mips_rewrite_small_data (rtx op)
6328 {
6329   op = copy_insn (op);
6330   for_each_rtx (&op, mips_rewrite_small_data_1, 0);
6331   return op;
6332 }
6333 \f
6334 /* Return true if the current function has an insn that implicitly
6335    refers to $gp.  */
6336
6337 static bool
6338 mips_function_has_gp_insn (void)
6339 {
6340   /* Don't bother rechecking if we found one last time.  */
6341   if (!cfun->machine->has_gp_insn_p)
6342     {
6343       rtx insn;
6344
6345       push_topmost_sequence ();
6346       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6347         if (INSN_P (insn)
6348             && GET_CODE (PATTERN (insn)) != USE
6349             && GET_CODE (PATTERN (insn)) != CLOBBER
6350             && (get_attr_got (insn) != GOT_UNSET
6351                 || small_data_pattern (PATTERN (insn), VOIDmode)))
6352           break;
6353       pop_topmost_sequence ();
6354
6355       cfun->machine->has_gp_insn_p = (insn != 0);
6356     }
6357   return cfun->machine->has_gp_insn_p;
6358 }
6359
6360
6361 /* Return the register that should be used as the global pointer
6362    within this function.  Return 0 if the function doesn't need
6363    a global pointer.  */
6364
6365 static unsigned int
6366 mips_global_pointer (void)
6367 {
6368   unsigned int regno;
6369
6370   /* $gp is always available unless we're using a GOT.  */
6371   if (!TARGET_USE_GOT)
6372     return GLOBAL_POINTER_REGNUM;
6373
6374   /* We must always provide $gp when it is used implicitly.  */
6375   if (!TARGET_EXPLICIT_RELOCS)
6376     return GLOBAL_POINTER_REGNUM;
6377
6378   /* FUNCTION_PROFILER includes a jal macro, so we need to give it
6379      a valid gp.  */
6380   if (current_function_profile)
6381     return GLOBAL_POINTER_REGNUM;
6382
6383   /* If the function has a nonlocal goto, $gp must hold the correct
6384      global pointer for the target function.  */
6385   if (current_function_has_nonlocal_goto)
6386     return GLOBAL_POINTER_REGNUM;
6387
6388   /* If the gp is never referenced, there's no need to initialize it.
6389      Note that reload can sometimes introduce constant pool references
6390      into a function that otherwise didn't need them.  For example,
6391      suppose we have an instruction like:
6392
6393           (set (reg:DF R1) (float:DF (reg:SI R2)))
6394
6395      If R2 turns out to be constant such as 1, the instruction may have a
6396      REG_EQUAL note saying that R1 == 1.0.  Reload then has the option of
6397      using this constant if R2 doesn't get allocated to a register.
6398
6399      In cases like these, reload will have added the constant to the pool
6400      but no instruction will yet refer to it.  */
6401   if (!df_regs_ever_live_p (GLOBAL_POINTER_REGNUM)
6402       && !current_function_uses_const_pool
6403       && !mips_function_has_gp_insn ())
6404     return 0;
6405
6406   /* We need a global pointer, but perhaps we can use a call-clobbered
6407      register instead of $gp.  */
6408   if (TARGET_CALL_SAVED_GP && current_function_is_leaf)
6409     for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
6410       if (!df_regs_ever_live_p (regno)
6411           && call_used_regs[regno]
6412           && !fixed_regs[regno]
6413           && regno != PIC_FUNCTION_ADDR_REGNUM)
6414         return regno;
6415
6416   return GLOBAL_POINTER_REGNUM;
6417 }
6418
6419
6420 /* Return true if the function return value MODE will get returned in a
6421    floating-point register.  */
6422
6423 static bool
6424 mips_return_mode_in_fpr_p (enum machine_mode mode)
6425 {
6426   return ((GET_MODE_CLASS (mode) == MODE_FLOAT
6427            || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT
6428            || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
6429           && GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_HWFPVALUE);
6430 }
6431
6432 /* Return a two-character string representing a function floating-point
6433    return mode, used to name MIPS16 function stubs.  */
6434
6435 static const char *
6436 mips16_call_stub_mode_suffix (enum machine_mode mode)
6437 {
6438   if (mode == SFmode)
6439     return "sf";
6440   else if (mode == DFmode)
6441     return "df";
6442   else if (mode == SCmode)
6443     return "sc";
6444   else if (mode == DCmode)
6445     return "dc";
6446   else if (mode == V2SFmode)
6447     return "df";
6448   else
6449     gcc_unreachable ();
6450 }
6451
6452 /* Return true if the current function returns its value in a floating-point
6453    register in MIPS16 mode.  */
6454
6455 static bool
6456 mips16_cfun_returns_in_fpr_p (void)
6457 {
6458   tree return_type = DECL_RESULT (current_function_decl);
6459   return (mips16_hard_float
6460           && !aggregate_value_p (return_type, current_function_decl)
6461           && mips_return_mode_in_fpr_p (DECL_MODE (return_type)));
6462 }
6463
6464
6465 /* Return true if the current function must save REGNO.  */
6466
6467 static bool
6468 mips_save_reg_p (unsigned int regno)
6469 {
6470   /* We only need to save $gp if TARGET_CALL_SAVED_GP and only then
6471      if we have not chosen a call-clobbered substitute.  */
6472   if (regno == GLOBAL_POINTER_REGNUM)
6473     return TARGET_CALL_SAVED_GP && cfun->machine->global_pointer == regno;
6474
6475   /* Check call-saved registers.  */
6476   if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
6477     return true;
6478
6479  /* Save both registers in an FPR pair if either one is used.  This is
6480     needed for the case when MIN_FPRS_PER_FMT == 1, which allows the odd
6481     register to be used without the even register.  */
6482  if (FP_REG_P (regno)
6483      && MAX_FPRS_PER_FMT == 2
6484      && df_regs_ever_live_p (regno + 1)
6485      && !call_used_regs[regno + 1])
6486    return true;
6487
6488   /* We need to save the old frame pointer before setting up a new one.  */
6489   if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
6490     return true;
6491
6492   /* We need to save the incoming return address if it is ever clobbered
6493      within the function.  */
6494   if (regno == GP_REG_FIRST + 31 && df_regs_ever_live_p (regno))
6495     return true;
6496
6497   if (TARGET_MIPS16)
6498     {
6499       /* $18 is a special case in mips16 code.  It may be used to call
6500          a function which returns a floating point value, but it is
6501          marked in call_used_regs.  */
6502       if (regno == GP_REG_FIRST + 18 && df_regs_ever_live_p (regno))
6503         return true;
6504
6505       /* $31 is also a special case.  It will be used to copy a return
6506          value into the floating point registers if the return value is
6507          floating point.  */
6508       if (regno == GP_REG_FIRST + 31
6509           && mips16_cfun_returns_in_fpr_p ())
6510         return true;
6511     }
6512
6513   return false;
6514 }
6515
6516 /* Return the index of the lowest X in the range [0, SIZE) for which
6517    bit REGS[X] is set in MASK.  Return SIZE if there is no such X.  */
6518
6519 static unsigned int
6520 mips16e_find_first_register (unsigned int mask, const unsigned char *regs,
6521                              unsigned int size)
6522 {
6523   unsigned int i;
6524
6525   for (i = 0; i < size; i++)
6526     if (BITSET_P (mask, regs[i]))
6527       break;
6528
6529   return i;
6530 }
6531
6532 /* *MASK_PTR is a mask of general purpose registers and *GP_REG_SIZE_PTR
6533    is the number of bytes that they occupy.  If *MASK_PTR contains REGS[X]
6534    for some X in [0, SIZE), adjust *MASK_PTR and *GP_REG_SIZE_PTR so that
6535    the same is true for all indexes (X, SIZE).  */
6536
6537 static void
6538 mips16e_mask_registers (unsigned int *mask_ptr, const unsigned char *regs,
6539                         unsigned int size, HOST_WIDE_INT *gp_reg_size_ptr)
6540 {
6541   unsigned int i;
6542
6543   i = mips16e_find_first_register (*mask_ptr, regs, size);
6544   for (i++; i < size; i++)
6545     if (!BITSET_P (*mask_ptr, regs[i]))
6546       {
6547         *gp_reg_size_ptr += GET_MODE_SIZE (gpr_mode);
6548         *mask_ptr |= 1 << regs[i];
6549       }
6550 }
6551
6552 /* Return the bytes needed to compute the frame pointer from the current
6553    stack pointer.  SIZE is the size (in bytes) of the local variables.
6554
6555    MIPS stack frames look like:
6556
6557              Before call                        After call
6558    high +-----------------------+       +-----------------------+
6559    mem. |                       |       |                       |
6560         |  caller's temps.      |       |  caller's temps.      |
6561         |                       |       |                       |
6562         +-----------------------+       +-----------------------+
6563         |                       |       |                       |
6564         |  arguments on stack.  |       |  arguments on stack.  |
6565         |                       |       |                       |
6566         +-----------------------+       +-----------------------+
6567         |  4 words to save      |       |  4 words to save      |
6568         |  arguments passed     |       |  arguments passed     |
6569         |  in registers, even   |       |  in registers, even   |
6570         |  if not passed.       |       |  if not passed.       |
6571     SP->+-----------------------+  VFP->+-----------------------+
6572                 (VFP = SP+fp_sp_offset) |                       |\
6573                                         |  fp register save     | | fp_reg_size
6574                                         |                       |/
6575                        SP+gp_sp_offset->+-----------------------+
6576                                        /|                       |\
6577                                       | |  gp register save     | | gp_reg_size
6578                        gp_reg_rounded | |                       |/
6579                                       | +-----------------------+
6580                                        \|  alignment padding    |
6581                                         +-----------------------+
6582                                         |                       |\
6583                                         |  local variables      | | var_size
6584                                         |                       |/
6585                                         +-----------------------+
6586                                         |                       |
6587                                         |  alloca allocations   |
6588                                         |                       |
6589                                         +-----------------------+
6590                                        /|                       |
6591                        cprestore_size | |  GP save for V.4 abi  |
6592                                        \|                       |
6593                                         +-----------------------+
6594                                         |                       |\
6595                                         |  arguments on stack   | |
6596                                         |                       | |
6597                                         +-----------------------+ |
6598                                         |  4 words to save      | | args_size
6599                                         |  arguments passed     | |
6600                                         |  in registers, even   | |
6601                                         |  if not passed.       | |
6602    low                                  |  (TARGET_OLDABI only) |/
6603    memory                           SP->+-----------------------+
6604
6605 */
6606
6607 HOST_WIDE_INT
6608 compute_frame_size (HOST_WIDE_INT size)
6609 {
6610   unsigned int regno;
6611   HOST_WIDE_INT total_size;     /* # bytes that the entire frame takes up */
6612   HOST_WIDE_INT var_size;       /* # bytes that variables take up */
6613   HOST_WIDE_INT args_size;      /* # bytes that outgoing arguments take up */
6614   HOST_WIDE_INT cprestore_size; /* # bytes that the cprestore slot takes up */
6615   HOST_WIDE_INT gp_reg_rounded; /* # bytes needed to store gp after rounding */
6616   HOST_WIDE_INT gp_reg_size;    /* # bytes needed to store gp regs */
6617   HOST_WIDE_INT fp_reg_size;    /* # bytes needed to store fp regs */
6618   unsigned int mask;            /* mask of saved gp registers */
6619   unsigned int fmask;           /* mask of saved fp registers */
6620
6621   cfun->machine->global_pointer = mips_global_pointer ();
6622
6623   gp_reg_size = 0;
6624   fp_reg_size = 0;
6625   mask = 0;
6626   fmask = 0;
6627   var_size = MIPS_STACK_ALIGN (size);
6628   args_size = current_function_outgoing_args_size;
6629   cprestore_size = MIPS_STACK_ALIGN (STARTING_FRAME_OFFSET) - args_size;
6630
6631   /* The space set aside by STARTING_FRAME_OFFSET isn't needed in leaf
6632      functions.  If the function has local variables, we're committed
6633      to allocating it anyway.  Otherwise reclaim it here.  */
6634   if (var_size == 0 && current_function_is_leaf)
6635     cprestore_size = args_size = 0;
6636
6637   /* The MIPS 3.0 linker does not like functions that dynamically
6638      allocate the stack and have 0 for STACK_DYNAMIC_OFFSET, since it
6639      looks like we are trying to create a second frame pointer to the
6640      function, so allocate some stack space to make it happy.  */
6641
6642   if (args_size == 0 && current_function_calls_alloca)
6643     args_size = 4 * UNITS_PER_WORD;
6644
6645   total_size = var_size + args_size + cprestore_size;
6646
6647   /* Calculate space needed for gp registers.  */
6648   for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
6649     if (mips_save_reg_p (regno))
6650       {
6651         gp_reg_size += GET_MODE_SIZE (gpr_mode);
6652         mask |= 1 << (regno - GP_REG_FIRST);
6653       }
6654
6655   /* We need to restore these for the handler.  */
6656   if (current_function_calls_eh_return)
6657     {
6658       unsigned int i;
6659       for (i = 0; ; ++i)
6660         {
6661           regno = EH_RETURN_DATA_REGNO (i);
6662           if (regno == INVALID_REGNUM)
6663             break;
6664           gp_reg_size += GET_MODE_SIZE (gpr_mode);
6665           mask |= 1 << (regno - GP_REG_FIRST);
6666         }
6667     }
6668
6669   /* The MIPS16e SAVE and RESTORE instructions have two ranges of registers:
6670      $a3-$a0 and $s2-$s8.  If we save one register in the range, we must
6671      save all later registers too.  */
6672   if (GENERATE_MIPS16E_SAVE_RESTORE)
6673     {
6674       mips16e_mask_registers (&mask, mips16e_s2_s8_regs,
6675                               ARRAY_SIZE (mips16e_s2_s8_regs), &gp_reg_size);
6676       mips16e_mask_registers (&mask, mips16e_a0_a3_regs,
6677                               ARRAY_SIZE (mips16e_a0_a3_regs), &gp_reg_size);
6678     }
6679
6680   /* This loop must iterate over the same space as its companion in
6681      mips_for_each_saved_reg.  */
6682   for (regno = (FP_REG_LAST - MAX_FPRS_PER_FMT + 1);
6683        regno >= FP_REG_FIRST;
6684        regno -= MAX_FPRS_PER_FMT)
6685     {
6686       if (mips_save_reg_p (regno))
6687         {
6688           fp_reg_size += MAX_FPRS_PER_FMT * UNITS_PER_FPREG;
6689           fmask |= ((1 << MAX_FPRS_PER_FMT) - 1) << (regno - FP_REG_FIRST);
6690         }
6691     }
6692
6693   gp_reg_rounded = MIPS_STACK_ALIGN (gp_reg_size);
6694   total_size += gp_reg_rounded + MIPS_STACK_ALIGN (fp_reg_size);
6695
6696   /* Add in the space required for saving incoming register arguments.  */
6697   total_size += current_function_pretend_args_size;
6698   total_size += MIPS_STACK_ALIGN (cfun->machine->varargs_size);
6699
6700   /* Save other computed information.  */
6701   cfun->machine->frame.total_size = total_size;
6702   cfun->machine->frame.var_size = var_size;
6703   cfun->machine->frame.args_size = args_size;
6704   cfun->machine->frame.cprestore_size = cprestore_size;
6705   cfun->machine->frame.gp_reg_size = gp_reg_size;
6706   cfun->machine->frame.fp_reg_size = fp_reg_size;
6707   cfun->machine->frame.mask = mask;
6708   cfun->machine->frame.fmask = fmask;
6709   cfun->machine->frame.initialized = reload_completed;
6710   cfun->machine->frame.num_gp = gp_reg_size / UNITS_PER_WORD;
6711   cfun->machine->frame.num_fp = (fp_reg_size
6712                                  / (MAX_FPRS_PER_FMT * UNITS_PER_FPREG));
6713
6714   if (mask)
6715     {
6716       HOST_WIDE_INT offset;
6717
6718       /* MIPS16e SAVE and RESTORE instructions require the GP save area
6719          to be aligned at the high end with any padding at the low end,
6720          so do it that way all the time.  */
6721       offset = (total_size
6722                 - MIPS_STACK_ALIGN (fp_reg_size)
6723                 - GET_MODE_SIZE (gpr_mode));
6724       cfun->machine->frame.gp_sp_offset = offset;
6725       cfun->machine->frame.gp_save_offset = offset - total_size;
6726     }
6727   else
6728     {
6729       cfun->machine->frame.gp_sp_offset = 0;
6730       cfun->machine->frame.gp_save_offset = 0;
6731     }
6732
6733   if (fmask)
6734     {
6735       HOST_WIDE_INT offset;
6736
6737       offset = (args_size + cprestore_size + var_size
6738                 + gp_reg_rounded + fp_reg_size
6739                 - MAX_FPRS_PER_FMT * UNITS_PER_FPREG);
6740       cfun->machine->frame.fp_sp_offset = offset;
6741       cfun->machine->frame.fp_save_offset = offset - total_size;
6742     }
6743   else
6744     {
6745       cfun->machine->frame.fp_sp_offset = 0;
6746       cfun->machine->frame.fp_save_offset = 0;
6747     }
6748
6749   /* Ok, we're done.  */
6750   return total_size;
6751 }
6752 \f
6753 /* Implement INITIAL_ELIMINATION_OFFSET.  FROM is either the frame
6754    pointer or argument pointer.  TO is either the stack pointer or
6755    hard frame pointer.  */
6756
6757 HOST_WIDE_INT
6758 mips_initial_elimination_offset (int from, int to)
6759 {
6760   HOST_WIDE_INT offset;
6761
6762   compute_frame_size (get_frame_size ());
6763
6764   /* Set OFFSET to the offset from the stack pointer.  */
6765   switch (from)
6766     {
6767     case FRAME_POINTER_REGNUM:
6768       offset = 0;
6769       break;
6770
6771     case ARG_POINTER_REGNUM:
6772       offset = (cfun->machine->frame.total_size
6773                 - current_function_pretend_args_size);
6774       break;
6775
6776     default:
6777       gcc_unreachable ();
6778     }
6779
6780   if (TARGET_MIPS16 && to == HARD_FRAME_POINTER_REGNUM)
6781     offset -= cfun->machine->frame.args_size;
6782
6783   return offset;
6784 }
6785 \f
6786 /* Implement RETURN_ADDR_RTX.  Note, we do not support moving
6787    back to a previous frame.  */
6788 rtx
6789 mips_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
6790 {
6791   if (count != 0)
6792     return const0_rtx;
6793
6794   return get_hard_reg_initial_val (Pmode, GP_REG_FIRST + 31);
6795 }
6796 \f
6797 /* Use FN to save or restore register REGNO.  MODE is the register's
6798    mode and OFFSET is the offset of its save slot from the current
6799    stack pointer.  */
6800
6801 static void
6802 mips_save_restore_reg (enum machine_mode mode, int regno,
6803                        HOST_WIDE_INT offset, mips_save_restore_fn fn)
6804 {
6805   rtx mem;
6806
6807   mem = gen_frame_mem (mode, plus_constant (stack_pointer_rtx, offset));
6808
6809   fn (gen_rtx_REG (mode, regno), mem);
6810 }
6811
6812
6813 /* Call FN for each register that is saved by the current function.
6814    SP_OFFSET is the offset of the current stack pointer from the start
6815    of the frame.  */
6816
6817 static void
6818 mips_for_each_saved_reg (HOST_WIDE_INT sp_offset, mips_save_restore_fn fn)
6819 {
6820   enum machine_mode fpr_mode;
6821   HOST_WIDE_INT offset;
6822   int regno;
6823
6824   /* Save registers starting from high to low.  The debuggers prefer at least
6825      the return register be stored at func+4, and also it allows us not to
6826      need a nop in the epilogue if at least one register is reloaded in
6827      addition to return address.  */
6828   offset = cfun->machine->frame.gp_sp_offset - sp_offset;
6829   for (regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
6830     if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
6831       {
6832         mips_save_restore_reg (gpr_mode, regno, offset, fn);
6833         offset -= GET_MODE_SIZE (gpr_mode);
6834       }
6835
6836   /* This loop must iterate over the same space as its companion in
6837      compute_frame_size.  */
6838   offset = cfun->machine->frame.fp_sp_offset - sp_offset;
6839   fpr_mode = (TARGET_SINGLE_FLOAT ? SFmode : DFmode);
6840   for (regno = (FP_REG_LAST - MAX_FPRS_PER_FMT + 1);
6841        regno >= FP_REG_FIRST;
6842        regno -= MAX_FPRS_PER_FMT)
6843     if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
6844       {
6845         mips_save_restore_reg (fpr_mode, regno, offset, fn);
6846         offset -= GET_MODE_SIZE (fpr_mode);
6847       }
6848 }
6849 \f
6850 /* If we're generating n32 or n64 abicalls, and the current function
6851    does not use $28 as its global pointer, emit a cplocal directive.
6852    Use pic_offset_table_rtx as the argument to the directive.  */
6853
6854 static void
6855 mips_output_cplocal (void)
6856 {
6857   if (!TARGET_EXPLICIT_RELOCS
6858       && cfun->machine->global_pointer > 0
6859       && cfun->machine->global_pointer != GLOBAL_POINTER_REGNUM)
6860     output_asm_insn (".cplocal %+", 0);
6861 }
6862
6863 /* Return the style of GP load sequence that is being used for the
6864    current function.  */
6865
6866 enum mips_loadgp_style
6867 mips_current_loadgp_style (void)
6868 {
6869   if (!TARGET_USE_GOT || cfun->machine->global_pointer == 0)
6870     return LOADGP_NONE;
6871
6872   if (TARGET_RTP_PIC)
6873     return LOADGP_RTP;
6874
6875   if (TARGET_ABSOLUTE_ABICALLS)
6876     return LOADGP_ABSOLUTE;
6877
6878   return TARGET_NEWABI ? LOADGP_NEWABI : LOADGP_OLDABI;
6879 }
6880
6881 /* The __gnu_local_gp symbol.  */
6882
6883 static GTY(()) rtx mips_gnu_local_gp;
6884
6885 /* If we're generating n32 or n64 abicalls, emit instructions
6886    to set up the global pointer.  */
6887
6888 static void
6889 mips_emit_loadgp (void)
6890 {
6891   rtx addr, offset, incoming_address, base, index;
6892
6893   switch (mips_current_loadgp_style ())
6894     {
6895     case LOADGP_ABSOLUTE:
6896       if (mips_gnu_local_gp == NULL)
6897         {
6898           mips_gnu_local_gp = gen_rtx_SYMBOL_REF (Pmode, "__gnu_local_gp");
6899           SYMBOL_REF_FLAGS (mips_gnu_local_gp) |= SYMBOL_FLAG_LOCAL;
6900         }
6901       emit_insn (gen_loadgp_absolute (mips_gnu_local_gp));
6902       break;
6903
6904     case LOADGP_NEWABI:
6905       addr = XEXP (DECL_RTL (current_function_decl), 0);
6906       offset = mips_unspec_address (addr, SYMBOL_GOTOFF_LOADGP);
6907       incoming_address = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
6908       emit_insn (gen_loadgp_newabi (offset, incoming_address));
6909       if (!TARGET_EXPLICIT_RELOCS)
6910         emit_insn (gen_loadgp_blockage ());
6911       break;
6912
6913     case LOADGP_RTP:
6914       base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_BASE));
6915       index = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (VXWORKS_GOTT_INDEX));
6916       emit_insn (gen_loadgp_rtp (base, index));
6917       if (!TARGET_EXPLICIT_RELOCS)
6918         emit_insn (gen_loadgp_blockage ());
6919       break;
6920
6921     default:
6922       break;
6923     }
6924 }
6925
6926 /* Set up the stack and frame (if desired) for the function.  */
6927
6928 static void
6929 mips_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
6930 {
6931   const char *fnname;
6932   HOST_WIDE_INT tsize = cfun->machine->frame.total_size;
6933
6934 #ifdef SDB_DEBUGGING_INFO
6935   if (debug_info_level != DINFO_LEVEL_TERSE && write_symbols == SDB_DEBUG)
6936     SDB_OUTPUT_SOURCE_LINE (file, DECL_SOURCE_LINE (current_function_decl));
6937 #endif
6938
6939   /* In mips16 mode, we may need to generate a 32 bit to handle
6940      floating point arguments.  The linker will arrange for any 32-bit
6941      functions to call this stub, which will then jump to the 16-bit
6942      function proper.  */
6943   if (mips16_hard_float
6944       && current_function_args_info.fp_code != 0)
6945     build_mips16_function_stub (file);
6946
6947   if (!FUNCTION_NAME_ALREADY_DECLARED)
6948     {
6949       /* Get the function name the same way that toplev.c does before calling
6950          assemble_start_function.  This is needed so that the name used here
6951          exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
6952       fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
6953
6954       if (!flag_inhibit_size_directive)
6955         {
6956           fputs ("\t.ent\t", file);
6957           assemble_name (file, fnname);
6958           fputs ("\n", file);
6959         }
6960
6961       assemble_name (file, fnname);
6962       fputs (":\n", file);
6963     }
6964
6965   /* Stop mips_file_end from treating this function as external.  */
6966   if (TARGET_IRIX && mips_abi == ABI_32)
6967     TREE_ASM_WRITTEN (DECL_NAME (cfun->decl)) = 1;
6968
6969   if (!flag_inhibit_size_directive)
6970     {
6971       /* .frame FRAMEREG, FRAMESIZE, RETREG */
6972       fprintf (file,
6973                "\t.frame\t%s," HOST_WIDE_INT_PRINT_DEC ",%s\t\t"
6974                "# vars= " HOST_WIDE_INT_PRINT_DEC ", regs= %d/%d"
6975                ", args= " HOST_WIDE_INT_PRINT_DEC
6976                ", gp= " HOST_WIDE_INT_PRINT_DEC "\n",
6977                (reg_names[(frame_pointer_needed)
6978                           ? HARD_FRAME_POINTER_REGNUM : STACK_POINTER_REGNUM]),
6979                ((frame_pointer_needed && TARGET_MIPS16)
6980                 ? tsize - cfun->machine->frame.args_size
6981                 : tsize),
6982                reg_names[GP_REG_FIRST + 31],
6983                cfun->machine->frame.var_size,
6984                cfun->machine->frame.num_gp,
6985                cfun->machine->frame.num_fp,
6986                cfun->machine->frame.args_size,
6987                cfun->machine->frame.cprestore_size);
6988
6989       /* .mask MASK, GPOFFSET; .fmask FPOFFSET */
6990       fprintf (file, "\t.mask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
6991                cfun->machine->frame.mask,
6992                cfun->machine->frame.gp_save_offset);
6993       fprintf (file, "\t.fmask\t0x%08x," HOST_WIDE_INT_PRINT_DEC "\n",
6994                cfun->machine->frame.fmask,
6995                cfun->machine->frame.fp_save_offset);
6996
6997       /* Require:
6998          OLD_SP == *FRAMEREG + FRAMESIZE => can find old_sp from nominated FP reg.
6999          HIGHEST_GP_SAVED == *FRAMEREG + FRAMESIZE + GPOFFSET => can find saved regs.  */
7000     }
7001
7002   if (mips_current_loadgp_style () == LOADGP_OLDABI)
7003     {
7004       /* Handle the initialization of $gp for SVR4 PIC.  */
7005       if (!cfun->machine->all_noreorder_p)
7006         output_asm_insn ("%(.cpload\t%^%)", 0);
7007       else
7008         output_asm_insn ("%(.cpload\t%^\n\t%<", 0);
7009     }
7010   else if (cfun->machine->all_noreorder_p)
7011     output_asm_insn ("%(%<", 0);
7012
7013   /* Tell the assembler which register we're using as the global
7014      pointer.  This is needed for thunks, since they can use either
7015      explicit relocs or assembler macros.  */
7016   mips_output_cplocal ();
7017 }
7018 \f
7019 /* Make the last instruction frame related and note that it performs
7020    the operation described by FRAME_PATTERN.  */
7021
7022 static void
7023 mips_set_frame_expr (rtx frame_pattern)
7024 {
7025   rtx insn;
7026
7027   insn = get_last_insn ();
7028   RTX_FRAME_RELATED_P (insn) = 1;
7029   REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
7030                                       frame_pattern,
7031                                       REG_NOTES (insn));
7032 }
7033
7034
7035 /* Return a frame-related rtx that stores REG at MEM.
7036    REG must be a single register.  */
7037
7038 static rtx
7039 mips_frame_set (rtx mem, rtx reg)
7040 {
7041   rtx set;
7042
7043   /* If we're saving the return address register and the dwarf return
7044      address column differs from the hard register number, adjust the
7045      note reg to refer to the former.  */
7046   if (REGNO (reg) == GP_REG_FIRST + 31
7047       && DWARF_FRAME_RETURN_COLUMN != GP_REG_FIRST + 31)
7048     reg = gen_rtx_REG (GET_MODE (reg), DWARF_FRAME_RETURN_COLUMN);
7049
7050   set = gen_rtx_SET (VOIDmode, mem, reg);
7051   RTX_FRAME_RELATED_P (set) = 1;
7052
7053   return set;
7054 }
7055
7056
7057 /* Save register REG to MEM.  Make the instruction frame-related.  */
7058
7059 static void
7060 mips_save_reg (rtx reg, rtx mem)
7061 {
7062   if (GET_MODE (reg) == DFmode && !TARGET_FLOAT64)
7063     {
7064       rtx x1, x2;
7065
7066       if (mips_split_64bit_move_p (mem, reg))
7067         mips_split_64bit_move (mem, reg);
7068       else
7069         emit_move_insn (mem, reg);
7070
7071       x1 = mips_frame_set (mips_subword (mem, 0), mips_subword (reg, 0));
7072       x2 = mips_frame_set (mips_subword (mem, 1), mips_subword (reg, 1));
7073       mips_set_frame_expr (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, x1, x2)));
7074     }
7075   else
7076     {
7077       if (TARGET_MIPS16
7078           && REGNO (reg) != GP_REG_FIRST + 31
7079           && !M16_REG_P (REGNO (reg)))
7080         {
7081           /* Save a non-mips16 register by moving it through a temporary.
7082              We don't need to do this for $31 since there's a special
7083              instruction for it.  */
7084           emit_move_insn (MIPS_PROLOGUE_TEMP (GET_MODE (reg)), reg);
7085           emit_move_insn (mem, MIPS_PROLOGUE_TEMP (GET_MODE (reg)));
7086         }
7087       else
7088         emit_move_insn (mem, reg);
7089
7090       mips_set_frame_expr (mips_frame_set (mem, reg));
7091     }
7092 }
7093
7094 /* Return a move between register REGNO and memory location SP + OFFSET.
7095    Make the move a load if RESTORE_P, otherwise make it a frame-related
7096    store.  */
7097
7098 static rtx
7099 mips16e_save_restore_reg (bool restore_p, HOST_WIDE_INT offset,
7100                           unsigned int regno)
7101 {
7102   rtx reg, mem;
7103
7104   mem = gen_frame_mem (SImode, plus_constant (stack_pointer_rtx, offset));
7105   reg = gen_rtx_REG (SImode, regno);
7106   return (restore_p
7107           ? gen_rtx_SET (VOIDmode, reg, mem)
7108           : mips_frame_set (mem, reg));
7109 }
7110
7111 /* Return RTL for a MIPS16e SAVE or RESTORE instruction; RESTORE_P says which.
7112    The instruction must:
7113
7114      - Allocate or deallocate SIZE bytes in total; SIZE is known
7115        to be nonzero.
7116
7117      - Save or restore as many registers in *MASK_PTR as possible.
7118        The instruction saves the first registers at the top of the
7119        allocated area, with the other registers below it.
7120
7121      - Save NARGS argument registers above the allocated area.
7122
7123    (NARGS is always zero if RESTORE_P.)
7124
7125    The SAVE and RESTORE instructions cannot save and restore all general
7126    registers, so there may be some registers left over for the caller to
7127    handle.  Destructively modify *MASK_PTR so that it contains the registers
7128    that still need to be saved or restored.  The caller can save these
7129    registers in the memory immediately below *OFFSET_PTR, which is a
7130    byte offset from the bottom of the allocated stack area.  */
7131
7132 static rtx
7133 mips16e_build_save_restore (bool restore_p, unsigned int *mask_ptr,
7134                             HOST_WIDE_INT *offset_ptr, unsigned int nargs,
7135                             HOST_WIDE_INT size)
7136 {
7137   rtx pattern, set;
7138   HOST_WIDE_INT offset, top_offset;
7139   unsigned int i, regno;
7140   int n;
7141
7142   gcc_assert (cfun->machine->frame.fp_reg_size == 0);
7143
7144   /* Calculate the number of elements in the PARALLEL.  We need one element
7145      for the stack adjustment, one for each argument register save, and one
7146      for each additional register move.  */
7147   n = 1 + nargs;
7148   for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
7149     if (BITSET_P (*mask_ptr, mips16e_save_restore_regs[i]))
7150       n++;
7151
7152   /* Create the final PARALLEL.  */
7153   pattern = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (n));
7154   n = 0;
7155
7156   /* Add the stack pointer adjustment.  */
7157   set = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
7158                      plus_constant (stack_pointer_rtx,
7159                                     restore_p ? size : -size));
7160   RTX_FRAME_RELATED_P (set) = 1;
7161   XVECEXP (pattern, 0, n++) = set;
7162
7163   /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
7164   top_offset = restore_p ? size : 0;
7165
7166   /* Save the arguments.  */
7167   for (i = 0; i < nargs; i++)
7168     {
7169       offset = top_offset + i * GET_MODE_SIZE (gpr_mode);
7170       set = mips16e_save_restore_reg (restore_p, offset, GP_ARG_FIRST + i);
7171       XVECEXP (pattern, 0, n++) = set;
7172     }
7173
7174   /* Then fill in the other register moves.  */
7175   offset = top_offset;
7176   for (i = 0; i < ARRAY_SIZE (mips16e_save_restore_regs); i++)
7177     {
7178       regno = mips16e_save_restore_regs[i];
7179       if (BITSET_P (*mask_ptr, regno))
7180         {
7181           offset -= UNITS_PER_WORD;
7182           set = mips16e_save_restore_reg (restore_p, offset, regno);
7183           XVECEXP (pattern, 0, n++) = set;
7184           *mask_ptr &= ~(1 << regno);
7185         }
7186     }
7187
7188   /* Tell the caller what offset it should use for the remaining registers.  */
7189   *offset_ptr = size + (offset - top_offset) + size;
7190
7191   gcc_assert (n == XVECLEN (pattern, 0));
7192
7193   return pattern;
7194 }
7195
7196 /* PATTERN is a PARALLEL whose first element adds ADJUST to the stack
7197    pointer.  Return true if PATTERN matches the kind of instruction
7198    generated by mips16e_build_save_restore.  If INFO is nonnull,
7199    initialize it when returning true.  */
7200
7201 bool
7202 mips16e_save_restore_pattern_p (rtx pattern, HOST_WIDE_INT adjust,
7203                                 struct mips16e_save_restore_info *info)
7204 {
7205   unsigned int i, nargs, mask;
7206   HOST_WIDE_INT top_offset, save_offset, offset, extra;
7207   rtx set, reg, mem, base;
7208   int n;
7209
7210   if (!GENERATE_MIPS16E_SAVE_RESTORE)
7211     return false;
7212
7213   /* Stack offsets in the PARALLEL are relative to the old stack pointer.  */
7214   top_offset = adjust > 0 ? adjust : 0;
7215
7216   /* Interpret all other members of the PARALLEL.  */
7217   save_offset = top_offset - GET_MODE_SIZE (gpr_mode);
7218   mask = 0;
7219   nargs = 0;
7220   i = 0;
7221   for (n = 1; n < XVECLEN (pattern, 0); n++)
7222     {
7223       /* Check that we have a SET.  */
7224       set = XVECEXP (pattern, 0, n);
7225       if (GET_CODE (set) != SET)
7226         return false;
7227
7228       /* Check that the SET is a load (if restoring) or a store
7229          (if saving).  */
7230       mem = adjust > 0 ? SET_SRC (set) : SET_DEST (set);
7231       if (!MEM_P (mem))
7232         return false;
7233
7234       /* Check that the address is the sum of the stack pointer and a
7235          possibly-zero constant offset.  */
7236       mips_split_plus (XEXP (mem, 0), &base, &offset);
7237       if (base != stack_pointer_rtx)
7238         return false;
7239
7240       /* Check that SET's other operand is a register.  */
7241       reg = adjust > 0 ? SET_DEST (set) : SET_SRC (set);
7242       if (!REG_P (reg))
7243         return false;
7244
7245       /* Check for argument saves.  */
7246       if (offset == top_offset + nargs * GET_MODE_SIZE (gpr_mode)
7247           && REGNO (reg) == GP_ARG_FIRST + nargs)
7248         nargs++;
7249       else if (offset == save_offset)
7250         {
7251           while (mips16e_save_restore_regs[i++] != REGNO (reg))
7252             if (i == ARRAY_SIZE (mips16e_save_restore_regs))
7253               return false;
7254
7255           mask |= 1 << REGNO (reg);
7256           save_offset -= GET_MODE_SIZE (gpr_mode);
7257         }
7258       else
7259         return false;
7260     }
7261
7262   /* Check that the restrictions on register ranges are met.  */
7263   extra = 0;
7264   mips16e_mask_registers (&mask, mips16e_s2_s8_regs,
7265                           ARRAY_SIZE (mips16e_s2_s8_regs), &extra);
7266   mips16e_mask_registers (&mask, mips16e_a0_a3_regs,
7267                           ARRAY_SIZE (mips16e_a0_a3_regs), &extra);
7268   if (extra != 0)
7269     return false;
7270
7271   /* Pass back information, if requested.  */
7272   if (info)
7273     {
7274       info->nargs = nargs;
7275       info->mask = mask;
7276       info->size = (adjust > 0 ? adjust : -adjust);
7277     }
7278
7279   return true;
7280 }
7281
7282 /* Add a MIPS16e SAVE or RESTORE register-range argument to string S
7283    for the register range [MIN_REG, MAX_REG].  Return a pointer to
7284    the null terminator.  */
7285
7286 static char *
7287 mips16e_add_register_range (char *s, unsigned int min_reg,
7288                             unsigned int max_reg)
7289 {
7290   if (min_reg != max_reg)
7291     s += sprintf (s, ",%s-%s", reg_names[min_reg], reg_names[max_reg]);
7292   else
7293     s += sprintf (s, ",%s", reg_names[min_reg]);
7294   return s;
7295 }
7296
7297 /* Return the assembly instruction for a MIPS16e SAVE or RESTORE instruction.
7298    PATTERN and ADJUST are as for mips16e_save_restore_pattern_p.  */
7299
7300 const char *
7301 mips16e_output_save_restore (rtx pattern, HOST_WIDE_INT adjust)
7302 {
7303   static char buffer[300];
7304
7305   struct mips16e_save_restore_info info;
7306   unsigned int i, end;
7307   char *s;
7308
7309   /* Parse the pattern.  */
7310   if (!mips16e_save_restore_pattern_p (pattern, adjust, &info))
7311     gcc_unreachable ();
7312
7313   /* Add the mnemonic.  */
7314   s = strcpy (buffer, adjust > 0 ? "restore\t" : "save\t");
7315   s += strlen (s);
7316
7317   /* Save the arguments.  */
7318   if (info.nargs > 1)
7319     s += sprintf (s, "%s-%s,", reg_names[GP_ARG_FIRST],
7320                   reg_names[GP_ARG_FIRST + info.nargs - 1]);
7321   else if (info.nargs == 1)
7322     s += sprintf (s, "%s,", reg_names[GP_ARG_FIRST]);
7323
7324   /* Emit the amount of stack space to allocate or deallocate.  */
7325   s += sprintf (s, "%d", (int) info.size);
7326
7327   /* Save or restore $16.  */
7328   if (BITSET_P (info.mask, 16))
7329     s += sprintf (s, ",%s", reg_names[GP_REG_FIRST + 16]);
7330
7331   /* Save or restore $17.  */
7332   if (BITSET_P (info.mask, 17))
7333     s += sprintf (s, ",%s", reg_names[GP_REG_FIRST + 17]);
7334
7335   /* Save or restore registers in the range $s2...$s8, which
7336      mips16e_s2_s8_regs lists in decreasing order.  Note that this
7337      is a software register range; the hardware registers are not
7338      numbered consecutively.  */
7339   end = ARRAY_SIZE (mips16e_s2_s8_regs);
7340   i = mips16e_find_first_register (info.mask, mips16e_s2_s8_regs, end);
7341   if (i < end)
7342     s = mips16e_add_register_range (s, mips16e_s2_s8_regs[end - 1],
7343                                     mips16e_s2_s8_regs[i]);
7344
7345   /* Save or restore registers in the range $a0...$a3.  */
7346   end = ARRAY_SIZE (mips16e_a0_a3_regs);
7347   i = mips16e_find_first_register (info.mask, mips16e_a0_a3_regs, end);
7348   if (i < end)
7349     s = mips16e_add_register_range (s, mips16e_a0_a3_regs[i],
7350                                     mips16e_a0_a3_regs[end - 1]);
7351
7352   /* Save or restore $31.  */
7353   if (BITSET_P (info.mask, 31))
7354     s += sprintf (s, ",%s", reg_names[GP_REG_FIRST + 31]);
7355
7356   return buffer;
7357 }
7358
7359 /* Return a simplified form of X using the register values in REG_VALUES.
7360    REG_VALUES[R] is the last value assigned to hard register R, or null
7361    if R has not been modified.
7362
7363    This function is rather limited, but is good enough for our purposes.  */
7364
7365 static rtx
7366 mips16e_collect_propagate_value (rtx x, rtx *reg_values)
7367 {
7368   rtx x0, x1;
7369
7370   x = avoid_constant_pool_reference (x);
7371
7372   if (UNARY_P (x))
7373     {
7374       x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
7375       return simplify_gen_unary (GET_CODE (x), GET_MODE (x),
7376                                  x0, GET_MODE (XEXP (x, 0)));
7377     }
7378
7379   if (ARITHMETIC_P (x))
7380     {
7381       x0 = mips16e_collect_propagate_value (XEXP (x, 0), reg_values);
7382       x1 = mips16e_collect_propagate_value (XEXP (x, 1), reg_values);
7383       return simplify_gen_binary (GET_CODE (x), GET_MODE (x), x0, x1);
7384     }
7385
7386   if (REG_P (x)
7387       && reg_values[REGNO (x)]
7388       && !rtx_unstable_p (reg_values[REGNO (x)]))
7389     return reg_values[REGNO (x)];
7390
7391   return x;
7392 }
7393
7394 /* Return true if (set DEST SRC) stores an argument register into its
7395    caller-allocated save slot.  If the register is not included in
7396    [GP_ARG_FIRST, GP_ARG_LAST + *NARGS_PTR), destructively modify
7397    *NARGS_PTR such that this condition holds.  REG_VALUES is as for
7398    mips16e_collect_propagate_value.  */
7399
7400 static bool
7401 mips16e_collect_argument_save (rtx dest, rtx src, rtx *reg_values,
7402                                unsigned int *nargs_ptr)
7403 {
7404   unsigned int argno, regno;
7405   HOST_WIDE_INT offset, required_offset;
7406   rtx addr, base;
7407
7408   /* Check that this is a word-mode store.  */
7409   if (!MEM_P (dest) || !REG_P (src) || GET_MODE (dest) != word_mode)
7410     return false;
7411
7412   /* Check that the register being saved is an unmodified argument
7413      register.  */
7414   regno = REGNO (src);
7415   if (regno < GP_ARG_FIRST || regno > GP_ARG_LAST || reg_values[regno])
7416     return false;
7417   argno = regno - GP_ARG_FIRST;
7418
7419   /* Check whether the address is an appropriate stack pointer or
7420      frame pointer access.  The frame pointer is offset from the
7421      stack pointer by the size of the outgoing arguments.  */
7422   addr = mips16e_collect_propagate_value (XEXP (dest, 0), reg_values);
7423   mips_split_plus (addr, &base, &offset);
7424   required_offset = cfun->machine->frame.total_size + argno * UNITS_PER_WORD;
7425   if (base == hard_frame_pointer_rtx)
7426     required_offset -= cfun->machine->frame.args_size;
7427   else if (base != stack_pointer_rtx)
7428     return false;
7429   if (offset != required_offset)
7430     return false;
7431
7432   /* Make sure that *NARGS_PTR is big enough.  */
7433   if (*nargs_ptr <= argno)
7434     *nargs_ptr = argno + 1;
7435
7436   return true;
7437 }
7438
7439 /* A subroutine of mips_expand_prologue, called only when generating
7440    MIPS16e SAVE instructions.  Search the start of the function for any
7441    instructions that save argument registers into their caller-allocated
7442    save slots.  Delete such instructions and return a value N such that
7443    saving [GP_ARG_FIRST, GP_ARG_FIRST + N) would make all the deleted
7444    instructions redundant.  */
7445
7446 static unsigned int
7447 mips16e_collect_argument_saves (void)
7448 {
7449   rtx reg_values[FIRST_PSEUDO_REGISTER];
7450   rtx insn, next, set, dest, src;
7451   unsigned int nargs;
7452
7453   push_topmost_sequence ();
7454   nargs = 0;
7455   memset (reg_values, 0, sizeof (reg_values));
7456   for (insn = get_insns (); insn; insn = next)
7457     {
7458       next = NEXT_INSN (insn);
7459       if (NOTE_P (insn))
7460         continue;
7461
7462       if (!INSN_P (insn))
7463         break;
7464
7465       set = PATTERN (insn);
7466       if (GET_CODE (set) != SET)
7467         break;
7468
7469       dest = SET_DEST (set);
7470       src = SET_SRC (set);
7471       if (mips16e_collect_argument_save (dest, src, reg_values, &nargs))
7472         delete_insn (insn);
7473       else if (REG_P (dest) && GET_MODE (dest) == word_mode)
7474         reg_values[REGNO (dest)]
7475           = mips16e_collect_propagate_value (src, reg_values);
7476       else
7477         break;
7478     }
7479   pop_topmost_sequence ();
7480
7481   return nargs;
7482 }
7483
7484 /* Expand the prologue into a bunch of separate insns.  */
7485
7486 void
7487 mips_expand_prologue (void)
7488 {
7489   HOST_WIDE_INT size;
7490   unsigned int nargs;
7491   rtx insn;
7492
7493   if (cfun->machine->global_pointer > 0)
7494     SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
7495
7496   size = compute_frame_size (get_frame_size ());
7497
7498   /* Save the registers.  Allocate up to MIPS_MAX_FIRST_STACK_STEP
7499      bytes beforehand; this is enough to cover the register save area
7500      without going out of range.  */
7501   if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
7502     {
7503       HOST_WIDE_INT step1;
7504
7505       step1 = MIN (size, MIPS_MAX_FIRST_STACK_STEP);
7506
7507       if (GENERATE_MIPS16E_SAVE_RESTORE)
7508         {
7509           HOST_WIDE_INT offset;
7510           unsigned int mask, regno;
7511
7512           /* Try to merge argument stores into the save instruction.  */
7513           nargs = mips16e_collect_argument_saves ();
7514
7515           /* Build the save instruction.  */
7516           mask = cfun->machine->frame.mask;
7517           insn = mips16e_build_save_restore (false, &mask, &offset,
7518                                              nargs, step1);
7519           RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
7520           size -= step1;
7521
7522           /* Check if we need to save other registers.  */
7523           for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
7524             if (BITSET_P (mask, regno - GP_REG_FIRST))
7525               {
7526                 offset -= GET_MODE_SIZE (gpr_mode);
7527                 mips_save_restore_reg (gpr_mode, regno, offset, mips_save_reg);
7528               }
7529         }
7530       else
7531         {
7532           insn = gen_add3_insn (stack_pointer_rtx,
7533                                 stack_pointer_rtx,
7534                                 GEN_INT (-step1));
7535           RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
7536           size -= step1;
7537           mips_for_each_saved_reg (size, mips_save_reg);
7538         }
7539     }
7540
7541   /* Allocate the rest of the frame.  */
7542   if (size > 0)
7543     {
7544       if (SMALL_OPERAND (-size))
7545         RTX_FRAME_RELATED_P (emit_insn (gen_add3_insn (stack_pointer_rtx,
7546                                                        stack_pointer_rtx,
7547                                                        GEN_INT (-size)))) = 1;
7548       else
7549         {
7550           emit_move_insn (MIPS_PROLOGUE_TEMP (Pmode), GEN_INT (size));
7551           if (TARGET_MIPS16)
7552             {
7553               /* There are no instructions to add or subtract registers
7554                  from the stack pointer, so use the frame pointer as a
7555                  temporary.  We should always be using a frame pointer
7556                  in this case anyway.  */
7557               gcc_assert (frame_pointer_needed);
7558               emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
7559               emit_insn (gen_sub3_insn (hard_frame_pointer_rtx,
7560                                         hard_frame_pointer_rtx,
7561                                         MIPS_PROLOGUE_TEMP (Pmode)));
7562               emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
7563             }
7564           else
7565             emit_insn (gen_sub3_insn (stack_pointer_rtx,
7566                                       stack_pointer_rtx,
7567                                       MIPS_PROLOGUE_TEMP (Pmode)));
7568
7569           /* Describe the combined effect of the previous instructions.  */
7570           mips_set_frame_expr
7571             (gen_rtx_SET (VOIDmode, stack_pointer_rtx,
7572                           plus_constant (stack_pointer_rtx, -size)));
7573         }
7574     }
7575
7576   /* Set up the frame pointer, if we're using one.  In mips16 code,
7577      we point the frame pointer ahead of the outgoing argument area.
7578      This should allow more variables & incoming arguments to be
7579      accessed with unextended instructions.  */
7580   if (frame_pointer_needed)
7581     {
7582       if (TARGET_MIPS16 && cfun->machine->frame.args_size != 0)
7583         {
7584           rtx offset = GEN_INT (cfun->machine->frame.args_size);
7585           if (SMALL_OPERAND (cfun->machine->frame.args_size))
7586             RTX_FRAME_RELATED_P
7587               (emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
7588                                          stack_pointer_rtx,
7589                                          offset))) = 1;
7590           else
7591             {
7592               emit_move_insn (MIPS_PROLOGUE_TEMP (Pmode), offset);
7593               emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
7594               emit_insn (gen_add3_insn (hard_frame_pointer_rtx,
7595                                         hard_frame_pointer_rtx,
7596                                         MIPS_PROLOGUE_TEMP (Pmode)));
7597               mips_set_frame_expr
7598                 (gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
7599                               plus_constant (stack_pointer_rtx,
7600                                              cfun->machine->frame.args_size)));
7601             }
7602         }
7603       else
7604         RTX_FRAME_RELATED_P (emit_move_insn (hard_frame_pointer_rtx,
7605                                              stack_pointer_rtx)) = 1;
7606     }
7607
7608   mips_emit_loadgp ();
7609
7610   /* If generating o32/o64 abicalls, save $gp on the stack.  */
7611   if (TARGET_ABICALLS && TARGET_OLDABI && !current_function_is_leaf)
7612     emit_insn (gen_cprestore (GEN_INT (current_function_outgoing_args_size)));
7613
7614   /* If we are profiling, make sure no instructions are scheduled before
7615      the call to mcount.  */
7616
7617   if (current_function_profile)
7618     emit_insn (gen_blockage ());
7619 }
7620 \f
7621 /* Do any necessary cleanup after a function to restore stack, frame,
7622    and regs.  */
7623
7624 #define RA_MASK BITMASK_HIGH    /* 1 << 31 */
7625
7626 static void
7627 mips_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
7628                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
7629 {
7630   /* Reinstate the normal $gp.  */
7631   SET_REGNO (pic_offset_table_rtx, GLOBAL_POINTER_REGNUM);
7632   mips_output_cplocal ();
7633
7634   if (cfun->machine->all_noreorder_p)
7635     {
7636       /* Avoid using %>%) since it adds excess whitespace.  */
7637       output_asm_insn (".set\tmacro", 0);
7638       output_asm_insn (".set\treorder", 0);
7639       set_noreorder = set_nomacro = 0;
7640     }
7641
7642   if (!FUNCTION_NAME_ALREADY_DECLARED && !flag_inhibit_size_directive)
7643     {
7644       const char *fnname;
7645
7646       /* Get the function name the same way that toplev.c does before calling
7647          assemble_start_function.  This is needed so that the name used here
7648          exactly matches the name used in ASM_DECLARE_FUNCTION_NAME.  */
7649       fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
7650       fputs ("\t.end\t", file);
7651       assemble_name (file, fnname);
7652       fputs ("\n", file);
7653     }
7654 }
7655 \f
7656 /* Emit instructions to restore register REG from slot MEM.  */
7657
7658 static void
7659 mips_restore_reg (rtx reg, rtx mem)
7660 {
7661   /* There's no mips16 instruction to load $31 directly.  Load into
7662      $7 instead and adjust the return insn appropriately.  */
7663   if (TARGET_MIPS16 && REGNO (reg) == GP_REG_FIRST + 31)
7664     reg = gen_rtx_REG (GET_MODE (reg), 7);
7665
7666   if (TARGET_MIPS16 && !M16_REG_P (REGNO (reg)))
7667     {
7668       /* Can't restore directly; move through a temporary.  */
7669       emit_move_insn (MIPS_EPILOGUE_TEMP (GET_MODE (reg)), mem);
7670       emit_move_insn (reg, MIPS_EPILOGUE_TEMP (GET_MODE (reg)));
7671     }
7672   else
7673     emit_move_insn (reg, mem);
7674 }
7675
7676
7677 /* Expand the epilogue into a bunch of separate insns.  SIBCALL_P is true
7678    if this epilogue precedes a sibling call, false if it is for a normal
7679    "epilogue" pattern.  */
7680
7681 void
7682 mips_expand_epilogue (int sibcall_p)
7683 {
7684   HOST_WIDE_INT step1, step2;
7685   rtx base, target;
7686
7687   if (!sibcall_p && mips_can_use_return_insn ())
7688     {
7689       emit_jump_insn (gen_return ());
7690       return;
7691     }
7692   
7693   /* In mips16 mode, if the return value should go into a floating-point
7694      register, we need to call a helper routine to copy it over.  */
7695   if (mips16_cfun_returns_in_fpr_p ())
7696     {
7697       char *name;
7698       rtx func;
7699       rtx insn;
7700       rtx retval;
7701       rtx call;
7702       tree id;
7703       tree return_type;
7704       enum machine_mode return_mode;
7705
7706       return_type = DECL_RESULT (current_function_decl);
7707       return_mode = DECL_MODE (return_type);
7708
7709       name = ACONCAT (("__mips16_ret_",
7710                        mips16_call_stub_mode_suffix (return_mode),
7711                        NULL));
7712       id = get_identifier (name);
7713       func = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
7714       retval = gen_rtx_REG (return_mode, GP_RETURN);
7715       call = gen_call_value_internal (retval, func, const0_rtx);
7716       insn = emit_call_insn (call);
7717       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), retval);
7718     }
7719
7720   /* Split the frame into two.  STEP1 is the amount of stack we should
7721      deallocate before restoring the registers.  STEP2 is the amount we
7722      should deallocate afterwards.
7723
7724      Start off by assuming that no registers need to be restored.  */
7725   step1 = cfun->machine->frame.total_size;
7726   step2 = 0;
7727
7728   /* Work out which register holds the frame address.  Account for the
7729      frame pointer offset used by mips16 code.  */
7730   if (!frame_pointer_needed)
7731     base = stack_pointer_rtx;
7732   else
7733     {
7734       base = hard_frame_pointer_rtx;
7735       if (TARGET_MIPS16)
7736         step1 -= cfun->machine->frame.args_size;
7737     }
7738
7739   /* If we need to restore registers, deallocate as much stack as
7740      possible in the second step without going out of range.  */
7741   if ((cfun->machine->frame.mask | cfun->machine->frame.fmask) != 0)
7742     {
7743       step2 = MIN (step1, MIPS_MAX_FIRST_STACK_STEP);
7744       step1 -= step2;
7745     }
7746
7747   /* Set TARGET to BASE + STEP1.  */
7748   target = base;
7749   if (step1 > 0)
7750     {
7751       rtx adjust;
7752
7753       /* Get an rtx for STEP1 that we can add to BASE.  */
7754       adjust = GEN_INT (step1);
7755       if (!SMALL_OPERAND (step1))
7756         {
7757           emit_move_insn (MIPS_EPILOGUE_TEMP (Pmode), adjust);
7758           adjust = MIPS_EPILOGUE_TEMP (Pmode);
7759         }
7760
7761       /* Normal mode code can copy the result straight into $sp.  */
7762       if (!TARGET_MIPS16)
7763         target = stack_pointer_rtx;
7764
7765       emit_insn (gen_add3_insn (target, base, adjust));
7766     }
7767
7768   /* Copy TARGET into the stack pointer.  */
7769   if (target != stack_pointer_rtx)
7770     emit_move_insn (stack_pointer_rtx, target);
7771
7772   /* If we're using addressing macros, $gp is implicitly used by all
7773      SYMBOL_REFs.  We must emit a blockage insn before restoring $gp
7774      from the stack.  */
7775   if (TARGET_CALL_SAVED_GP && !TARGET_EXPLICIT_RELOCS)
7776     emit_insn (gen_blockage ());
7777
7778   if (GENERATE_MIPS16E_SAVE_RESTORE && cfun->machine->frame.mask != 0)
7779     {
7780       unsigned int regno, mask;
7781       HOST_WIDE_INT offset;
7782       rtx restore;
7783
7784       /* Generate the restore instruction.  */
7785       mask = cfun->machine->frame.mask;
7786       restore = mips16e_build_save_restore (true, &mask, &offset, 0, step2);
7787
7788       /* Restore any other registers manually.  */
7789       for (regno = GP_REG_FIRST; regno < GP_REG_LAST; regno++)
7790         if (BITSET_P (mask, regno - GP_REG_FIRST))
7791           {
7792             offset -= GET_MODE_SIZE (gpr_mode);
7793             mips_save_restore_reg (gpr_mode, regno, offset, mips_restore_reg);
7794           }
7795
7796       /* Restore the remaining registers and deallocate the final bit
7797          of the frame.  */
7798       emit_insn (restore);
7799     }
7800   else
7801     {
7802       /* Restore the registers.  */
7803       mips_for_each_saved_reg (cfun->machine->frame.total_size - step2,
7804                                mips_restore_reg);
7805
7806       /* Deallocate the final bit of the frame.  */
7807       if (step2 > 0)
7808         emit_insn (gen_add3_insn (stack_pointer_rtx,
7809                                   stack_pointer_rtx,
7810                                   GEN_INT (step2)));
7811     }
7812
7813   /* Add in the __builtin_eh_return stack adjustment.  We need to
7814      use a temporary in mips16 code.  */
7815   if (current_function_calls_eh_return)
7816     {
7817       if (TARGET_MIPS16)
7818         {
7819           emit_move_insn (MIPS_EPILOGUE_TEMP (Pmode), stack_pointer_rtx);
7820           emit_insn (gen_add3_insn (MIPS_EPILOGUE_TEMP (Pmode),
7821                                     MIPS_EPILOGUE_TEMP (Pmode),
7822                                     EH_RETURN_STACKADJ_RTX));
7823           emit_move_insn (stack_pointer_rtx, MIPS_EPILOGUE_TEMP (Pmode));
7824         }
7825       else
7826         emit_insn (gen_add3_insn (stack_pointer_rtx,
7827                                   stack_pointer_rtx,
7828                                   EH_RETURN_STACKADJ_RTX));
7829     }
7830
7831   if (!sibcall_p)
7832     {
7833       /* When generating MIPS16 code, the normal mips_for_each_saved_reg
7834          path will restore the return address into $7 rather than $31.  */
7835       if (TARGET_MIPS16
7836           && !GENERATE_MIPS16E_SAVE_RESTORE
7837           && (cfun->machine->frame.mask & RA_MASK) != 0)
7838         emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
7839                                                           GP_REG_FIRST + 7)));
7840       else
7841         emit_jump_insn (gen_return_internal (gen_rtx_REG (Pmode,
7842                                                           GP_REG_FIRST + 31)));
7843     }
7844 }
7845 \f
7846 /* Return nonzero if this function is known to have a null epilogue.
7847    This allows the optimizer to omit jumps to jumps if no stack
7848    was created.  */
7849
7850 int
7851 mips_can_use_return_insn (void)
7852 {
7853   if (! reload_completed)
7854     return 0;
7855
7856   if (df_regs_ever_live_p (31) || current_function_profile)
7857     return 0;
7858
7859   /* In mips16 mode, a function that returns a floating point value
7860      needs to arrange to copy the return value into the floating point
7861      registers.  */
7862   if (mips16_cfun_returns_in_fpr_p ())
7863     return 0;
7864
7865   if (cfun->machine->frame.initialized)
7866     return cfun->machine->frame.total_size == 0;
7867
7868   return compute_frame_size (get_frame_size ()) == 0;
7869 }
7870 \f
7871 /* Implement TARGET_ASM_OUTPUT_MI_THUNK.  Generate rtl rather than asm text
7872    in order to avoid duplicating too much logic from elsewhere.  */
7873
7874 static void
7875 mips_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
7876                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
7877                       tree function)
7878 {
7879   rtx this, temp1, temp2, insn, fnaddr;
7880
7881   /* Pretend to be a post-reload pass while generating rtl.  */
7882   no_new_pseudos = 1;
7883   reload_completed = 1;
7884
7885   /* Mark the end of the (empty) prologue.  */
7886   emit_note (NOTE_INSN_PROLOGUE_END);
7887
7888   /* Pick a global pointer.  Use a call-clobbered register if
7889      TARGET_CALL_SAVED_GP, so that we can use a sibcall.  */
7890   if (TARGET_USE_GOT)
7891     {
7892       cfun->machine->global_pointer =
7893         TARGET_CALL_SAVED_GP ? 15 : GLOBAL_POINTER_REGNUM;
7894
7895       SET_REGNO (pic_offset_table_rtx, cfun->machine->global_pointer);
7896
7897     }
7898
7899   /* Set up the global pointer for n32 or n64 abicalls.  If
7900      LOADGP_ABSOLUTE then the thunk does not use the gp and there is
7901      no need to load it.*/
7902   if (mips_current_loadgp_style () != LOADGP_ABSOLUTE
7903       || !targetm.binds_local_p (function))
7904     mips_emit_loadgp ();
7905
7906   /* We need two temporary registers in some cases.  */
7907   temp1 = gen_rtx_REG (Pmode, 2);
7908   temp2 = gen_rtx_REG (Pmode, 3);
7909
7910   /* Find out which register contains the "this" pointer.  */
7911   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
7912     this = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
7913   else
7914     this = gen_rtx_REG (Pmode, GP_ARG_FIRST);
7915
7916   /* Add DELTA to THIS.  */
7917   if (delta != 0)
7918     {
7919       rtx offset = GEN_INT (delta);
7920       if (!SMALL_OPERAND (delta))
7921         {
7922           emit_move_insn (temp1, offset);
7923           offset = temp1;
7924         }
7925       emit_insn (gen_add3_insn (this, this, offset));
7926     }
7927
7928   /* If needed, add *(*THIS + VCALL_OFFSET) to THIS.  */
7929   if (vcall_offset != 0)
7930     {
7931       rtx addr;
7932
7933       /* Set TEMP1 to *THIS.  */
7934       emit_move_insn (temp1, gen_rtx_MEM (Pmode, this));
7935
7936       /* Set ADDR to a legitimate address for *THIS + VCALL_OFFSET.  */
7937       addr = mips_add_offset (temp2, temp1, vcall_offset);
7938
7939       /* Load the offset and add it to THIS.  */
7940       emit_move_insn (temp1, gen_rtx_MEM (Pmode, addr));
7941       emit_insn (gen_add3_insn (this, this, temp1));
7942     }
7943
7944   /* Jump to the target function.  Use a sibcall if direct jumps are
7945      allowed, otherwise load the address into a register first.  */
7946   fnaddr = XEXP (DECL_RTL (function), 0);
7947   if (TARGET_MIPS16 || TARGET_USE_GOT || SYMBOL_REF_LONG_CALL_P (fnaddr))
7948     {
7949       /* This is messy.  gas treats "la $25,foo" as part of a call
7950          sequence and may allow a global "foo" to be lazily bound.
7951          The general move patterns therefore reject this combination.
7952
7953          In this context, lazy binding would actually be OK
7954          for TARGET_CALL_CLOBBERED_GP, but it's still wrong for
7955          TARGET_CALL_SAVED_GP; see mips_load_call_address.
7956          We must therefore load the address via a temporary
7957          register if mips_dangerous_for_la25_p.
7958
7959          If we jump to the temporary register rather than $25, the assembler
7960          can use the move insn to fill the jump's delay slot.  */
7961       if (TARGET_USE_PIC_FN_ADDR_REG
7962           && !mips_dangerous_for_la25_p (fnaddr))
7963         temp1 = gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM);
7964       mips_load_call_address (temp1, fnaddr, true);
7965
7966       if (TARGET_USE_PIC_FN_ADDR_REG
7967           && REGNO (temp1) != PIC_FUNCTION_ADDR_REGNUM)
7968         emit_move_insn (gen_rtx_REG (Pmode, PIC_FUNCTION_ADDR_REGNUM), temp1);
7969       emit_jump_insn (gen_indirect_jump (temp1));
7970     }
7971   else
7972     {
7973       insn = emit_call_insn (gen_sibcall_internal (fnaddr, const0_rtx));
7974       SIBLING_CALL_P (insn) = 1;
7975     }
7976
7977   /* Run just enough of rest_of_compilation.  This sequence was
7978      "borrowed" from alpha.c.  */
7979   insn = get_insns ();
7980   insn_locators_alloc ();
7981   split_all_insns_noflow ();
7982   if (TARGET_MIPS16)
7983     mips16_lay_out_constants ();
7984   shorten_branches (insn);
7985   final_start_function (insn, file, 1);
7986   final (insn, file, 1);
7987   final_end_function ();
7988
7989   /* Clean up the vars set above.  Note that final_end_function resets
7990      the global pointer for us.  */
7991   reload_completed = 0;
7992   no_new_pseudos = 0;
7993 }
7994 \f
7995 /* Returns nonzero if X contains a SYMBOL_REF.  */
7996
7997 static int
7998 symbolic_expression_p (rtx x)
7999 {
8000   if (GET_CODE (x) == SYMBOL_REF)
8001     return 1;
8002
8003   if (GET_CODE (x) == CONST)
8004     return symbolic_expression_p (XEXP (x, 0));
8005
8006   if (UNARY_P (x))
8007     return symbolic_expression_p (XEXP (x, 0));
8008
8009   if (ARITHMETIC_P (x))
8010     return (symbolic_expression_p (XEXP (x, 0))
8011             || symbolic_expression_p (XEXP (x, 1)));
8012
8013   return 0;
8014 }
8015
8016 /* Choose the section to use for the constant rtx expression X that has
8017    mode MODE.  */
8018
8019 static section *
8020 mips_select_rtx_section (enum machine_mode mode, rtx x,
8021                          unsigned HOST_WIDE_INT align)
8022 {
8023   if (TARGET_MIPS16)
8024     {
8025       /* In mips16 mode, the constant table always goes in the same section
8026          as the function, so that constants can be loaded using PC relative
8027          addressing.  */
8028       return function_section (current_function_decl);
8029     }
8030   else if (TARGET_EMBEDDED_DATA)
8031     {
8032       /* For embedded applications, always put constants in read-only data,
8033          in order to reduce RAM usage.  */
8034       return mergeable_constant_section (mode, align, 0);
8035     }
8036   else
8037     {
8038       /* For hosted applications, always put constants in small data if
8039          possible, as this gives the best performance.  */
8040       /* ??? Consider using mergeable small data sections.  */
8041
8042       if (GET_MODE_SIZE (mode) <= (unsigned) mips_section_threshold
8043           && mips_section_threshold > 0)
8044         return get_named_section (NULL, ".sdata", 0);
8045       else if (flag_pic && symbolic_expression_p (x))
8046         return get_named_section (NULL, ".data.rel.ro", 3);
8047       else
8048         return mergeable_constant_section (mode, align, 0);
8049     }
8050 }
8051
8052 /* Implement TARGET_ASM_FUNCTION_RODATA_SECTION.
8053
8054    The complication here is that, with the combination TARGET_ABICALLS
8055    && !TARGET_GPWORD, jump tables will use absolute addresses, and should
8056    therefore not be included in the read-only part of a DSO.  Handle such
8057    cases by selecting a normal data section instead of a read-only one.
8058    The logic apes that in default_function_rodata_section.  */
8059
8060 static section *
8061 mips_function_rodata_section (tree decl)
8062 {
8063   if (!TARGET_ABICALLS || TARGET_GPWORD)
8064     return default_function_rodata_section (decl);
8065
8066   if (decl && DECL_SECTION_NAME (decl))
8067     {
8068       const char *name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
8069       if (DECL_ONE_ONLY (decl) && strncmp (name, ".gnu.linkonce.t.", 16) == 0)
8070         {
8071           char *rname = ASTRDUP (name);
8072           rname[14] = 'd';
8073           return get_section (rname, SECTION_LINKONCE | SECTION_WRITE, decl);
8074         }
8075       else if (flag_function_sections && flag_data_sections
8076                && strncmp (name, ".text.", 6) == 0)
8077         {
8078           char *rname = ASTRDUP (name);
8079           memcpy (rname + 1, "data", 4);
8080           return get_section (rname, SECTION_WRITE, decl);
8081         }
8082     }
8083   return data_section;
8084 }
8085
8086 /* Implement TARGET_IN_SMALL_DATA_P.  This function controls whether
8087    locally-defined objects go in a small data section.  It also controls
8088    the setting of the SYMBOL_REF_SMALL_P flag, which in turn helps
8089    mips_classify_symbol decide when to use %gp_rel(...)($gp) accesses.  */
8090
8091 static bool
8092 mips_in_small_data_p (tree decl)
8093 {
8094   HOST_WIDE_INT size;
8095
8096   if (TREE_CODE (decl) == STRING_CST || TREE_CODE (decl) == FUNCTION_DECL)
8097     return false;
8098
8099   /* We don't yet generate small-data references for -mabicalls or
8100      VxWorks RTP code.  See the related -G handling in override_options.  */
8101   if (TARGET_ABICALLS || TARGET_VXWORKS_RTP)
8102     return false;
8103
8104   if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl) != 0)
8105     {
8106       const char *name;
8107
8108       /* Reject anything that isn't in a known small-data section.  */
8109       name = TREE_STRING_POINTER (DECL_SECTION_NAME (decl));
8110       if (strcmp (name, ".sdata") != 0 && strcmp (name, ".sbss") != 0)
8111         return false;
8112
8113       /* If a symbol is defined externally, the assembler will use the
8114          usual -G rules when deciding how to implement macros.  */
8115       if (TARGET_EXPLICIT_RELOCS || !DECL_EXTERNAL (decl))
8116         return true;
8117     }
8118   else if (TARGET_EMBEDDED_DATA)
8119     {
8120       /* Don't put constants into the small data section: we want them
8121          to be in ROM rather than RAM.  */
8122       if (TREE_CODE (decl) != VAR_DECL)
8123         return false;
8124
8125       if (TREE_READONLY (decl)
8126           && !TREE_SIDE_EFFECTS (decl)
8127           && (!DECL_INITIAL (decl) || TREE_CONSTANT (DECL_INITIAL (decl))))
8128         return false;
8129     }
8130
8131   size = int_size_in_bytes (TREE_TYPE (decl));
8132   return (size > 0 && size <= mips_section_threshold);
8133 }
8134
8135 /* Implement TARGET_USE_ANCHORS_FOR_SYMBOL_P.  We don't want to use
8136    anchors for small data: the GP register acts as an anchor in that
8137    case.  We also don't want to use them for PC-relative accesses,
8138    where the PC acts as an anchor.  */
8139
8140 static bool
8141 mips_use_anchors_for_symbol_p (rtx symbol)
8142 {
8143   switch (mips_classify_symbol (symbol))
8144     {
8145     case SYMBOL_CONSTANT_POOL:
8146     case SYMBOL_SMALL_DATA:
8147       return false;
8148
8149     default:
8150       return true;
8151     }
8152 }
8153 \f
8154 /* See whether VALTYPE is a record whose fields should be returned in
8155    floating-point registers.  If so, return the number of fields and
8156    list them in FIELDS (which should have two elements).  Return 0
8157    otherwise.
8158
8159    For n32 & n64, a structure with one or two fields is returned in
8160    floating-point registers as long as every field has a floating-point
8161    type.  */
8162
8163 static int
8164 mips_fpr_return_fields (tree valtype, tree *fields)
8165 {
8166   tree field;
8167   int i;
8168
8169   if (!TARGET_NEWABI)
8170     return 0;
8171
8172   if (TREE_CODE (valtype) != RECORD_TYPE)
8173     return 0;
8174
8175   i = 0;
8176   for (field = TYPE_FIELDS (valtype); field != 0; field = TREE_CHAIN (field))
8177     {
8178       if (TREE_CODE (field) != FIELD_DECL)
8179         continue;
8180
8181       if (TREE_CODE (TREE_TYPE (field)) != REAL_TYPE)
8182         return 0;
8183
8184       if (i == 2)
8185         return 0;
8186
8187       fields[i++] = field;
8188     }
8189   return i;
8190 }
8191
8192
8193 /* Implement TARGET_RETURN_IN_MSB.  For n32 & n64, we should return
8194    a value in the most significant part of $2/$3 if:
8195
8196       - the target is big-endian;
8197
8198       - the value has a structure or union type (we generalize this to
8199         cover aggregates from other languages too); and
8200
8201       - the structure is not returned in floating-point registers.  */
8202
8203 static bool
8204 mips_return_in_msb (tree valtype)
8205 {
8206   tree fields[2];
8207
8208   return (TARGET_NEWABI
8209           && TARGET_BIG_ENDIAN
8210           && AGGREGATE_TYPE_P (valtype)
8211           && mips_fpr_return_fields (valtype, fields) == 0);
8212 }
8213
8214
8215 /* Return a composite value in a pair of floating-point registers.
8216    MODE1 and OFFSET1 are the mode and byte offset for the first value,
8217    likewise MODE2 and OFFSET2 for the second.  MODE is the mode of the
8218    complete value.
8219
8220    For n32 & n64, $f0 always holds the first value and $f2 the second.
8221    Otherwise the values are packed together as closely as possible.  */
8222
8223 static rtx
8224 mips_return_fpr_pair (enum machine_mode mode,
8225                       enum machine_mode mode1, HOST_WIDE_INT offset1,
8226                       enum machine_mode mode2, HOST_WIDE_INT offset2)
8227 {
8228   int inc;
8229
8230   inc = (TARGET_NEWABI ? 2 : MAX_FPRS_PER_FMT);
8231   return gen_rtx_PARALLEL
8232     (mode,
8233      gen_rtvec (2,
8234                 gen_rtx_EXPR_LIST (VOIDmode,
8235                                    gen_rtx_REG (mode1, FP_RETURN),
8236                                    GEN_INT (offset1)),
8237                 gen_rtx_EXPR_LIST (VOIDmode,
8238                                    gen_rtx_REG (mode2, FP_RETURN + inc),
8239                                    GEN_INT (offset2))));
8240
8241 }
8242
8243
8244 /* Implement FUNCTION_VALUE and LIBCALL_VALUE.  For normal calls,
8245    VALTYPE is the return type and MODE is VOIDmode.  For libcalls,
8246    VALTYPE is null and MODE is the mode of the return value.  */
8247
8248 rtx
8249 mips_function_value (tree valtype, tree func ATTRIBUTE_UNUSED,
8250                      enum machine_mode mode)
8251 {
8252   if (valtype)
8253     {
8254       tree fields[2];
8255       int unsignedp;
8256
8257       mode = TYPE_MODE (valtype);
8258       unsignedp = TYPE_UNSIGNED (valtype);
8259
8260       /* Since we define TARGET_PROMOTE_FUNCTION_RETURN that returns
8261          true, we must promote the mode just as PROMOTE_MODE does.  */
8262       mode = promote_mode (valtype, mode, &unsignedp, 1);
8263
8264       /* Handle structures whose fields are returned in $f0/$f2.  */
8265       switch (mips_fpr_return_fields (valtype, fields))
8266         {
8267         case 1:
8268           return gen_rtx_REG (mode, FP_RETURN);
8269
8270         case 2:
8271           return mips_return_fpr_pair (mode,
8272                                        TYPE_MODE (TREE_TYPE (fields[0])),
8273                                        int_byte_position (fields[0]),
8274                                        TYPE_MODE (TREE_TYPE (fields[1])),
8275                                        int_byte_position (fields[1]));
8276         }
8277
8278       /* If a value is passed in the most significant part of a register, see
8279          whether we have to round the mode up to a whole number of words.  */
8280       if (mips_return_in_msb (valtype))
8281         {
8282           HOST_WIDE_INT size = int_size_in_bytes (valtype);
8283           if (size % UNITS_PER_WORD != 0)
8284             {
8285               size += UNITS_PER_WORD - size % UNITS_PER_WORD;
8286               mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
8287             }
8288         }
8289
8290       /* For EABI, the class of return register depends entirely on MODE.
8291          For example, "struct { some_type x; }" and "union { some_type x; }"
8292          are returned in the same way as a bare "some_type" would be.
8293          Other ABIs only use FPRs for scalar, complex or vector types.  */
8294       if (mips_abi != ABI_EABI && !FLOAT_TYPE_P (valtype))
8295         return gen_rtx_REG (mode, GP_RETURN);
8296     }
8297
8298   if (!TARGET_MIPS16)
8299     {
8300       /* Handle long doubles for n32 & n64.  */
8301       if (mode == TFmode)
8302         return mips_return_fpr_pair (mode,
8303                                      DImode, 0,
8304                                      DImode, GET_MODE_SIZE (mode) / 2);
8305
8306       if (mips_return_mode_in_fpr_p (mode))
8307         {
8308           if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
8309             return mips_return_fpr_pair (mode,
8310                                          GET_MODE_INNER (mode), 0,
8311                                          GET_MODE_INNER (mode),
8312                                          GET_MODE_SIZE (mode) / 2);
8313           else
8314             return gen_rtx_REG (mode, FP_RETURN);
8315         }
8316     }
8317
8318   return gen_rtx_REG (mode, GP_RETURN);
8319 }
8320
8321 /* Return nonzero when an argument must be passed by reference.  */
8322
8323 static bool
8324 mips_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
8325                         enum machine_mode mode, tree type,
8326                         bool named ATTRIBUTE_UNUSED)
8327 {
8328   if (mips_abi == ABI_EABI)
8329     {
8330       int size;
8331
8332       /* ??? How should SCmode be handled?  */
8333       if (mode == DImode || mode == DFmode)
8334         return 0;
8335
8336       size = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode);
8337       return size == -1 || size > UNITS_PER_WORD;
8338     }
8339   else
8340     {
8341       /* If we have a variable-sized parameter, we have no choice.  */
8342       return targetm.calls.must_pass_in_stack (mode, type);
8343     }
8344 }
8345
8346 static bool
8347 mips_callee_copies (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
8348                     enum machine_mode mode ATTRIBUTE_UNUSED,
8349                     tree type ATTRIBUTE_UNUSED, bool named)
8350 {
8351   return mips_abi == ABI_EABI && named;
8352 }
8353
8354 /* Return true if registers of class CLASS cannot change from mode FROM
8355    to mode TO.  */
8356
8357 bool
8358 mips_cannot_change_mode_class (enum machine_mode from,
8359                                enum machine_mode to, enum reg_class class)
8360 {
8361   if (MIN (GET_MODE_SIZE (from), GET_MODE_SIZE (to)) <= UNITS_PER_WORD
8362       && MAX (GET_MODE_SIZE (from), GET_MODE_SIZE (to)) > UNITS_PER_WORD)
8363     {
8364       if (TARGET_BIG_ENDIAN)
8365         {
8366           /* When a multi-word value is stored in paired floating-point
8367              registers, the first register always holds the low word.
8368              We therefore can't allow FPRs to change between single-word
8369              and multi-word modes.  */
8370           if (MAX_FPRS_PER_FMT > 1 && reg_classes_intersect_p (FP_REGS, class))
8371             return true;
8372         }
8373       else
8374         {
8375           /* LO_REGNO == HI_REGNO + 1, so if a multi-word value is stored
8376              in LO and HI, the high word always comes first.  We therefore
8377              can't allow values stored in HI to change between single-word
8378              and multi-word modes.
8379              This rule applies to both the original HI/LO pair and the new
8380              DSP accumulators.  */
8381           if (reg_classes_intersect_p (ACC_REGS, class))
8382             return true;
8383         }
8384     }
8385
8386   /* gcc assumes that each word of a multiword register can be accessed
8387      individually using SUBREGs.  This is not true for floating-point
8388      registers if they are bigger than a word.  */
8389   if (UNITS_PER_FPREG > UNITS_PER_WORD
8390       && GET_MODE_SIZE (from) > UNITS_PER_WORD
8391       && GET_MODE_SIZE (to) < UNITS_PER_FPREG
8392       && reg_classes_intersect_p (FP_REGS, class))
8393     return true;
8394
8395   /* Loading a 32-bit value into a 64-bit floating-point register
8396      will not sign-extend the value, despite what LOAD_EXTEND_OP says.
8397      We can't allow 64-bit float registers to change from SImode to
8398      to a wider mode.  */
8399   if (TARGET_64BIT
8400       && TARGET_FLOAT64
8401       && from == SImode
8402       && GET_MODE_SIZE (to) >= UNITS_PER_WORD
8403       && reg_classes_intersect_p (FP_REGS, class))
8404     return true;
8405
8406   return false;
8407 }
8408
8409 /* Return true if X should not be moved directly into register $25.
8410    We need this because many versions of GAS will treat "la $25,foo" as
8411    part of a call sequence and so allow a global "foo" to be lazily bound.  */
8412
8413 bool
8414 mips_dangerous_for_la25_p (rtx x)
8415 {
8416   return (!TARGET_EXPLICIT_RELOCS
8417           && TARGET_USE_GOT
8418           && GET_CODE (x) == SYMBOL_REF
8419           && mips_global_symbol_p (x));
8420 }
8421
8422 /* Implement PREFERRED_RELOAD_CLASS.  */
8423
8424 enum reg_class
8425 mips_preferred_reload_class (rtx x, enum reg_class class)
8426 {
8427   if (mips_dangerous_for_la25_p (x) && reg_class_subset_p (LEA_REGS, class))
8428     return LEA_REGS;
8429
8430   if (TARGET_HARD_FLOAT
8431       && FLOAT_MODE_P (GET_MODE (x))
8432       && reg_class_subset_p (FP_REGS, class))
8433     return FP_REGS;
8434
8435   if (reg_class_subset_p (GR_REGS, class))
8436     class = GR_REGS;
8437
8438   if (TARGET_MIPS16 && reg_class_subset_p (M16_REGS, class))
8439     class = M16_REGS;
8440
8441   return class;
8442 }
8443
8444 /* This function returns the register class required for a secondary
8445    register when copying between one of the registers in CLASS, and X,
8446    using MODE.  If IN_P is nonzero, the copy is going from X to the
8447    register, otherwise the register is the source.  A return value of
8448    NO_REGS means that no secondary register is required.  */
8449
8450 enum reg_class
8451 mips_secondary_reload_class (enum reg_class class,
8452                              enum machine_mode mode, rtx x, int in_p)
8453 {
8454   enum reg_class gr_regs = TARGET_MIPS16 ? M16_REGS : GR_REGS;
8455   int regno = -1;
8456   int gp_reg_p;
8457
8458   if (REG_P (x)|| GET_CODE (x) == SUBREG)
8459     regno = true_regnum (x);
8460
8461   gp_reg_p = TARGET_MIPS16 ? M16_REG_P (regno) : GP_REG_P (regno);
8462
8463   if (mips_dangerous_for_la25_p (x))
8464     {
8465       gr_regs = LEA_REGS;
8466       if (TEST_HARD_REG_BIT (reg_class_contents[(int) class], 25))
8467         return gr_regs;
8468     }
8469
8470   /* Copying from HI or LO to anywhere other than a general register
8471      requires a general register.
8472      This rule applies to both the original HI/LO pair and the new
8473      DSP accumulators.  */
8474   if (reg_class_subset_p (class, ACC_REGS))
8475     {
8476       if (TARGET_MIPS16 && in_p)
8477         {
8478           /* We can't really copy to HI or LO at all in mips16 mode.  */
8479           return M16_REGS;
8480         }
8481       return gp_reg_p ? NO_REGS : gr_regs;
8482     }
8483   if (ACC_REG_P (regno))
8484     {
8485       if (TARGET_MIPS16 && ! in_p)
8486         {
8487           /* We can't really copy to HI or LO at all in mips16 mode.  */
8488           return M16_REGS;
8489         }
8490       return class == gr_regs ? NO_REGS : gr_regs;
8491     }
8492
8493   /* We can only copy a value to a condition code register from a
8494      floating point register, and even then we require a scratch
8495      floating point register.  We can only copy a value out of a
8496      condition code register into a general register.  */
8497   if (class == ST_REGS)
8498     {
8499       if (in_p)
8500         return FP_REGS;
8501       return gp_reg_p ? NO_REGS : gr_regs;
8502     }
8503   if (ST_REG_P (regno))
8504     {
8505       if (! in_p)
8506         return FP_REGS;
8507       return class == gr_regs ? NO_REGS : gr_regs;
8508     }
8509
8510   if (class == FP_REGS)
8511     {
8512       if (MEM_P (x))
8513         {
8514           /* In this case we can use lwc1, swc1, ldc1 or sdc1.  */
8515           return NO_REGS;
8516         }
8517       else if (CONSTANT_P (x) && GET_MODE_CLASS (mode) == MODE_FLOAT)
8518         {
8519           /* We can use the l.s and l.d macros to load floating-point
8520              constants.  ??? For l.s, we could probably get better
8521              code by returning GR_REGS here.  */
8522           return NO_REGS;
8523         }
8524       else if (gp_reg_p || x == CONST0_RTX (mode))
8525         {
8526           /* In this case we can use mtc1, mfc1, dmtc1 or dmfc1.  */
8527           return NO_REGS;
8528         }
8529       else if (FP_REG_P (regno))
8530         {
8531           /* In this case we can use mov.s or mov.d.  */
8532           return NO_REGS;
8533         }
8534       else
8535         {
8536           /* Otherwise, we need to reload through an integer register.  */
8537           return gr_regs;
8538         }
8539     }
8540
8541   /* In mips16 mode, going between memory and anything but M16_REGS
8542      requires an M16_REG.  */
8543   if (TARGET_MIPS16)
8544     {
8545       if (class != M16_REGS && class != M16_NA_REGS)
8546         {
8547           if (gp_reg_p)
8548             return NO_REGS;
8549           return M16_REGS;
8550         }
8551       if (! gp_reg_p)
8552         {
8553           if (class == M16_REGS || class == M16_NA_REGS)
8554             return NO_REGS;
8555           return M16_REGS;
8556         }
8557     }
8558
8559   return NO_REGS;
8560 }
8561
8562 /* Implement CLASS_MAX_NREGS.
8563
8564    - UNITS_PER_FPREG controls the number of registers needed by FP_REGS.
8565
8566    - ST_REGS are always hold CCmode values, and CCmode values are
8567      considered to be 4 bytes wide.
8568
8569    All other register classes are covered by UNITS_PER_WORD.  Note that
8570    this is true even for unions of integer and float registers when the
8571    latter are smaller than the former.  The only supported combination
8572    in which case this occurs is -mgp64 -msingle-float, which has 64-bit
8573    words but 32-bit float registers.  A word-based calculation is correct
8574    in that case since -msingle-float disallows multi-FPR values.  */
8575
8576 int
8577 mips_class_max_nregs (enum reg_class class ATTRIBUTE_UNUSED,
8578                       enum machine_mode mode)
8579 {
8580   if (class == ST_REGS)
8581     return (GET_MODE_SIZE (mode) + 3) / 4;
8582   else if (class == FP_REGS)
8583     return (GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG;
8584   else
8585     return (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
8586 }
8587
8588 static bool
8589 mips_valid_pointer_mode (enum machine_mode mode)
8590 {
8591   return (mode == SImode || (TARGET_64BIT && mode == DImode));
8592 }
8593
8594 /* Target hook for vector_mode_supported_p.  */
8595
8596 static bool
8597 mips_vector_mode_supported_p (enum machine_mode mode)
8598 {
8599   switch (mode)
8600     {
8601     case V2SFmode:
8602       return TARGET_PAIRED_SINGLE_FLOAT;
8603
8604     case V2HImode:
8605     case V4QImode:
8606       return TARGET_DSP;
8607
8608     default:
8609       return false;
8610     }
8611 }
8612 \f
8613 /* If we can access small data directly (using gp-relative relocation
8614    operators) return the small data pointer, otherwise return null.
8615
8616    For each mips16 function which refers to GP relative symbols, we
8617    use a pseudo register, initialized at the start of the function, to
8618    hold the $gp value.  */
8619
8620 static rtx
8621 mips16_gp_pseudo_reg (void)
8622 {
8623   if (cfun->machine->mips16_gp_pseudo_rtx == NULL_RTX)
8624     {
8625       rtx insn, scan;
8626
8627       cfun->machine->mips16_gp_pseudo_rtx = gen_reg_rtx (Pmode);
8628
8629       /* We want to initialize this to a value which gcc will believe
8630          is constant.  */
8631       insn = gen_load_const_gp (cfun->machine->mips16_gp_pseudo_rtx);
8632
8633       push_topmost_sequence ();
8634       /* We need to emit the initialization after the FUNCTION_BEG
8635          note, so that it will be integrated.  */
8636       for (scan = get_insns (); scan != NULL_RTX; scan = NEXT_INSN (scan))
8637         if (NOTE_P (scan)
8638             && NOTE_KIND (scan) == NOTE_INSN_FUNCTION_BEG)
8639           break;
8640       if (scan == NULL_RTX)
8641         scan = get_insns ();
8642       insn = emit_insn_after (insn, scan);
8643       pop_topmost_sequence ();
8644     }
8645
8646   return cfun->machine->mips16_gp_pseudo_rtx;
8647 }
8648
8649 /* Write out code to move floating point arguments in or out of
8650    general registers.  Output the instructions to FILE.  FP_CODE is
8651    the code describing which arguments are present (see the comment at
8652    the definition of CUMULATIVE_ARGS in mips.h).  FROM_FP_P is nonzero if
8653    we are copying from the floating point registers.  */
8654
8655 static void
8656 mips16_fp_args (FILE *file, int fp_code, int from_fp_p)
8657 {
8658   const char *s;
8659   int gparg, fparg;
8660   unsigned int f;
8661   CUMULATIVE_ARGS cum;
8662
8663   /* This code only works for the original 32-bit ABI and the O64 ABI.  */
8664   gcc_assert (TARGET_OLDABI);
8665
8666   if (from_fp_p)
8667     s = "mfc1";
8668   else
8669     s = "mtc1";
8670
8671   init_cumulative_args (&cum, NULL, NULL);
8672
8673   for (f = (unsigned int) fp_code; f != 0; f >>= 2)
8674     {
8675       enum machine_mode mode;
8676       struct mips_arg_info info;
8677
8678       if ((f & 3) == 1)
8679         mode = SFmode;
8680       else if ((f & 3) == 2)
8681         mode = DFmode;
8682       else
8683         gcc_unreachable ();
8684
8685       mips_arg_info (&cum, mode, NULL, true, &info);
8686       gparg = mips_arg_regno (&info, false);
8687       fparg = mips_arg_regno (&info, true);
8688
8689       if (mode == SFmode)
8690         fprintf (file, "\t%s\t%s,%s\n", s,
8691                  reg_names[gparg], reg_names[fparg]);
8692       else if (TARGET_64BIT)
8693         fprintf (file, "\td%s\t%s,%s\n", s,
8694                  reg_names[gparg], reg_names[fparg]);
8695       else if (ISA_HAS_MXHC1)
8696         /* -mips32r2 -mfp64 */
8697         fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", 
8698                  s,
8699                  reg_names[gparg + (WORDS_BIG_ENDIAN ? 1 : 0)],
8700                  reg_names[fparg],
8701                  from_fp_p ? "mfhc1" : "mthc1",
8702                  reg_names[gparg + (WORDS_BIG_ENDIAN ? 0 : 1)],
8703                  reg_names[fparg]);
8704       else if (TARGET_BIG_ENDIAN)
8705         fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
8706                  reg_names[gparg], reg_names[fparg + 1], s,
8707                  reg_names[gparg + 1], reg_names[fparg]);
8708       else
8709         fprintf (file, "\t%s\t%s,%s\n\t%s\t%s,%s\n", s,
8710                  reg_names[gparg], reg_names[fparg], s,
8711                  reg_names[gparg + 1], reg_names[fparg + 1]);
8712
8713       function_arg_advance (&cum, mode, NULL, true);
8714     }
8715 }
8716
8717 /* Build a mips16 function stub.  This is used for functions which
8718    take arguments in the floating point registers.  It is 32-bit code
8719    that moves the floating point args into the general registers, and
8720    then jumps to the 16-bit code.  */
8721
8722 static void
8723 build_mips16_function_stub (FILE *file)
8724 {
8725   const char *fnname;
8726   char *secname, *stubname;
8727   tree stubid, stubdecl;
8728   int need_comma;
8729   unsigned int f;
8730
8731   fnname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
8732   secname = (char *) alloca (strlen (fnname) + 20);
8733   sprintf (secname, ".mips16.fn.%s", fnname);
8734   stubname = (char *) alloca (strlen (fnname) + 20);
8735   sprintf (stubname, "__fn_stub_%s", fnname);
8736   stubid = get_identifier (stubname);
8737   stubdecl = build_decl (FUNCTION_DECL, stubid,
8738                          build_function_type (void_type_node, NULL_TREE));
8739   DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
8740   DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
8741
8742   fprintf (file, "\t# Stub function for %s (", current_function_name ());
8743   need_comma = 0;
8744   for (f = (unsigned int) current_function_args_info.fp_code; f != 0; f >>= 2)
8745     {
8746       fprintf (file, "%s%s",
8747                need_comma ? ", " : "",
8748                (f & 3) == 1 ? "float" : "double");
8749       need_comma = 1;
8750     }
8751   fprintf (file, ")\n");
8752
8753   fprintf (file, "\t.set\tnomips16\n");
8754   switch_to_section (function_section (stubdecl));
8755   ASM_OUTPUT_ALIGN (file, floor_log2 (FUNCTION_BOUNDARY / BITS_PER_UNIT));
8756
8757   /* ??? If FUNCTION_NAME_ALREADY_DECLARED is defined, then we are
8758      within a .ent, and we cannot emit another .ent.  */
8759   if (!FUNCTION_NAME_ALREADY_DECLARED)
8760     {
8761       fputs ("\t.ent\t", file);
8762       assemble_name (file, stubname);
8763       fputs ("\n", file);
8764     }
8765
8766   assemble_name (file, stubname);
8767   fputs (":\n", file);
8768
8769   /* We don't want the assembler to insert any nops here.  */
8770   fprintf (file, "\t.set\tnoreorder\n");
8771
8772   mips16_fp_args (file, current_function_args_info.fp_code, 1);
8773
8774   fprintf (asm_out_file, "\t.set\tnoat\n");
8775   fprintf (asm_out_file, "\tla\t%s,", reg_names[GP_REG_FIRST + 1]);
8776   assemble_name (file, fnname);
8777   fprintf (file, "\n");
8778   fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
8779   fprintf (asm_out_file, "\t.set\tat\n");
8780
8781   /* Unfortunately, we can't fill the jump delay slot.  We can't fill
8782      with one of the mfc1 instructions, because the result is not
8783      available for one instruction, so if the very first instruction
8784      in the function refers to the register, it will see the wrong
8785      value.  */
8786   fprintf (file, "\tnop\n");
8787
8788   fprintf (file, "\t.set\treorder\n");
8789
8790   if (!FUNCTION_NAME_ALREADY_DECLARED)
8791     {
8792       fputs ("\t.end\t", file);
8793       assemble_name (file, stubname);
8794       fputs ("\n", file);
8795     }
8796
8797   fprintf (file, "\t.set\tmips16\n");
8798
8799   switch_to_section (function_section (current_function_decl));
8800 }
8801
8802 /* We keep a list of functions for which we have already built stubs
8803    in build_mips16_call_stub.  */
8804
8805 struct mips16_stub
8806 {
8807   struct mips16_stub *next;
8808   char *name;
8809   int fpret;
8810 };
8811
8812 static struct mips16_stub *mips16_stubs;
8813
8814 /* Emit code to return a double value from a mips16 stub.  GPREG is the
8815    first GP reg to use, FPREG is the first FP reg to use.  */
8816
8817 static void
8818 mips16_fpret_double (int gpreg, int fpreg)
8819 {
8820   if (TARGET_64BIT)
8821     fprintf (asm_out_file, "\tdmfc1\t%s,%s\n",
8822              reg_names[gpreg], reg_names[fpreg]);
8823   else if (TARGET_FLOAT64)
8824     {
8825       fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8826                reg_names[gpreg + WORDS_BIG_ENDIAN],
8827                reg_names[fpreg]);
8828       fprintf (asm_out_file, "\tmfhc1\t%s,%s\n",
8829                reg_names[gpreg + !WORDS_BIG_ENDIAN],
8830                reg_names[fpreg]);
8831     }
8832   else
8833     {
8834       if (TARGET_BIG_ENDIAN)
8835         {
8836           fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8837                    reg_names[gpreg + 0],
8838                    reg_names[fpreg + 1]);
8839           fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8840                    reg_names[gpreg + 1],
8841                    reg_names[fpreg + 0]);
8842         }
8843       else
8844         {
8845           fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8846                    reg_names[gpreg + 0],
8847                    reg_names[fpreg + 0]);
8848           fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
8849                    reg_names[gpreg + 1],
8850                    reg_names[fpreg + 1]);
8851         }
8852     }
8853 }
8854
8855 /* Build a call stub for a mips16 call.  A stub is needed if we are
8856    passing any floating point values which should go into the floating
8857    point registers.  If we are, and the call turns out to be to a
8858    32-bit function, the stub will be used to move the values into the
8859    floating point registers before calling the 32-bit function.  The
8860    linker will magically adjust the function call to either the 16-bit
8861    function or the 32-bit stub, depending upon where the function call
8862    is actually defined.
8863
8864    Similarly, we need a stub if the return value might come back in a
8865    floating point register.
8866
8867    RETVAL is the location of the return value, or null if this is
8868    a call rather than a call_value.  FN is the address of the
8869    function and ARG_SIZE is the size of the arguments.  FP_CODE
8870    is the code built by function_arg.  This function returns a nonzero
8871    value if it builds the call instruction itself.  */
8872
8873 int
8874 build_mips16_call_stub (rtx retval, rtx fn, rtx arg_size, int fp_code)
8875 {
8876   int fpret = 0;
8877   const char *fnname;
8878   char *secname, *stubname;
8879   struct mips16_stub *l;
8880   tree stubid, stubdecl;
8881   int need_comma;
8882   unsigned int f;
8883
8884   /* We don't need to do anything if we aren't in mips16 mode, or if
8885      we were invoked with the -msoft-float option.  */
8886   if (!mips16_hard_float)
8887     return 0;
8888
8889   /* Figure out whether the value might come back in a floating point
8890      register.  */
8891   if (retval)
8892     fpret = mips_return_mode_in_fpr_p (GET_MODE (retval));
8893
8894   /* We don't need to do anything if there were no floating point
8895      arguments and the value will not be returned in a floating point
8896      register.  */
8897   if (fp_code == 0 && ! fpret)
8898     return 0;
8899
8900   /* We don't need to do anything if this is a call to a special
8901      mips16 support function.  */
8902   if (GET_CODE (fn) == SYMBOL_REF
8903       && strncmp (XSTR (fn, 0), "__mips16_", 9) == 0)
8904     return 0;
8905
8906   /* This code will only work for o32 and o64 abis.  The other ABI's
8907      require more sophisticated support.  */
8908   gcc_assert (TARGET_OLDABI);
8909
8910   /* If we're calling via a function pointer, then we must always call
8911      via a stub.  There are magic stubs provided in libgcc.a for each
8912      of the required cases.  Each of them expects the function address
8913      to arrive in register $2.  */
8914
8915   if (GET_CODE (fn) != SYMBOL_REF)
8916     {
8917       char buf[30];
8918       tree id;
8919       rtx stub_fn, insn;
8920
8921       /* ??? If this code is modified to support other ABI's, we need
8922          to handle PARALLEL return values here.  */
8923
8924       if (fpret)
8925         sprintf (buf, "__mips16_call_stub_%s_%d",
8926                  mips16_call_stub_mode_suffix (GET_MODE (retval)),
8927                  fp_code);
8928       else
8929         sprintf (buf, "__mips16_call_stub_%d",
8930                  fp_code);
8931
8932       id = get_identifier (buf);
8933       stub_fn = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (id));
8934
8935       emit_move_insn (gen_rtx_REG (Pmode, 2), fn);
8936
8937       if (retval == NULL_RTX)
8938         insn = gen_call_internal (stub_fn, arg_size);
8939       else
8940         insn = gen_call_value_internal (retval, stub_fn, arg_size);
8941       insn = emit_call_insn (insn);
8942
8943       /* Put the register usage information on the CALL.  */
8944       CALL_INSN_FUNCTION_USAGE (insn) =
8945         gen_rtx_EXPR_LIST (VOIDmode,
8946                            gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, 2)),
8947                            CALL_INSN_FUNCTION_USAGE (insn));
8948
8949       /* If we are handling a floating point return value, we need to
8950          save $18 in the function prologue.  Putting a note on the
8951          call will mean that df_regs_ever_live_p ($18) will be true if the
8952          call is not eliminated, and we can check that in the prologue
8953          code.  */
8954       if (fpret)
8955         CALL_INSN_FUNCTION_USAGE (insn) =
8956           gen_rtx_EXPR_LIST (VOIDmode,
8957                              gen_rtx_USE (VOIDmode,
8958                                           gen_rtx_REG (word_mode, 18)),
8959                              CALL_INSN_FUNCTION_USAGE (insn));
8960
8961       /* Return 1 to tell the caller that we've generated the call
8962          insn.  */
8963       return 1;
8964     }
8965
8966   /* We know the function we are going to call.  If we have already
8967      built a stub, we don't need to do anything further.  */
8968
8969   fnname = XSTR (fn, 0);
8970   for (l = mips16_stubs; l != NULL; l = l->next)
8971     if (strcmp (l->name, fnname) == 0)
8972       break;
8973
8974   if (l == NULL)
8975     {
8976       /* Build a special purpose stub.  When the linker sees a
8977          function call in mips16 code, it will check where the target
8978          is defined.  If the target is a 32-bit call, the linker will
8979          search for the section defined here.  It can tell which
8980          symbol this section is associated with by looking at the
8981          relocation information (the name is unreliable, since this
8982          might be a static function).  If such a section is found, the
8983          linker will redirect the call to the start of the magic
8984          section.
8985
8986          If the function does not return a floating point value, the
8987          special stub section is named
8988              .mips16.call.FNNAME
8989
8990          If the function does return a floating point value, the stub
8991          section is named
8992              .mips16.call.fp.FNNAME
8993          */
8994
8995       secname = (char *) alloca (strlen (fnname) + 40);
8996       sprintf (secname, ".mips16.call.%s%s",
8997                fpret ? "fp." : "",
8998                fnname);
8999       stubname = (char *) alloca (strlen (fnname) + 20);
9000       sprintf (stubname, "__call_stub_%s%s",
9001                fpret ? "fp_" : "",
9002                fnname);
9003       stubid = get_identifier (stubname);
9004       stubdecl = build_decl (FUNCTION_DECL, stubid,
9005                              build_function_type (void_type_node, NULL_TREE));
9006       DECL_SECTION_NAME (stubdecl) = build_string (strlen (secname), secname);
9007       DECL_RESULT (stubdecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
9008
9009       fprintf (asm_out_file, "\t# Stub function to call %s%s (",
9010                (fpret
9011                 ? (GET_MODE (retval) == SFmode ? "float " : "double ")
9012                 : ""),
9013                fnname);
9014       need_comma = 0;
9015       for (f = (unsigned int) fp_code; f != 0; f >>= 2)
9016         {
9017           fprintf (asm_out_file, "%s%s",
9018                    need_comma ? ", " : "",
9019                    (f & 3) == 1 ? "float" : "double");
9020           need_comma = 1;
9021         }
9022       fprintf (asm_out_file, ")\n");
9023
9024       fprintf (asm_out_file, "\t.set\tnomips16\n");
9025       assemble_start_function (stubdecl, stubname);
9026
9027       if (!FUNCTION_NAME_ALREADY_DECLARED)
9028         {
9029           fputs ("\t.ent\t", asm_out_file);
9030           assemble_name (asm_out_file, stubname);
9031           fputs ("\n", asm_out_file);
9032
9033           assemble_name (asm_out_file, stubname);
9034           fputs (":\n", asm_out_file);
9035         }
9036
9037       /* We build the stub code by hand.  That's the only way we can
9038          do it, since we can't generate 32-bit code during a 16-bit
9039          compilation.  */
9040
9041       /* We don't want the assembler to insert any nops here.  */
9042       fprintf (asm_out_file, "\t.set\tnoreorder\n");
9043
9044       mips16_fp_args (asm_out_file, fp_code, 0);
9045
9046       if (! fpret)
9047         {
9048           fprintf (asm_out_file, "\t.set\tnoat\n");
9049           fprintf (asm_out_file, "\tla\t%s,%s\n", reg_names[GP_REG_FIRST + 1],
9050                    fnname);
9051           fprintf (asm_out_file, "\tjr\t%s\n", reg_names[GP_REG_FIRST + 1]);
9052           fprintf (asm_out_file, "\t.set\tat\n");
9053           /* Unfortunately, we can't fill the jump delay slot.  We
9054              can't fill with one of the mtc1 instructions, because the
9055              result is not available for one instruction, so if the
9056              very first instruction in the function refers to the
9057              register, it will see the wrong value.  */
9058           fprintf (asm_out_file, "\tnop\n");
9059         }
9060       else
9061         {
9062           fprintf (asm_out_file, "\tmove\t%s,%s\n",
9063                    reg_names[GP_REG_FIRST + 18], reg_names[GP_REG_FIRST + 31]);
9064           fprintf (asm_out_file, "\tjal\t%s\n", fnname);
9065           /* As above, we can't fill the delay slot.  */
9066           fprintf (asm_out_file, "\tnop\n");
9067           if (GET_MODE (retval) == SFmode)
9068             fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9069                      reg_names[GP_REG_FIRST + 2], reg_names[FP_REG_FIRST + 0]);
9070           else if (GET_MODE (retval) == SCmode)
9071             {
9072               fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9073                        reg_names[GP_REG_FIRST + 2],
9074                        reg_names[FP_REG_FIRST + 0]);
9075               fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9076                        reg_names[GP_REG_FIRST + 3],
9077                        reg_names[FP_REG_FIRST + MAX_FPRS_PER_FMT]);
9078             }
9079           else if (GET_MODE (retval) == DFmode
9080                    || GET_MODE (retval) == V2SFmode)
9081             {
9082               mips16_fpret_double (GP_REG_FIRST + 2, FP_REG_FIRST + 0);
9083             }
9084           else if (GET_MODE (retval) == DCmode)
9085             {
9086               mips16_fpret_double (GP_REG_FIRST + 2,
9087                                    FP_REG_FIRST + 0);
9088               mips16_fpret_double (GP_REG_FIRST + 4,
9089                                    FP_REG_FIRST + MAX_FPRS_PER_FMT);
9090             }
9091           else
9092             {
9093               if (TARGET_BIG_ENDIAN)
9094                 {
9095                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9096                            reg_names[GP_REG_FIRST + 2],
9097                            reg_names[FP_REG_FIRST + 1]);
9098                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9099                            reg_names[GP_REG_FIRST + 3],
9100                            reg_names[FP_REG_FIRST + 0]);
9101                 }
9102               else
9103                 {
9104                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9105                            reg_names[GP_REG_FIRST + 2],
9106                            reg_names[FP_REG_FIRST + 0]);
9107                   fprintf (asm_out_file, "\tmfc1\t%s,%s\n",
9108                            reg_names[GP_REG_FIRST + 3],
9109                            reg_names[FP_REG_FIRST + 1]);
9110                 }
9111             }
9112           fprintf (asm_out_file, "\tj\t%s\n", reg_names[GP_REG_FIRST + 18]);
9113           /* As above, we can't fill the delay slot.  */
9114           fprintf (asm_out_file, "\tnop\n");
9115         }
9116
9117       fprintf (asm_out_file, "\t.set\treorder\n");
9118
9119 #ifdef ASM_DECLARE_FUNCTION_SIZE
9120       ASM_DECLARE_FUNCTION_SIZE (asm_out_file, stubname, stubdecl);
9121 #endif
9122
9123       if (!FUNCTION_NAME_ALREADY_DECLARED)
9124         {
9125           fputs ("\t.end\t", asm_out_file);
9126           assemble_name (asm_out_file, stubname);
9127           fputs ("\n", asm_out_file);
9128         }
9129
9130       fprintf (asm_out_file, "\t.set\tmips16\n");
9131
9132       /* Record this stub.  */
9133       l = (struct mips16_stub *) xmalloc (sizeof *l);
9134       l->name = xstrdup (fnname);
9135       l->fpret = fpret;
9136       l->next = mips16_stubs;
9137       mips16_stubs = l;
9138     }
9139
9140   /* If we expect a floating point return value, but we've built a
9141      stub which does not expect one, then we're in trouble.  We can't
9142      use the existing stub, because it won't handle the floating point
9143      value.  We can't build a new stub, because the linker won't know
9144      which stub to use for the various calls in this object file.
9145      Fortunately, this case is illegal, since it means that a function
9146      was declared in two different ways in a single compilation.  */
9147   if (fpret && ! l->fpret)
9148     error ("cannot handle inconsistent calls to %qs", fnname);
9149
9150   /* If we are calling a stub which handles a floating point return
9151      value, we need to arrange to save $18 in the prologue.  We do
9152      this by marking the function call as using the register.  The
9153      prologue will later see that it is used, and emit code to save
9154      it.  */
9155
9156   if (l->fpret)
9157     {
9158       rtx insn;
9159
9160       if (retval == NULL_RTX)
9161         insn = gen_call_internal (fn, arg_size);
9162       else
9163         insn = gen_call_value_internal (retval, fn, arg_size);
9164       insn = emit_call_insn (insn);
9165
9166       CALL_INSN_FUNCTION_USAGE (insn) =
9167         gen_rtx_EXPR_LIST (VOIDmode,
9168                            gen_rtx_USE (VOIDmode, gen_rtx_REG (word_mode, 18)),
9169                            CALL_INSN_FUNCTION_USAGE (insn));
9170
9171       /* Return 1 to tell the caller that we've generated the call
9172          insn.  */
9173       return 1;
9174     }
9175
9176   /* Return 0 to let the caller generate the call insn.  */
9177   return 0;
9178 }
9179
9180 /* An entry in the mips16 constant pool.  VALUE is the pool constant,
9181    MODE is its mode, and LABEL is the CODE_LABEL associated with it.  */
9182
9183 struct mips16_constant {
9184   struct mips16_constant *next;
9185   rtx value;
9186   rtx label;
9187   enum machine_mode mode;
9188 };
9189
9190 /* Information about an incomplete mips16 constant pool.  FIRST is the
9191    first constant, HIGHEST_ADDRESS is the highest address that the first
9192    byte of the pool can have, and INSN_ADDRESS is the current instruction
9193    address.  */
9194
9195 struct mips16_constant_pool {
9196   struct mips16_constant *first;
9197   int highest_address;
9198   int insn_address;
9199 };
9200
9201 /* Add constant VALUE to POOL and return its label.  MODE is the
9202    value's mode (used for CONST_INTs, etc.).  */
9203
9204 static rtx
9205 add_constant (struct mips16_constant_pool *pool,
9206               rtx value, enum machine_mode mode)
9207 {
9208   struct mips16_constant **p, *c;
9209   bool first_of_size_p;
9210
9211   /* See whether the constant is already in the pool.  If so, return the
9212      existing label, otherwise leave P pointing to the place where the
9213      constant should be added.
9214
9215      Keep the pool sorted in increasing order of mode size so that we can
9216      reduce the number of alignments needed.  */
9217   first_of_size_p = true;
9218   for (p = &pool->first; *p != 0; p = &(*p)->next)
9219     {
9220       if (mode == (*p)->mode && rtx_equal_p (value, (*p)->value))
9221         return (*p)->label;
9222       if (GET_MODE_SIZE (mode) < GET_MODE_SIZE ((*p)->mode))
9223         break;
9224       if (GET_MODE_SIZE (mode) == GET_MODE_SIZE ((*p)->mode))
9225         first_of_size_p = false;
9226     }
9227
9228   /* In the worst case, the constant needed by the earliest instruction
9229      will end up at the end of the pool.  The entire pool must then be
9230      accessible from that instruction.
9231
9232      When adding the first constant, set the pool's highest address to
9233      the address of the first out-of-range byte.  Adjust this address
9234      downwards each time a new constant is added.  */
9235   if (pool->first == 0)
9236     /* For pc-relative lw, addiu and daddiu instructions, the base PC value
9237        is the address of the instruction with the lowest two bits clear.
9238        The base PC value for ld has the lowest three bits clear.  Assume
9239        the worst case here.  */
9240     pool->highest_address = pool->insn_address - (UNITS_PER_WORD - 2) + 0x8000;
9241   pool->highest_address -= GET_MODE_SIZE (mode);
9242   if (first_of_size_p)
9243     /* Take into account the worst possible padding due to alignment.  */
9244     pool->highest_address -= GET_MODE_SIZE (mode) - 1;
9245
9246   /* Create a new entry.  */
9247   c = (struct mips16_constant *) xmalloc (sizeof *c);
9248   c->value = value;
9249   c->mode = mode;
9250   c->label = gen_label_rtx ();
9251   c->next = *p;
9252   *p = c;
9253
9254   return c->label;
9255 }
9256
9257 /* Output constant VALUE after instruction INSN and return the last
9258    instruction emitted.  MODE is the mode of the constant.  */
9259
9260 static rtx
9261 dump_constants_1 (enum machine_mode mode, rtx value, rtx insn)
9262 {
9263   switch (GET_MODE_CLASS (mode))
9264     {
9265     case MODE_INT:
9266       {
9267         rtx size = GEN_INT (GET_MODE_SIZE (mode));
9268         return emit_insn_after (gen_consttable_int (value, size), insn);
9269       }
9270
9271     case MODE_FLOAT:
9272       return emit_insn_after (gen_consttable_float (value), insn);
9273
9274     case MODE_VECTOR_FLOAT:
9275     case MODE_VECTOR_INT:
9276       {
9277         int i;
9278         for (i = 0; i < CONST_VECTOR_NUNITS (value); i++)
9279           insn = dump_constants_1 (GET_MODE_INNER (mode),
9280                                    CONST_VECTOR_ELT (value, i), insn);
9281         return insn;
9282       }
9283
9284     default:
9285       gcc_unreachable ();
9286     }
9287 }
9288
9289
9290 /* Dump out the constants in CONSTANTS after INSN.  */
9291
9292 static void
9293 dump_constants (struct mips16_constant *constants, rtx insn)
9294 {
9295   struct mips16_constant *c, *next;
9296   int align;
9297
9298   align = 0;
9299   for (c = constants; c != NULL; c = next)
9300     {
9301       /* If necessary, increase the alignment of PC.  */
9302       if (align < GET_MODE_SIZE (c->mode))
9303         {
9304           int align_log = floor_log2 (GET_MODE_SIZE (c->mode));
9305           insn = emit_insn_after (gen_align (GEN_INT (align_log)), insn);
9306         }
9307       align = GET_MODE_SIZE (c->mode);
9308
9309       insn = emit_label_after (c->label, insn);
9310       insn = dump_constants_1 (c->mode, c->value, insn);
9311
9312       next = c->next;
9313       free (c);
9314     }
9315
9316   emit_barrier_after (insn);
9317 }
9318
9319 /* Return the length of instruction INSN.  */
9320
9321 static int
9322 mips16_insn_length (rtx insn)
9323 {
9324   if (JUMP_P (insn))
9325     {
9326       rtx body = PATTERN (insn);
9327       if (GET_CODE (body) == ADDR_VEC)
9328         return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 0);
9329       if (GET_CODE (body) == ADDR_DIFF_VEC)
9330         return GET_MODE_SIZE (GET_MODE (body)) * XVECLEN (body, 1);
9331     }
9332   return get_attr_length (insn);
9333 }
9334
9335 /* Rewrite *X so that constant pool references refer to the constant's
9336    label instead.  DATA points to the constant pool structure.  */
9337
9338 static int
9339 mips16_rewrite_pool_refs (rtx *x, void *data)
9340 {
9341   struct mips16_constant_pool *pool = data;
9342   if (GET_CODE (*x) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (*x))
9343     *x = gen_rtx_LABEL_REF (Pmode, add_constant (pool,
9344                                                  get_pool_constant (*x),
9345                                                  get_pool_mode (*x)));
9346   return 0;
9347 }
9348
9349 /* Build MIPS16 constant pools.  */
9350
9351 static void
9352 mips16_lay_out_constants (void)
9353 {
9354   struct mips16_constant_pool pool;
9355   rtx insn, barrier;
9356
9357   barrier = 0;
9358   memset (&pool, 0, sizeof (pool));
9359   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
9360     {
9361       /* Rewrite constant pool references in INSN.  */
9362       if (INSN_P (insn))
9363         for_each_rtx (&PATTERN (insn), mips16_rewrite_pool_refs, &pool);
9364
9365       pool.insn_address += mips16_insn_length (insn);
9366
9367       if (pool.first != NULL)
9368         {
9369           /* If there are no natural barriers between the first user of
9370              the pool and the highest acceptable address, we'll need to
9371              create a new instruction to jump around the constant pool.
9372              In the worst case, this instruction will be 4 bytes long.
9373
9374              If it's too late to do this transformation after INSN,
9375              do it immediately before INSN.  */
9376           if (barrier == 0 && pool.insn_address + 4 > pool.highest_address)
9377             {
9378               rtx label, jump;
9379
9380               label = gen_label_rtx ();
9381
9382               jump = emit_jump_insn_before (gen_jump (label), insn);
9383               JUMP_LABEL (jump) = label;
9384               LABEL_NUSES (label) = 1;
9385               barrier = emit_barrier_after (jump);
9386
9387               emit_label_after (label, barrier);
9388               pool.insn_address += 4;
9389             }
9390
9391           /* See whether the constant pool is now out of range of the first
9392              user.  If so, output the constants after the previous barrier.
9393              Note that any instructions between BARRIER and INSN (inclusive)
9394              will use negative offsets to refer to the pool.  */
9395           if (pool.insn_address > pool.highest_address)
9396             {
9397               dump_constants (pool.first, barrier);
9398               pool.first = NULL;
9399               barrier = 0;
9400             }
9401           else if (BARRIER_P (insn))
9402             barrier = insn;
9403         }
9404     }
9405   dump_constants (pool.first, get_last_insn ());
9406 }
9407 \f
9408 /* A temporary variable used by for_each_rtx callbacks, etc.  */
9409 static rtx mips_sim_insn;
9410
9411 /* A structure representing the state of the processor pipeline.
9412    Used by the mips_sim_* family of functions.  */
9413 struct mips_sim {
9414   /* The maximum number of instructions that can be issued in a cycle.
9415      (Caches mips_issue_rate.)  */
9416   unsigned int issue_rate;
9417
9418   /* The current simulation time.  */
9419   unsigned int time;
9420
9421   /* How many more instructions can be issued in the current cycle.  */
9422   unsigned int insns_left;
9423
9424   /* LAST_SET[X].INSN is the last instruction to set register X.
9425      LAST_SET[X].TIME is the time at which that instruction was issued.
9426      INSN is null if no instruction has yet set register X.  */
9427   struct {
9428     rtx insn;
9429     unsigned int time;
9430   } last_set[FIRST_PSEUDO_REGISTER];
9431
9432   /* The pipeline's current DFA state.  */
9433   state_t dfa_state;
9434 };
9435
9436 /* Reset STATE to the initial simulation state.  */
9437
9438 static void
9439 mips_sim_reset (struct mips_sim *state)
9440 {
9441   state->time = 0;
9442   state->insns_left = state->issue_rate;
9443   memset (&state->last_set, 0, sizeof (state->last_set));
9444   state_reset (state->dfa_state);
9445 }
9446
9447 /* Initialize STATE before its first use.  DFA_STATE points to an
9448    allocated but uninitialized DFA state.  */
9449
9450 static void
9451 mips_sim_init (struct mips_sim *state, state_t dfa_state)
9452 {
9453   state->issue_rate = mips_issue_rate ();
9454   state->dfa_state = dfa_state;
9455   mips_sim_reset (state);
9456 }
9457
9458 /* Advance STATE by one clock cycle.  */
9459
9460 static void
9461 mips_sim_next_cycle (struct mips_sim *state)
9462 {
9463   state->time++;
9464   state->insns_left = state->issue_rate;
9465   state_transition (state->dfa_state, 0);
9466 }
9467
9468 /* Advance simulation state STATE until instruction INSN can read
9469    register REG.  */
9470
9471 static void
9472 mips_sim_wait_reg (struct mips_sim *state, rtx insn, rtx reg)
9473 {
9474   unsigned int i;
9475
9476   for (i = 0; i < HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg)); i++)
9477     if (state->last_set[REGNO (reg) + i].insn != 0)
9478       {
9479         unsigned int t;
9480
9481         t = state->last_set[REGNO (reg) + i].time;
9482         t += insn_latency (state->last_set[REGNO (reg) + i].insn, insn);
9483         while (state->time < t)
9484           mips_sim_next_cycle (state);
9485     }
9486 }
9487
9488 /* A for_each_rtx callback.  If *X is a register, advance simulation state
9489    DATA until mips_sim_insn can read the register's value.  */
9490
9491 static int
9492 mips_sim_wait_regs_2 (rtx *x, void *data)
9493 {
9494   if (REG_P (*x))
9495     mips_sim_wait_reg (data, mips_sim_insn, *x);
9496   return 0;
9497 }
9498
9499 /* Call mips_sim_wait_regs_2 (R, DATA) for each register R mentioned in *X.  */
9500
9501 static void
9502 mips_sim_wait_regs_1 (rtx *x, void *data)
9503 {
9504   for_each_rtx (x, mips_sim_wait_regs_2, data);
9505 }
9506
9507 /* Advance simulation state STATE until all of INSN's register
9508    dependencies are satisfied.  */
9509
9510 static void
9511 mips_sim_wait_regs (struct mips_sim *state, rtx insn)
9512 {
9513   mips_sim_insn = insn;
9514   note_uses (&PATTERN (insn), mips_sim_wait_regs_1, state);
9515 }
9516
9517 /* Advance simulation state STATE until the units required by
9518    instruction INSN are available.  */
9519
9520 static void
9521 mips_sim_wait_units (struct mips_sim *state, rtx insn)
9522 {
9523   state_t tmp_state;
9524
9525   tmp_state = alloca (state_size ());
9526   while (state->insns_left == 0
9527          || (memcpy (tmp_state, state->dfa_state, state_size ()),
9528              state_transition (tmp_state, insn) >= 0))
9529     mips_sim_next_cycle (state);
9530 }
9531
9532 /* Advance simulation state STATE until INSN is ready to issue.  */
9533
9534 static void
9535 mips_sim_wait_insn (struct mips_sim *state, rtx insn)
9536 {
9537   mips_sim_wait_regs (state, insn);
9538   mips_sim_wait_units (state, insn);
9539 }
9540
9541 /* mips_sim_insn has just set X.  Update the LAST_SET array
9542    in simulation state DATA.  */
9543
9544 static void
9545 mips_sim_record_set (rtx x, rtx pat ATTRIBUTE_UNUSED, void *data)
9546 {
9547   struct mips_sim *state;
9548   unsigned int i;
9549
9550   state = data;
9551   if (REG_P (x))
9552     for (i = 0; i < HARD_REGNO_NREGS (REGNO (x), GET_MODE (x)); i++)
9553       {
9554         state->last_set[REGNO (x) + i].insn = mips_sim_insn;
9555         state->last_set[REGNO (x) + i].time = state->time;
9556       }
9557 }
9558
9559 /* Issue instruction INSN in scheduler state STATE.  Assume that INSN
9560    can issue immediately (i.e., that mips_sim_wait_insn has already
9561    been called).  */
9562
9563 static void
9564 mips_sim_issue_insn (struct mips_sim *state, rtx insn)
9565 {
9566   state_transition (state->dfa_state, insn);
9567   state->insns_left--;
9568
9569   mips_sim_insn = insn;
9570   note_stores (PATTERN (insn), mips_sim_record_set, state);
9571 }
9572
9573 /* Simulate issuing a NOP in state STATE.  */
9574
9575 static void
9576 mips_sim_issue_nop (struct mips_sim *state)
9577 {
9578   if (state->insns_left == 0)
9579     mips_sim_next_cycle (state);
9580   state->insns_left--;
9581 }
9582
9583 /* Update simulation state STATE so that it's ready to accept the instruction
9584    after INSN.  INSN should be part of the main rtl chain, not a member of a
9585    SEQUENCE.  */
9586
9587 static void
9588 mips_sim_finish_insn (struct mips_sim *state, rtx insn)
9589 {
9590   /* If INSN is a jump with an implicit delay slot, simulate a nop.  */
9591   if (JUMP_P (insn))
9592     mips_sim_issue_nop (state);
9593
9594   switch (GET_CODE (SEQ_BEGIN (insn)))
9595     {
9596     case CODE_LABEL:
9597     case CALL_INSN:
9598       /* We can't predict the processor state after a call or label.  */
9599       mips_sim_reset (state);
9600       break;
9601
9602     case JUMP_INSN:
9603       /* The delay slots of branch likely instructions are only executed
9604          when the branch is taken.  Therefore, if the caller has simulated
9605          the delay slot instruction, STATE does not really reflect the state
9606          of the pipeline for the instruction after the delay slot.  Also,
9607          branch likely instructions tend to incur a penalty when not taken,
9608          so there will probably be an extra delay between the branch and
9609          the instruction after the delay slot.  */
9610       if (INSN_ANNULLED_BRANCH_P (SEQ_BEGIN (insn)))
9611         mips_sim_reset (state);
9612       break;
9613
9614     default:
9615       break;
9616     }
9617 }
9618 \f
9619 /* The VR4130 pipeline issues aligned pairs of instructions together,
9620    but it stalls the second instruction if it depends on the first.
9621    In order to cut down the amount of logic required, this dependence
9622    check is not based on a full instruction decode.  Instead, any non-SPECIAL
9623    instruction is assumed to modify the register specified by bits 20-16
9624    (which is usually the "rt" field).
9625
9626    In beq, beql, bne and bnel instructions, the rt field is actually an
9627    input, so we can end up with a false dependence between the branch
9628    and its delay slot.  If this situation occurs in instruction INSN,
9629    try to avoid it by swapping rs and rt.  */
9630
9631 static void
9632 vr4130_avoid_branch_rt_conflict (rtx insn)
9633 {
9634   rtx first, second;
9635
9636   first = SEQ_BEGIN (insn);
9637   second = SEQ_END (insn);
9638   if (JUMP_P (first)
9639       && NONJUMP_INSN_P (second)
9640       && GET_CODE (PATTERN (first)) == SET
9641       && GET_CODE (SET_DEST (PATTERN (first))) == PC
9642       && GET_CODE (SET_SRC (PATTERN (first))) == IF_THEN_ELSE)
9643     {
9644       /* Check for the right kind of condition.  */
9645       rtx cond = XEXP (SET_SRC (PATTERN (first)), 0);
9646       if ((GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
9647           && REG_P (XEXP (cond, 0))
9648           && REG_P (XEXP (cond, 1))
9649           && reg_referenced_p (XEXP (cond, 1), PATTERN (second))
9650           && !reg_referenced_p (XEXP (cond, 0), PATTERN (second)))
9651         {
9652           /* SECOND mentions the rt register but not the rs register.  */
9653           rtx tmp = XEXP (cond, 0);
9654           XEXP (cond, 0) = XEXP (cond, 1);
9655           XEXP (cond, 1) = tmp;
9656         }
9657     }
9658 }
9659
9660 /* Implement -mvr4130-align.  Go through each basic block and simulate the
9661    processor pipeline.  If we find that a pair of instructions could execute
9662    in parallel, and the first of those instruction is not 8-byte aligned,
9663    insert a nop to make it aligned.  */
9664
9665 static void
9666 vr4130_align_insns (void)
9667 {
9668   struct mips_sim state;
9669   rtx insn, subinsn, last, last2, next;
9670   bool aligned_p;
9671
9672   dfa_start ();
9673
9674   /* LAST is the last instruction before INSN to have a nonzero length.
9675      LAST2 is the last such instruction before LAST.  */
9676   last = 0;
9677   last2 = 0;
9678
9679   /* ALIGNED_P is true if INSN is known to be at an aligned address.  */
9680   aligned_p = true;
9681
9682   mips_sim_init (&state, alloca (state_size ()));
9683   for (insn = get_insns (); insn != 0; insn = next)
9684     {
9685       unsigned int length;
9686
9687       next = NEXT_INSN (insn);
9688
9689       /* See the comment above vr4130_avoid_branch_rt_conflict for details.
9690          This isn't really related to the alignment pass, but we do it on
9691          the fly to avoid a separate instruction walk.  */
9692       vr4130_avoid_branch_rt_conflict (insn);
9693
9694       if (USEFUL_INSN_P (insn))
9695         FOR_EACH_SUBINSN (subinsn, insn)
9696           {
9697             mips_sim_wait_insn (&state, subinsn);
9698
9699             /* If we want this instruction to issue in parallel with the
9700                previous one, make sure that the previous instruction is
9701                aligned.  There are several reasons why this isn't worthwhile
9702                when the second instruction is a call:
9703
9704                   - Calls are less likely to be performance critical,
9705                   - There's a good chance that the delay slot can execute
9706                     in parallel with the call.
9707                   - The return address would then be unaligned.
9708
9709                In general, if we're going to insert a nop between instructions
9710                X and Y, it's better to insert it immediately after X.  That
9711                way, if the nop makes Y aligned, it will also align any labels
9712                between X and Y.  */
9713             if (state.insns_left != state.issue_rate
9714                 && !CALL_P (subinsn))
9715               {
9716                 if (subinsn == SEQ_BEGIN (insn) && aligned_p)
9717                   {
9718                     /* SUBINSN is the first instruction in INSN and INSN is
9719                        aligned.  We want to align the previous instruction
9720                        instead, so insert a nop between LAST2 and LAST.
9721
9722                        Note that LAST could be either a single instruction
9723                        or a branch with a delay slot.  In the latter case,
9724                        LAST, like INSN, is already aligned, but the delay
9725                        slot must have some extra delay that stops it from
9726                        issuing at the same time as the branch.  We therefore
9727                        insert a nop before the branch in order to align its
9728                        delay slot.  */
9729                     emit_insn_after (gen_nop (), last2);
9730                     aligned_p = false;
9731                   }
9732                 else if (subinsn != SEQ_BEGIN (insn) && !aligned_p)
9733                   {
9734                     /* SUBINSN is the delay slot of INSN, but INSN is
9735                        currently unaligned.  Insert a nop between
9736                        LAST and INSN to align it.  */
9737                     emit_insn_after (gen_nop (), last);
9738                     aligned_p = true;
9739                   }
9740               }
9741             mips_sim_issue_insn (&state, subinsn);
9742           }
9743       mips_sim_finish_insn (&state, insn);
9744
9745       /* Update LAST, LAST2 and ALIGNED_P for the next instruction.  */
9746       length = get_attr_length (insn);
9747       if (length > 0)
9748         {
9749           /* If the instruction is an asm statement or multi-instruction
9750              mips.md patern, the length is only an estimate.  Insert an
9751              8 byte alignment after it so that the following instructions
9752              can be handled correctly.  */
9753           if (NONJUMP_INSN_P (SEQ_BEGIN (insn))
9754               && (recog_memoized (insn) < 0 || length >= 8))
9755             {
9756               next = emit_insn_after (gen_align (GEN_INT (3)), insn);
9757               next = NEXT_INSN (next);
9758               mips_sim_next_cycle (&state);
9759               aligned_p = true;
9760             }
9761           else if (length & 4)
9762             aligned_p = !aligned_p;
9763           last2 = last;
9764           last = insn;
9765         }
9766
9767       /* See whether INSN is an aligned label.  */
9768       if (LABEL_P (insn) && label_to_alignment (insn) >= 3)
9769         aligned_p = true;
9770     }
9771   dfa_finish ();
9772 }
9773 \f
9774 /* Subroutine of mips_reorg.  If there is a hazard between INSN
9775    and a previous instruction, avoid it by inserting nops after
9776    instruction AFTER.
9777
9778    *DELAYED_REG and *HILO_DELAY describe the hazards that apply at
9779    this point.  If *DELAYED_REG is non-null, INSN must wait a cycle
9780    before using the value of that register.  *HILO_DELAY counts the
9781    number of instructions since the last hilo hazard (that is,
9782    the number of instructions since the last mflo or mfhi).
9783
9784    After inserting nops for INSN, update *DELAYED_REG and *HILO_DELAY
9785    for the next instruction.
9786
9787    LO_REG is an rtx for the LO register, used in dependence checking.  */
9788
9789 static void
9790 mips_avoid_hazard (rtx after, rtx insn, int *hilo_delay,
9791                    rtx *delayed_reg, rtx lo_reg)
9792 {
9793   rtx pattern, set;
9794   int nops, ninsns;
9795
9796   if (!INSN_P (insn))
9797     return;
9798
9799   pattern = PATTERN (insn);
9800
9801   /* Do not put the whole function in .set noreorder if it contains
9802      an asm statement.  We don't know whether there will be hazards
9803      between the asm statement and the gcc-generated code.  */
9804   if (GET_CODE (pattern) == ASM_INPUT || asm_noperands (pattern) >= 0)
9805     cfun->machine->all_noreorder_p = false;
9806
9807   /* Ignore zero-length instructions (barriers and the like).  */
9808   ninsns = get_attr_length (insn) / 4;
9809   if (ninsns == 0)
9810     return;
9811
9812   /* Work out how many nops are needed.  Note that we only care about
9813      registers that are explicitly mentioned in the instruction's pattern.
9814      It doesn't matter that calls use the argument registers or that they
9815      clobber hi and lo.  */
9816   if (*hilo_delay < 2 && reg_set_p (lo_reg, pattern))
9817     nops = 2 - *hilo_delay;
9818   else if (*delayed_reg != 0 && reg_referenced_p (*delayed_reg, pattern))
9819     nops = 1;
9820   else
9821     nops = 0;
9822
9823   /* Insert the nops between this instruction and the previous one.
9824      Each new nop takes us further from the last hilo hazard.  */
9825   *hilo_delay += nops;
9826   while (nops-- > 0)
9827     emit_insn_after (gen_hazard_nop (), after);
9828
9829   /* Set up the state for the next instruction.  */
9830   *hilo_delay += ninsns;
9831   *delayed_reg = 0;
9832   if (INSN_CODE (insn) >= 0)
9833     switch (get_attr_hazard (insn))
9834       {
9835       case HAZARD_NONE:
9836         break;
9837
9838       case HAZARD_HILO:
9839         *hilo_delay = 0;
9840         break;
9841
9842       case HAZARD_DELAY:
9843         set = single_set (insn);
9844         gcc_assert (set != 0);
9845         *delayed_reg = SET_DEST (set);
9846         break;
9847       }
9848 }
9849
9850
9851 /* Go through the instruction stream and insert nops where necessary.
9852    See if the whole function can then be put into .set noreorder &
9853    .set nomacro.  */
9854
9855 static void
9856 mips_avoid_hazards (void)
9857 {
9858   rtx insn, last_insn, lo_reg, delayed_reg;
9859   int hilo_delay, i;
9860
9861   /* Force all instructions to be split into their final form.  */
9862   split_all_insns_noflow ();
9863
9864   /* Recalculate instruction lengths without taking nops into account.  */
9865   cfun->machine->ignore_hazard_length_p = true;
9866   shorten_branches (get_insns ());
9867
9868   cfun->machine->all_noreorder_p = true;
9869
9870   /* Profiled functions can't be all noreorder because the profiler
9871      support uses assembler macros.  */
9872   if (current_function_profile)
9873     cfun->machine->all_noreorder_p = false;
9874
9875   /* Code compiled with -mfix-vr4120 can't be all noreorder because
9876      we rely on the assembler to work around some errata.  */
9877   if (TARGET_FIX_VR4120)
9878     cfun->machine->all_noreorder_p = false;
9879
9880   /* The same is true for -mfix-vr4130 if we might generate mflo or
9881      mfhi instructions.  Note that we avoid using mflo and mfhi if
9882      the VR4130 macc and dmacc instructions are available instead;
9883      see the *mfhilo_{si,di}_macc patterns.  */
9884   if (TARGET_FIX_VR4130 && !ISA_HAS_MACCHI)
9885     cfun->machine->all_noreorder_p = false;
9886
9887   last_insn = 0;
9888   hilo_delay = 2;
9889   delayed_reg = 0;
9890   lo_reg = gen_rtx_REG (SImode, LO_REGNUM);
9891
9892   for (insn = get_insns (); insn != 0; insn = NEXT_INSN (insn))
9893     if (INSN_P (insn))
9894       {
9895         if (GET_CODE (PATTERN (insn)) == SEQUENCE)
9896           for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
9897             mips_avoid_hazard (last_insn, XVECEXP (PATTERN (insn), 0, i),
9898                                &hilo_delay, &delayed_reg, lo_reg);
9899         else
9900           mips_avoid_hazard (last_insn, insn, &hilo_delay,
9901                              &delayed_reg, lo_reg);
9902
9903         last_insn = insn;
9904       }
9905 }
9906
9907
9908 /* Implement TARGET_MACHINE_DEPENDENT_REORG.  */
9909
9910 static void
9911 mips_reorg (void)
9912 {
9913   if (TARGET_MIPS16)
9914     mips16_lay_out_constants ();
9915   else if (TARGET_EXPLICIT_RELOCS)
9916     {
9917       if (mips_flag_delayed_branch)
9918         dbr_schedule (get_insns ());
9919       mips_avoid_hazards ();
9920       if (TUNE_MIPS4130 && TARGET_VR4130_ALIGN)
9921         vr4130_align_insns ();
9922     }
9923 }
9924
9925 /* This function does three things:
9926
9927    - Register the special divsi3 and modsi3 functions if -mfix-vr4120.
9928    - Register the mips16 hardware floating point stubs.
9929    - Register the gofast functions if selected using --enable-gofast.  */
9930
9931 #include "config/gofast.h"
9932
9933 static void
9934 mips_init_libfuncs (void)
9935 {
9936   if (TARGET_FIX_VR4120)
9937     {
9938       set_optab_libfunc (sdiv_optab, SImode, "__vr4120_divsi3");
9939       set_optab_libfunc (smod_optab, SImode, "__vr4120_modsi3");
9940     }
9941
9942   if (mips16_hard_float)
9943     {
9944       set_optab_libfunc (add_optab, SFmode, "__mips16_addsf3");
9945       set_optab_libfunc (sub_optab, SFmode, "__mips16_subsf3");
9946       set_optab_libfunc (smul_optab, SFmode, "__mips16_mulsf3");
9947       set_optab_libfunc (sdiv_optab, SFmode, "__mips16_divsf3");
9948
9949       set_optab_libfunc (eq_optab, SFmode, "__mips16_eqsf2");
9950       set_optab_libfunc (ne_optab, SFmode, "__mips16_nesf2");
9951       set_optab_libfunc (gt_optab, SFmode, "__mips16_gtsf2");
9952       set_optab_libfunc (ge_optab, SFmode, "__mips16_gesf2");
9953       set_optab_libfunc (lt_optab, SFmode, "__mips16_ltsf2");
9954       set_optab_libfunc (le_optab, SFmode, "__mips16_lesf2");
9955
9956       set_conv_libfunc (sfix_optab, SImode, SFmode, "__mips16_fix_truncsfsi");
9957       set_conv_libfunc (sfloat_optab, SFmode, SImode, "__mips16_floatsisf");
9958
9959       if (TARGET_DOUBLE_FLOAT)
9960         {
9961           set_optab_libfunc (add_optab, DFmode, "__mips16_adddf3");
9962           set_optab_libfunc (sub_optab, DFmode, "__mips16_subdf3");
9963           set_optab_libfunc (smul_optab, DFmode, "__mips16_muldf3");
9964           set_optab_libfunc (sdiv_optab, DFmode, "__mips16_divdf3");
9965
9966           set_optab_libfunc (eq_optab, DFmode, "__mips16_eqdf2");
9967           set_optab_libfunc (ne_optab, DFmode, "__mips16_nedf2");
9968           set_optab_libfunc (gt_optab, DFmode, "__mips16_gtdf2");
9969           set_optab_libfunc (ge_optab, DFmode, "__mips16_gedf2");
9970           set_optab_libfunc (lt_optab, DFmode, "__mips16_ltdf2");
9971           set_optab_libfunc (le_optab, DFmode, "__mips16_ledf2");
9972
9973           set_conv_libfunc (sext_optab, DFmode, SFmode, "__mips16_extendsfdf2");
9974           set_conv_libfunc (trunc_optab, SFmode, DFmode, "__mips16_truncdfsf2");
9975
9976           set_conv_libfunc (sfix_optab, SImode, DFmode, "__mips16_fix_truncdfsi");
9977           set_conv_libfunc (sfloat_optab, DFmode, SImode, "__mips16_floatsidf");
9978         }
9979     }
9980   else
9981     gofast_maybe_init_libfuncs ();
9982 }
9983
9984 /* Return a number assessing the cost of moving a register in class
9985    FROM to class TO.  The classes are expressed using the enumeration
9986    values such as `GENERAL_REGS'.  A value of 2 is the default; other
9987    values are interpreted relative to that.
9988
9989    It is not required that the cost always equal 2 when FROM is the
9990    same as TO; on some machines it is expensive to move between
9991    registers if they are not general registers.
9992
9993    If reload sees an insn consisting of a single `set' between two
9994    hard registers, and if `REGISTER_MOVE_COST' applied to their
9995    classes returns a value of 2, reload does not check to ensure that
9996    the constraints of the insn are met.  Setting a cost of other than
9997    2 will allow reload to verify that the constraints are met.  You
9998    should do this if the `movM' pattern's constraints do not allow
9999    such copying.
10000
10001    ??? We make the cost of moving from HI/LO into general
10002    registers the same as for one of moving general registers to
10003    HI/LO for TARGET_MIPS16 in order to prevent allocating a
10004    pseudo to HI/LO.  This might hurt optimizations though, it
10005    isn't clear if it is wise.  And it might not work in all cases.  We
10006    could solve the DImode LO reg problem by using a multiply, just
10007    like reload_{in,out}si.  We could solve the SImode/HImode HI reg
10008    problem by using divide instructions.  divu puts the remainder in
10009    the HI reg, so doing a divide by -1 will move the value in the HI
10010    reg for all values except -1.  We could handle that case by using a
10011    signed divide, e.g.  -1 / 2 (or maybe 1 / -2?).  We'd have to emit
10012    a compare/branch to test the input value to see which instruction
10013    we need to use.  This gets pretty messy, but it is feasible.  */
10014
10015 int
10016 mips_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
10017                          enum reg_class to, enum reg_class from)
10018 {
10019   if (from == M16_REGS && GR_REG_CLASS_P (to))
10020     return 2;
10021   else if (from == M16_NA_REGS && GR_REG_CLASS_P (to))
10022     return 2;
10023   else if (GR_REG_CLASS_P (from))
10024     {
10025       if (to == M16_REGS)
10026         return 2;
10027       else if (to == M16_NA_REGS)
10028         return 2;
10029       else if (GR_REG_CLASS_P (to))
10030         {
10031           if (TARGET_MIPS16)
10032             return 4;
10033           else
10034             return 2;
10035         }
10036       else if (to == FP_REGS)
10037         return 4;
10038       else if (reg_class_subset_p (to, ACC_REGS))
10039         {
10040           if (TARGET_MIPS16)
10041             return 12;
10042           else
10043             return 6;
10044         }
10045       else if (COP_REG_CLASS_P (to))
10046         {
10047           return 5;
10048         }
10049     }
10050   else if (from == FP_REGS)
10051     {
10052       if (GR_REG_CLASS_P (to))
10053         return 4;
10054       else if (to == FP_REGS)
10055         return 2;
10056       else if (to == ST_REGS)
10057         return 8;
10058     }
10059   else if (reg_class_subset_p (from, ACC_REGS))
10060     {
10061       if (GR_REG_CLASS_P (to))
10062         {
10063           if (TARGET_MIPS16)
10064             return 12;
10065           else
10066             return 6;
10067         }
10068     }
10069   else if (from == ST_REGS && GR_REG_CLASS_P (to))
10070     return 4;
10071   else if (COP_REG_CLASS_P (from))
10072     {
10073       return 5;
10074     }
10075
10076   /* Fall through.
10077      ??? What cases are these? Shouldn't we return 2 here?  */
10078
10079   return 12;
10080 }
10081
10082 /* Return the length of INSN.  LENGTH is the initial length computed by
10083    attributes in the machine-description file.  */
10084
10085 int
10086 mips_adjust_insn_length (rtx insn, int length)
10087 {
10088   /* A unconditional jump has an unfilled delay slot if it is not part
10089      of a sequence.  A conditional jump normally has a delay slot, but
10090      does not on MIPS16.  */
10091   if (CALL_P (insn) || (TARGET_MIPS16 ? simplejump_p (insn) : JUMP_P (insn)))
10092     length += 4;
10093
10094   /* See how many nops might be needed to avoid hardware hazards.  */
10095   if (!cfun->machine->ignore_hazard_length_p && INSN_CODE (insn) >= 0)
10096     switch (get_attr_hazard (insn))
10097       {
10098       case HAZARD_NONE:
10099         break;
10100
10101       case HAZARD_DELAY:
10102         length += 4;
10103         break;
10104
10105       case HAZARD_HILO:
10106         length += 8;
10107         break;
10108       }
10109
10110   /* All MIPS16 instructions are a measly two bytes.  */
10111   if (TARGET_MIPS16)
10112     length /= 2;
10113
10114   return length;
10115 }
10116
10117
10118 /* Return an asm sequence to start a noat block and load the address
10119    of a label into $1.  */
10120
10121 const char *
10122 mips_output_load_label (void)
10123 {
10124   if (TARGET_EXPLICIT_RELOCS)
10125     switch (mips_abi)
10126       {
10127       case ABI_N32:
10128         return "%[lw\t%@,%%got_page(%0)(%+)\n\taddiu\t%@,%@,%%got_ofst(%0)";
10129
10130       case ABI_64:
10131         return "%[ld\t%@,%%got_page(%0)(%+)\n\tdaddiu\t%@,%@,%%got_ofst(%0)";
10132
10133       default:
10134         if (ISA_HAS_LOAD_DELAY)
10135           return "%[lw\t%@,%%got(%0)(%+)%#\n\taddiu\t%@,%@,%%lo(%0)";
10136         return "%[lw\t%@,%%got(%0)(%+)\n\taddiu\t%@,%@,%%lo(%0)";
10137       }
10138   else
10139     {
10140       if (Pmode == DImode)
10141         return "%[dla\t%@,%0";
10142       else
10143         return "%[la\t%@,%0";
10144     }
10145 }
10146
10147 /* Return the assembly code for INSN, which has the operands given by
10148    OPERANDS, and which branches to OPERANDS[1] if some condition is true.
10149    BRANCH_IF_TRUE is the asm template that should be used if OPERANDS[1]
10150    is in range of a direct branch.  BRANCH_IF_FALSE is an inverted
10151    version of BRANCH_IF_TRUE.  */
10152
10153 const char *
10154 mips_output_conditional_branch (rtx insn, rtx *operands,
10155                                 const char *branch_if_true,
10156                                 const char *branch_if_false)
10157 {
10158   unsigned int length;
10159   rtx taken, not_taken;
10160
10161   length = get_attr_length (insn);
10162   if (length <= 8)
10163     {
10164       /* Just a simple conditional branch.  */
10165       mips_branch_likely = (final_sequence && INSN_ANNULLED_BRANCH_P (insn));
10166       return branch_if_true;
10167     }
10168
10169   /* Generate a reversed branch around a direct jump.  This fallback does
10170      not use branch-likely instructions.  */
10171   mips_branch_likely = false;
10172   not_taken = gen_label_rtx ();
10173   taken = operands[1];
10174
10175   /* Generate the reversed branch to NOT_TAKEN.  */
10176   operands[1] = not_taken;
10177   output_asm_insn (branch_if_false, operands);
10178
10179   /* If INSN has a delay slot, we must provide delay slots for both the
10180      branch to NOT_TAKEN and the conditional jump.  We must also ensure
10181      that INSN's delay slot is executed in the appropriate cases.  */
10182   if (final_sequence)
10183     {
10184       /* This first delay slot will always be executed, so use INSN's
10185          delay slot if is not annulled.  */
10186       if (!INSN_ANNULLED_BRANCH_P (insn))
10187         {
10188           final_scan_insn (XVECEXP (final_sequence, 0, 1),
10189                            asm_out_file, optimize, 1, NULL);
10190           INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
10191         }
10192       else
10193         output_asm_insn ("nop", 0);
10194       fprintf (asm_out_file, "\n");
10195     }
10196
10197   /* Output the unconditional branch to TAKEN.  */
10198   if (length <= 16)
10199     output_asm_insn ("j\t%0%/", &taken);
10200   else
10201     {
10202       output_asm_insn (mips_output_load_label (), &taken);
10203       output_asm_insn ("jr\t%@%]%/", 0);
10204     }
10205
10206   /* Now deal with its delay slot; see above.  */
10207   if (final_sequence)
10208     {
10209       /* This delay slot will only be executed if the branch is taken.
10210          Use INSN's delay slot if is annulled.  */
10211       if (INSN_ANNULLED_BRANCH_P (insn))
10212         {
10213           final_scan_insn (XVECEXP (final_sequence, 0, 1),
10214                            asm_out_file, optimize, 1, NULL);
10215           INSN_DELETED_P (XVECEXP (final_sequence, 0, 1)) = 1;
10216         }
10217       else
10218         output_asm_insn ("nop", 0);
10219       fprintf (asm_out_file, "\n");
10220     }
10221
10222   /* Output NOT_TAKEN.  */
10223   (*targetm.asm_out.internal_label) (asm_out_file, "L",
10224                                      CODE_LABEL_NUMBER (not_taken));
10225   return "";
10226 }
10227
10228 /* Return the assembly code for INSN, which branches to OPERANDS[1]
10229    if some ordered condition is true.  The condition is given by
10230    OPERANDS[0] if !INVERTED_P, otherwise it is the inverse of
10231    OPERANDS[0].  OPERANDS[2] is the comparison's first operand;
10232    its second is always zero.  */
10233
10234 const char *
10235 mips_output_order_conditional_branch (rtx insn, rtx *operands, bool inverted_p)
10236 {
10237   const char *branch[2];
10238
10239   /* Make BRANCH[1] branch to OPERANDS[1] when the condition is true.
10240      Make BRANCH[0] branch on the inverse condition.  */
10241   switch (GET_CODE (operands[0]))
10242     {
10243       /* These cases are equivalent to comparisons against zero.  */
10244     case LEU:
10245       inverted_p = !inverted_p;
10246       /* Fall through.  */
10247     case GTU:
10248       branch[!inverted_p] = MIPS_BRANCH ("bne", "%2,%.,%1");
10249       branch[inverted_p] = MIPS_BRANCH ("beq", "%2,%.,%1");
10250       break;
10251
10252       /* These cases are always true or always false.  */
10253     case LTU:
10254       inverted_p = !inverted_p;
10255       /* Fall through.  */
10256     case GEU:
10257       branch[!inverted_p] = MIPS_BRANCH ("beq", "%.,%.,%1");
10258       branch[inverted_p] = MIPS_BRANCH ("bne", "%.,%.,%1");
10259       break;
10260
10261     default:
10262       branch[!inverted_p] = MIPS_BRANCH ("b%C0z", "%2,%1");
10263       branch[inverted_p] = MIPS_BRANCH ("b%N0z", "%2,%1");
10264       break;
10265     }
10266   return mips_output_conditional_branch (insn, operands, branch[1], branch[0]);
10267 }
10268 \f
10269 /* Used to output div or ddiv instruction DIVISION, which has the operands
10270    given by OPERANDS.  Add in a divide-by-zero check if needed.
10271
10272    When working around R4000 and R4400 errata, we need to make sure that
10273    the division is not immediately followed by a shift[1][2].  We also
10274    need to stop the division from being put into a branch delay slot[3].
10275    The easiest way to avoid both problems is to add a nop after the
10276    division.  When a divide-by-zero check is needed, this nop can be
10277    used to fill the branch delay slot.
10278
10279    [1] If a double-word or a variable shift executes immediately
10280        after starting an integer division, the shift may give an
10281        incorrect result.  See quotations of errata #16 and #28 from
10282        "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
10283        in mips.md for details.
10284
10285    [2] A similar bug to [1] exists for all revisions of the
10286        R4000 and the R4400 when run in an MC configuration.
10287        From "MIPS R4000MC Errata, Processor Revision 2.2 and 3.0":
10288
10289        "19. In this following sequence:
10290
10291                     ddiv                (or ddivu or div or divu)
10292                     dsll32              (or dsrl32, dsra32)
10293
10294             if an MPT stall occurs, while the divide is slipping the cpu
10295             pipeline, then the following double shift would end up with an
10296             incorrect result.
10297
10298             Workaround: The compiler needs to avoid generating any
10299             sequence with divide followed by extended double shift."
10300
10301        This erratum is also present in "MIPS R4400MC Errata, Processor
10302        Revision 1.0" and "MIPS R4400MC Errata, Processor Revision 2.0
10303        & 3.0" as errata #10 and #4, respectively.
10304
10305    [3] From "MIPS R4000PC/SC Errata, Processor Revision 2.2 and 3.0"
10306        (also valid for MIPS R4000MC processors):
10307
10308        "52. R4000SC: This bug does not apply for the R4000PC.
10309
10310             There are two flavors of this bug:
10311
10312             1) If the instruction just after divide takes an RF exception
10313                (tlb-refill, tlb-invalid) and gets an instruction cache
10314                miss (both primary and secondary) and the line which is
10315                currently in secondary cache at this index had the first
10316                data word, where the bits 5..2 are set, then R4000 would
10317                get a wrong result for the div.
10318
10319             ##1
10320                     nop
10321                     div r8, r9
10322                     -------------------         # end-of page. -tlb-refill
10323                     nop
10324             ##2
10325                     nop
10326                     div r8, r9
10327                     -------------------         # end-of page. -tlb-invalid
10328                     nop
10329
10330             2) If the divide is in the taken branch delay slot, where the
10331                target takes RF exception and gets an I-cache miss for the
10332                exception vector or where I-cache miss occurs for the
10333                target address, under the above mentioned scenarios, the
10334                div would get wrong results.
10335
10336             ##1
10337                     j   r2              # to next page mapped or unmapped
10338                     div r8,r9           # this bug would be there as long
10339                                         # as there is an ICache miss and
10340                     nop                 # the "data pattern" is present
10341
10342             ##2
10343                     beq r0, r0, NextPage        # to Next page
10344                     div r8,r9
10345                     nop
10346
10347             This bug is present for div, divu, ddiv, and ddivu
10348             instructions.
10349
10350             Workaround: For item 1), OS could make sure that the next page
10351             after the divide instruction is also mapped.  For item 2), the
10352             compiler could make sure that the divide instruction is not in
10353             the branch delay slot."
10354
10355        These processors have PRId values of 0x00004220 and 0x00004300 for
10356        the R4000 and 0x00004400, 0x00004500 and 0x00004600 for the R4400.  */
10357
10358 const char *
10359 mips_output_division (const char *division, rtx *operands)
10360 {
10361   const char *s;
10362
10363   s = division;
10364   if (TARGET_FIX_R4000 || TARGET_FIX_R4400)
10365     {
10366       output_asm_insn (s, operands);
10367       s = "nop";
10368     }
10369   if (TARGET_CHECK_ZERO_DIV)
10370     {
10371       if (TARGET_MIPS16)
10372         {
10373           output_asm_insn (s, operands);
10374           s = "bnez\t%2,1f\n\tbreak\t7\n1:";
10375         }
10376       else if (GENERATE_DIVIDE_TRAPS)
10377         {
10378           output_asm_insn (s, operands);
10379           s = "teq\t%2,%.,7";
10380         }
10381       else
10382         {
10383           output_asm_insn ("%(bne\t%2,%.,1f", operands);
10384           output_asm_insn (s, operands);
10385           s = "break\t7%)\n1:";
10386         }
10387     }
10388   return s;
10389 }
10390 \f
10391 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
10392    with a final "000" replaced by "k".  Ignore case.
10393
10394    Note: this function is shared between GCC and GAS.  */
10395
10396 static bool
10397 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
10398 {
10399   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
10400     given++, canonical++;
10401
10402   return ((*given == 0 && *canonical == 0)
10403           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
10404 }
10405
10406
10407 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
10408    CPU name.  We've traditionally allowed a lot of variation here.
10409
10410    Note: this function is shared between GCC and GAS.  */
10411
10412 static bool
10413 mips_matching_cpu_name_p (const char *canonical, const char *given)
10414 {
10415   /* First see if the name matches exactly, or with a final "000"
10416      turned into "k".  */
10417   if (mips_strict_matching_cpu_name_p (canonical, given))
10418     return true;
10419
10420   /* If not, try comparing based on numerical designation alone.
10421      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
10422   if (TOLOWER (*given) == 'r')
10423     given++;
10424   if (!ISDIGIT (*given))
10425     return false;
10426
10427   /* Skip over some well-known prefixes in the canonical name,
10428      hoping to find a number there too.  */
10429   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
10430     canonical += 2;
10431   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
10432     canonical += 2;
10433   else if (TOLOWER (canonical[0]) == 'r')
10434     canonical += 1;
10435
10436   return mips_strict_matching_cpu_name_p (canonical, given);
10437 }
10438
10439
10440 /* Return the mips_cpu_info entry for the processor or ISA given
10441    by CPU_STRING.  Return null if the string isn't recognized.
10442
10443    A similar function exists in GAS.  */
10444
10445 static const struct mips_cpu_info *
10446 mips_parse_cpu (const char *cpu_string)
10447 {
10448   const struct mips_cpu_info *p;
10449   const char *s;
10450
10451   /* In the past, we allowed upper-case CPU names, but it doesn't
10452      work well with the multilib machinery.  */
10453   for (s = cpu_string; *s != 0; s++)
10454     if (ISUPPER (*s))
10455       {
10456         warning (0, "the cpu name must be lower case");
10457         break;
10458       }
10459
10460   /* 'from-abi' selects the most compatible architecture for the given
10461      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
10462      EABIs, we have to decide whether we're using the 32-bit or 64-bit
10463      version.  Look first at the -mgp options, if given, otherwise base
10464      the choice on MASK_64BIT in TARGET_DEFAULT.  */
10465   if (strcasecmp (cpu_string, "from-abi") == 0)
10466     return mips_cpu_info_from_isa (ABI_NEEDS_32BIT_REGS ? 1
10467                                    : ABI_NEEDS_64BIT_REGS ? 3
10468                                    : (TARGET_64BIT ? 3 : 1));
10469
10470   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
10471   if (strcasecmp (cpu_string, "default") == 0)
10472     return 0;
10473
10474   for (p = mips_cpu_info_table; p->name != 0; p++)
10475     if (mips_matching_cpu_name_p (p->name, cpu_string))
10476       return p;
10477
10478   return 0;
10479 }
10480
10481
10482 /* Return the processor associated with the given ISA level, or null
10483    if the ISA isn't valid.  */
10484
10485 static const struct mips_cpu_info *
10486 mips_cpu_info_from_isa (int isa)
10487 {
10488   const struct mips_cpu_info *p;
10489
10490   for (p = mips_cpu_info_table; p->name != 0; p++)
10491     if (p->isa == isa)
10492       return p;
10493
10494   return 0;
10495 }
10496 \f
10497 /* Implement HARD_REGNO_NREGS.  The size of FP registers is controlled
10498    by UNITS_PER_FPREG.  The size of FP status registers is always 4, because
10499    they only hold condition code modes, and CCmode is always considered to
10500    be 4 bytes wide.  All other registers are word sized.  */
10501
10502 unsigned int
10503 mips_hard_regno_nregs (int regno, enum machine_mode mode)
10504 {
10505   if (ST_REG_P (regno))
10506     return ((GET_MODE_SIZE (mode) + 3) / 4);
10507   else if (! FP_REG_P (regno))
10508     return ((GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD);
10509   else
10510     return ((GET_MODE_SIZE (mode) + UNITS_PER_FPREG - 1) / UNITS_PER_FPREG);
10511 }
10512
10513 /* Implement TARGET_RETURN_IN_MEMORY.  Under the old (i.e., 32 and O64 ABIs)
10514    all BLKmode objects are returned in memory.  Under the new (N32 and
10515    64-bit MIPS ABIs) small structures are returned in a register.
10516    Objects with varying size must still be returned in memory, of
10517    course.  */
10518
10519 static bool
10520 mips_return_in_memory (tree type, tree fndecl ATTRIBUTE_UNUSED)
10521 {
10522   if (TARGET_OLDABI)
10523     return (TYPE_MODE (type) == BLKmode);
10524   else
10525     return ((int_size_in_bytes (type) > (2 * UNITS_PER_WORD))
10526             || (int_size_in_bytes (type) == -1));
10527 }
10528
10529 static bool
10530 mips_strict_argument_naming (CUMULATIVE_ARGS *ca ATTRIBUTE_UNUSED)
10531 {
10532   return !TARGET_OLDABI;
10533 }
10534 \f
10535 /* Return true if INSN is a multiply-add or multiply-subtract
10536    instruction and PREV assigns to the accumulator operand.  */
10537
10538 bool
10539 mips_linked_madd_p (rtx prev, rtx insn)
10540 {
10541   rtx x;
10542
10543   x = single_set (insn);
10544   if (x == 0)
10545     return false;
10546
10547   x = SET_SRC (x);
10548
10549   if (GET_CODE (x) == PLUS
10550       && GET_CODE (XEXP (x, 0)) == MULT
10551       && reg_set_p (XEXP (x, 1), prev))
10552     return true;
10553
10554   if (GET_CODE (x) == MINUS
10555       && GET_CODE (XEXP (x, 1)) == MULT
10556       && reg_set_p (XEXP (x, 0), prev))
10557     return true;
10558
10559   return false;
10560 }
10561 \f
10562 /* Used by TUNE_MACC_CHAINS to record the last scheduled instruction
10563    that may clobber hi or lo.  */
10564
10565 static rtx mips_macc_chains_last_hilo;
10566
10567 /* A TUNE_MACC_CHAINS helper function.  Record that instruction INSN has
10568    been scheduled, updating mips_macc_chains_last_hilo appropriately.  */
10569
10570 static void
10571 mips_macc_chains_record (rtx insn)
10572 {
10573   if (get_attr_may_clobber_hilo (insn))
10574     mips_macc_chains_last_hilo = insn;
10575 }
10576
10577 /* A TUNE_MACC_CHAINS helper function.  Search ready queue READY, which
10578    has NREADY elements, looking for a multiply-add or multiply-subtract
10579    instruction that is cumulative with mips_macc_chains_last_hilo.
10580    If there is one, promote it ahead of anything else that might
10581    clobber hi or lo.  */
10582
10583 static void
10584 mips_macc_chains_reorder (rtx *ready, int nready)
10585 {
10586   int i, j;
10587
10588   if (mips_macc_chains_last_hilo != 0)
10589     for (i = nready - 1; i >= 0; i--)
10590       if (mips_linked_madd_p (mips_macc_chains_last_hilo, ready[i]))
10591         {
10592           for (j = nready - 1; j > i; j--)
10593             if (recog_memoized (ready[j]) >= 0
10594                 && get_attr_may_clobber_hilo (ready[j]))
10595               {
10596                 mips_promote_ready (ready, i, j);
10597                 break;
10598               }
10599           break;
10600         }
10601 }
10602 \f
10603 /* The last instruction to be scheduled.  */
10604
10605 static rtx vr4130_last_insn;
10606
10607 /* A note_stores callback used by vr4130_true_reg_dependence_p.  DATA
10608    points to an rtx that is initially an instruction.  Nullify the rtx
10609    if the instruction uses the value of register X.  */
10610
10611 static void
10612 vr4130_true_reg_dependence_p_1 (rtx x, rtx pat ATTRIBUTE_UNUSED, void *data)
10613 {
10614   rtx *insn_ptr = data;
10615   if (REG_P (x)
10616       && *insn_ptr != 0
10617       && reg_referenced_p (x, PATTERN (*insn_ptr)))
10618     *insn_ptr = 0;
10619 }
10620
10621 /* Return true if there is true register dependence between vr4130_last_insn
10622    and INSN.  */
10623
10624 static bool
10625 vr4130_true_reg_dependence_p (rtx insn)
10626 {
10627   note_stores (PATTERN (vr4130_last_insn),
10628                vr4130_true_reg_dependence_p_1, &insn);
10629   return insn == 0;
10630 }
10631
10632 /* A TUNE_MIPS4130 helper function.  Given that INSN1 is at the head of
10633    the ready queue and that INSN2 is the instruction after it, return
10634    true if it is worth promoting INSN2 ahead of INSN1.  Look for cases
10635    in which INSN1 and INSN2 can probably issue in parallel, but for
10636    which (INSN2, INSN1) should be less sensitive to instruction
10637    alignment than (INSN1, INSN2).  See 4130.md for more details.  */
10638
10639 static bool
10640 vr4130_swap_insns_p (rtx insn1, rtx insn2)
10641 {
10642   dep_link_t dep;
10643
10644   /* Check for the following case:
10645
10646      1) there is some other instruction X with an anti dependence on INSN1;
10647      2) X has a higher priority than INSN2; and
10648      3) X is an arithmetic instruction (and thus has no unit restrictions).
10649
10650      If INSN1 is the last instruction blocking X, it would better to
10651      choose (INSN1, X) over (INSN2, INSN1).  */
10652   FOR_EACH_DEP_LINK (dep, INSN_FORW_DEPS (insn1))
10653     if (DEP_LINK_KIND (dep) == REG_DEP_ANTI
10654         && INSN_PRIORITY (DEP_LINK_CON (dep)) > INSN_PRIORITY (insn2)
10655         && recog_memoized (DEP_LINK_CON (dep)) >= 0
10656         && get_attr_vr4130_class (DEP_LINK_CON (dep)) == VR4130_CLASS_ALU)
10657       return false;
10658
10659   if (vr4130_last_insn != 0
10660       && recog_memoized (insn1) >= 0
10661       && recog_memoized (insn2) >= 0)
10662     {
10663       /* See whether INSN1 and INSN2 use different execution units,
10664          or if they are both ALU-type instructions.  If so, they can
10665          probably execute in parallel.  */
10666       enum attr_vr4130_class class1 = get_attr_vr4130_class (insn1);
10667       enum attr_vr4130_class class2 = get_attr_vr4130_class (insn2);
10668       if (class1 != class2 || class1 == VR4130_CLASS_ALU)
10669         {
10670           /* If only one of the instructions has a dependence on
10671              vr4130_last_insn, prefer to schedule the other one first.  */
10672           bool dep1 = vr4130_true_reg_dependence_p (insn1);
10673           bool dep2 = vr4130_true_reg_dependence_p (insn2);
10674           if (dep1 != dep2)
10675             return dep1;
10676
10677           /* Prefer to schedule INSN2 ahead of INSN1 if vr4130_last_insn
10678              is not an ALU-type instruction and if INSN1 uses the same
10679              execution unit.  (Note that if this condition holds, we already
10680              know that INSN2 uses a different execution unit.)  */
10681           if (class1 != VR4130_CLASS_ALU
10682               && recog_memoized (vr4130_last_insn) >= 0
10683               && class1 == get_attr_vr4130_class (vr4130_last_insn))
10684             return true;
10685         }
10686     }
10687   return false;
10688 }
10689
10690 /* A TUNE_MIPS4130 helper function.  (READY, NREADY) describes a ready
10691    queue with at least two instructions.  Swap the first two if
10692    vr4130_swap_insns_p says that it could be worthwhile.  */
10693
10694 static void
10695 vr4130_reorder (rtx *ready, int nready)
10696 {
10697   if (vr4130_swap_insns_p (ready[nready - 1], ready[nready - 2]))
10698     mips_promote_ready (ready, nready - 2, nready - 1);
10699 }
10700 \f
10701 /* Remove the instruction at index LOWER from ready queue READY and
10702    reinsert it in front of the instruction at index HIGHER.  LOWER must
10703    be <= HIGHER.  */
10704
10705 static void
10706 mips_promote_ready (rtx *ready, int lower, int higher)
10707 {
10708   rtx new_head;
10709   int i;
10710
10711   new_head = ready[lower];
10712   for (i = lower; i < higher; i++)
10713     ready[i] = ready[i + 1];
10714   ready[i] = new_head;
10715 }
10716
10717 /* Implement TARGET_SCHED_REORDER.  */
10718
10719 static int
10720 mips_sched_reorder (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
10721                     rtx *ready, int *nreadyp, int cycle)
10722 {
10723   if (!reload_completed && TUNE_MACC_CHAINS)
10724     {
10725       if (cycle == 0)
10726         mips_macc_chains_last_hilo = 0;
10727       if (*nreadyp > 0)
10728         mips_macc_chains_reorder (ready, *nreadyp);
10729     }
10730   if (reload_completed && TUNE_MIPS4130 && !TARGET_VR4130_ALIGN)
10731     {
10732       if (cycle == 0)
10733         vr4130_last_insn = 0;
10734       if (*nreadyp > 1)
10735         vr4130_reorder (ready, *nreadyp);
10736     }
10737   return mips_issue_rate ();
10738 }
10739
10740 /* Implement TARGET_SCHED_VARIABLE_ISSUE.  */
10741
10742 static int
10743 mips_variable_issue (FILE *file ATTRIBUTE_UNUSED, int verbose ATTRIBUTE_UNUSED,
10744                      rtx insn, int more)
10745 {
10746   switch (GET_CODE (PATTERN (insn)))
10747     {
10748     case USE:
10749     case CLOBBER:
10750       /* Don't count USEs and CLOBBERs against the issue rate.  */
10751       break;
10752
10753     default:
10754       more--;
10755       if (!reload_completed && TUNE_MACC_CHAINS)
10756         mips_macc_chains_record (insn);
10757       vr4130_last_insn = insn;
10758       break;
10759     }
10760   return more;
10761 }
10762 \f
10763 /* Implement TARGET_SCHED_ADJUST_COST.  We assume that anti and output
10764    dependencies have no cost.  */
10765
10766 static int
10767 mips_adjust_cost (rtx insn ATTRIBUTE_UNUSED, rtx link,
10768                   rtx dep ATTRIBUTE_UNUSED, int cost)
10769 {
10770   if (REG_NOTE_KIND (link) != 0)
10771     return 0;
10772   return cost;
10773 }
10774
10775 /* Return the number of instructions that can be issued per cycle.  */
10776
10777 static int
10778 mips_issue_rate (void)
10779 {
10780   switch (mips_tune)
10781     {
10782     case PROCESSOR_74KC:
10783     case PROCESSOR_74KF:
10784     case PROCESSOR_74KX:
10785     case PROCESSOR_R4130:
10786     case PROCESSOR_R5400:
10787     case PROCESSOR_R5500:
10788     case PROCESSOR_R7000:
10789     case PROCESSOR_R9000:
10790       return 2;
10791
10792     case PROCESSOR_SB1:
10793     case PROCESSOR_SB1A:
10794       /* This is actually 4, but we get better performance if we claim 3.
10795          This is partly because of unwanted speculative code motion with the
10796          larger number, and partly because in most common cases we can't
10797          reach the theoretical max of 4.  */
10798       return 3;
10799
10800     default:
10801       return 1;
10802     }
10803 }
10804
10805 /* Implements TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD.  This should
10806    be as wide as the scheduling freedom in the DFA.  */
10807
10808 static int
10809 mips_multipass_dfa_lookahead (void)
10810 {
10811   /* Can schedule up to 4 of the 6 function units in any one cycle.  */
10812   if (TUNE_SB1)
10813     return 4;
10814
10815   return 0;
10816 }
10817
10818 /* Implements a store data bypass check.  We need this because the cprestore
10819    pattern is type store, but defined using an UNSPEC.  This UNSPEC causes the
10820    default routine to abort.  We just return false for that case.  */
10821 /* ??? Should try to give a better result here than assuming false.  */
10822
10823 int
10824 mips_store_data_bypass_p (rtx out_insn, rtx in_insn)
10825 {
10826   if (GET_CODE (PATTERN (in_insn)) == UNSPEC_VOLATILE)
10827     return false;
10828
10829   return ! store_data_bypass_p (out_insn, in_insn);
10830 }
10831 \f
10832 /* Given that we have an rtx of the form (prefetch ... WRITE LOCALITY),
10833    return the first operand of the associated "pref" or "prefx" insn.  */
10834
10835 rtx
10836 mips_prefetch_cookie (rtx write, rtx locality)
10837 {
10838   /* store_streamed / load_streamed.  */
10839   if (INTVAL (locality) <= 0)
10840     return GEN_INT (INTVAL (write) + 4);
10841
10842   /* store / load.  */
10843   if (INTVAL (locality) <= 2)
10844     return write;
10845
10846   /* store_retained / load_retained.  */
10847   return GEN_INT (INTVAL (write) + 6);
10848 }
10849 \f
10850 /* MIPS builtin function support. */
10851
10852 struct builtin_description
10853 {
10854   /* The code of the main .md file instruction.  See mips_builtin_type
10855      for more information.  */
10856   enum insn_code icode;
10857
10858   /* The floating-point comparison code to use with ICODE, if any.  */
10859   enum mips_fp_condition cond;
10860
10861   /* The name of the builtin function.  */
10862   const char *name;
10863
10864   /* Specifies how the function should be expanded.  */
10865   enum mips_builtin_type builtin_type;
10866
10867   /* The function's prototype.  */
10868   enum mips_function_type function_type;
10869
10870   /* The target flags required for this function.  */
10871   int target_flags;
10872 };
10873
10874 /* Define a MIPS_BUILTIN_DIRECT function for instruction CODE_FOR_mips_<INSN>.
10875    FUNCTION_TYPE and TARGET_FLAGS are builtin_description fields.  */
10876 #define DIRECT_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)               \
10877   { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                 \
10878     MIPS_BUILTIN_DIRECT, FUNCTION_TYPE, TARGET_FLAGS }
10879
10880 /* Define __builtin_mips_<INSN>_<COND>_{s,d}, both of which require
10881    TARGET_FLAGS.  */
10882 #define CMP_SCALAR_BUILTINS(INSN, COND, TARGET_FLAGS)                   \
10883   { CODE_FOR_mips_ ## INSN ## _cond_s, MIPS_FP_COND_ ## COND,           \
10884     "__builtin_mips_" #INSN "_" #COND "_s",                             \
10885     MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_SF_SF, TARGET_FLAGS },      \
10886   { CODE_FOR_mips_ ## INSN ## _cond_d, MIPS_FP_COND_ ## COND,           \
10887     "__builtin_mips_" #INSN "_" #COND "_d",                             \
10888     MIPS_BUILTIN_CMP_SINGLE, MIPS_INT_FTYPE_DF_DF, TARGET_FLAGS }
10889
10890 /* Define __builtin_mips_{any,all,upper,lower}_<INSN>_<COND>_ps.
10891    The lower and upper forms require TARGET_FLAGS while the any and all
10892    forms require MASK_MIPS3D.  */
10893 #define CMP_PS_BUILTINS(INSN, COND, TARGET_FLAGS)                       \
10894   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10895     "__builtin_mips_any_" #INSN "_" #COND "_ps",                        \
10896     MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },      \
10897   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10898     "__builtin_mips_all_" #INSN "_" #COND "_ps",                        \
10899     MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF, MASK_MIPS3D },      \
10900   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10901     "__builtin_mips_lower_" #INSN "_" #COND "_ps",                      \
10902     MIPS_BUILTIN_CMP_LOWER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS },   \
10903   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10904     "__builtin_mips_upper_" #INSN "_" #COND "_ps",                      \
10905     MIPS_BUILTIN_CMP_UPPER, MIPS_INT_FTYPE_V2SF_V2SF, TARGET_FLAGS }
10906
10907 /* Define __builtin_mips_{any,all}_<INSN>_<COND>_4s.  The functions
10908    require MASK_MIPS3D.  */
10909 #define CMP_4S_BUILTINS(INSN, COND)                                     \
10910   { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,          \
10911     "__builtin_mips_any_" #INSN "_" #COND "_4s",                        \
10912     MIPS_BUILTIN_CMP_ANY, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,           \
10913     MASK_MIPS3D },                                                      \
10914   { CODE_FOR_mips_ ## INSN ## _cond_4s, MIPS_FP_COND_ ## COND,          \
10915     "__builtin_mips_all_" #INSN "_" #COND "_4s",                        \
10916     MIPS_BUILTIN_CMP_ALL, MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF,           \
10917     MASK_MIPS3D }
10918
10919 /* Define __builtin_mips_mov{t,f}_<INSN>_<COND>_ps.  The comparison
10920    instruction requires TARGET_FLAGS.  */
10921 #define MOVTF_BUILTINS(INSN, COND, TARGET_FLAGS)                        \
10922   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10923     "__builtin_mips_movt_" #INSN "_" #COND "_ps",                       \
10924     MIPS_BUILTIN_MOVT, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,             \
10925     TARGET_FLAGS },                                                     \
10926   { CODE_FOR_mips_ ## INSN ## _cond_ps, MIPS_FP_COND_ ## COND,          \
10927     "__builtin_mips_movf_" #INSN "_" #COND "_ps",                       \
10928     MIPS_BUILTIN_MOVF, MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF,             \
10929     TARGET_FLAGS }
10930
10931 /* Define all the builtins related to c.cond.fmt condition COND.  */
10932 #define CMP_BUILTINS(COND)                                              \
10933   MOVTF_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                   \
10934   MOVTF_BUILTINS (cabs, COND, MASK_MIPS3D),                             \
10935   CMP_SCALAR_BUILTINS (cabs, COND, MASK_MIPS3D),                        \
10936   CMP_PS_BUILTINS (c, COND, MASK_PAIRED_SINGLE_FLOAT),                  \
10937   CMP_PS_BUILTINS (cabs, COND, MASK_MIPS3D),                            \
10938   CMP_4S_BUILTINS (c, COND),                                            \
10939   CMP_4S_BUILTINS (cabs, COND)
10940
10941 static const struct builtin_description mips_bdesc[] =
10942 {
10943   DIRECT_BUILTIN (pll_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10944   DIRECT_BUILTIN (pul_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10945   DIRECT_BUILTIN (plu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10946   DIRECT_BUILTIN (puu_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10947   DIRECT_BUILTIN (cvt_ps_s, MIPS_V2SF_FTYPE_SF_SF, MASK_PAIRED_SINGLE_FLOAT),
10948   DIRECT_BUILTIN (cvt_s_pl, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10949   DIRECT_BUILTIN (cvt_s_pu, MIPS_SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10950   DIRECT_BUILTIN (abs_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT),
10951
10952   DIRECT_BUILTIN (alnv_ps, MIPS_V2SF_FTYPE_V2SF_V2SF_INT,
10953                   MASK_PAIRED_SINGLE_FLOAT),
10954   DIRECT_BUILTIN (addr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
10955   DIRECT_BUILTIN (mulr_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
10956   DIRECT_BUILTIN (cvt_pw_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
10957   DIRECT_BUILTIN (cvt_ps_pw, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
10958
10959   DIRECT_BUILTIN (recip1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
10960   DIRECT_BUILTIN (recip1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
10961   DIRECT_BUILTIN (recip1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
10962   DIRECT_BUILTIN (recip2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
10963   DIRECT_BUILTIN (recip2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
10964   DIRECT_BUILTIN (recip2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
10965
10966   DIRECT_BUILTIN (rsqrt1_s, MIPS_SF_FTYPE_SF, MASK_MIPS3D),
10967   DIRECT_BUILTIN (rsqrt1_d, MIPS_DF_FTYPE_DF, MASK_MIPS3D),
10968   DIRECT_BUILTIN (rsqrt1_ps, MIPS_V2SF_FTYPE_V2SF, MASK_MIPS3D),
10969   DIRECT_BUILTIN (rsqrt2_s, MIPS_SF_FTYPE_SF_SF, MASK_MIPS3D),
10970   DIRECT_BUILTIN (rsqrt2_d, MIPS_DF_FTYPE_DF_DF, MASK_MIPS3D),
10971   DIRECT_BUILTIN (rsqrt2_ps, MIPS_V2SF_FTYPE_V2SF_V2SF, MASK_MIPS3D),
10972
10973   MIPS_FP_CONDITIONS (CMP_BUILTINS)
10974 };
10975
10976 /* Builtin functions for the SB-1 processor.  */
10977
10978 #define CODE_FOR_mips_sqrt_ps CODE_FOR_sqrtv2sf2
10979
10980 static const struct builtin_description sb1_bdesc[] =
10981 {
10982   DIRECT_BUILTIN (sqrt_ps, MIPS_V2SF_FTYPE_V2SF, MASK_PAIRED_SINGLE_FLOAT)
10983 };
10984
10985 /* Builtin functions for DSP ASE.  */
10986
10987 #define CODE_FOR_mips_addq_ph CODE_FOR_addv2hi3
10988 #define CODE_FOR_mips_addu_qb CODE_FOR_addv4qi3
10989 #define CODE_FOR_mips_subq_ph CODE_FOR_subv2hi3
10990 #define CODE_FOR_mips_subu_qb CODE_FOR_subv4qi3
10991 #define CODE_FOR_mips_mul_ph CODE_FOR_mulv2hi3
10992
10993 /* Define a MIPS_BUILTIN_DIRECT_NO_TARGET function for instruction
10994    CODE_FOR_mips_<INSN>.  FUNCTION_TYPE and TARGET_FLAGS are
10995    builtin_description fields.  */
10996 #define DIRECT_NO_TARGET_BUILTIN(INSN, FUNCTION_TYPE, TARGET_FLAGS)     \
10997   { CODE_FOR_mips_ ## INSN, 0, "__builtin_mips_" #INSN,                 \
10998     MIPS_BUILTIN_DIRECT_NO_TARGET, FUNCTION_TYPE, TARGET_FLAGS }
10999
11000 /* Define __builtin_mips_bposge<VALUE>.  <VALUE> is 32 for the MIPS32 DSP
11001    branch instruction.  TARGET_FLAGS is a builtin_description field.  */
11002 #define BPOSGE_BUILTIN(VALUE, TARGET_FLAGS)                             \
11003   { CODE_FOR_mips_bposge, 0, "__builtin_mips_bposge" #VALUE,            \
11004     MIPS_BUILTIN_BPOSGE ## VALUE, MIPS_SI_FTYPE_VOID, TARGET_FLAGS }
11005
11006 static const struct builtin_description dsp_bdesc[] =
11007 {
11008   DIRECT_BUILTIN (addq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11009   DIRECT_BUILTIN (addq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11010   DIRECT_BUILTIN (addq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11011   DIRECT_BUILTIN (addu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
11012   DIRECT_BUILTIN (addu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
11013   DIRECT_BUILTIN (subq_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11014   DIRECT_BUILTIN (subq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11015   DIRECT_BUILTIN (subq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11016   DIRECT_BUILTIN (subu_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
11017   DIRECT_BUILTIN (subu_s_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
11018   DIRECT_BUILTIN (addsc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11019   DIRECT_BUILTIN (addwc, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11020   DIRECT_BUILTIN (modsub, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11021   DIRECT_BUILTIN (raddu_w_qb, MIPS_SI_FTYPE_V4QI, MASK_DSP),
11022   DIRECT_BUILTIN (absq_s_ph, MIPS_V2HI_FTYPE_V2HI, MASK_DSP),
11023   DIRECT_BUILTIN (absq_s_w, MIPS_SI_FTYPE_SI, MASK_DSP),
11024   DIRECT_BUILTIN (precrq_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
11025   DIRECT_BUILTIN (precrq_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
11026   DIRECT_BUILTIN (precrq_rs_ph_w, MIPS_V2HI_FTYPE_SI_SI, MASK_DSP),
11027   DIRECT_BUILTIN (precrqu_s_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSP),
11028   DIRECT_BUILTIN (preceq_w_phl, MIPS_SI_FTYPE_V2HI, MASK_DSP),
11029   DIRECT_BUILTIN (preceq_w_phr, MIPS_SI_FTYPE_V2HI, MASK_DSP),
11030   DIRECT_BUILTIN (precequ_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11031   DIRECT_BUILTIN (precequ_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11032   DIRECT_BUILTIN (precequ_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11033   DIRECT_BUILTIN (precequ_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11034   DIRECT_BUILTIN (preceu_ph_qbl, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11035   DIRECT_BUILTIN (preceu_ph_qbr, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11036   DIRECT_BUILTIN (preceu_ph_qbla, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11037   DIRECT_BUILTIN (preceu_ph_qbra, MIPS_V2HI_FTYPE_V4QI, MASK_DSP),
11038   DIRECT_BUILTIN (shll_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
11039   DIRECT_BUILTIN (shll_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
11040   DIRECT_BUILTIN (shll_s_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
11041   DIRECT_BUILTIN (shll_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11042   DIRECT_BUILTIN (shrl_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSP),
11043   DIRECT_BUILTIN (shra_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
11044   DIRECT_BUILTIN (shra_r_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSP),
11045   DIRECT_BUILTIN (shra_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11046   DIRECT_BUILTIN (muleu_s_ph_qbl, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
11047   DIRECT_BUILTIN (muleu_s_ph_qbr, MIPS_V2HI_FTYPE_V4QI_V2HI, MASK_DSP),
11048   DIRECT_BUILTIN (mulq_rs_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11049   DIRECT_BUILTIN (muleq_s_w_phl, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
11050   DIRECT_BUILTIN (muleq_s_w_phr, MIPS_SI_FTYPE_V2HI_V2HI, MASK_DSP),
11051   DIRECT_BUILTIN (bitrev, MIPS_SI_FTYPE_SI, MASK_DSP),
11052   DIRECT_BUILTIN (insv, MIPS_SI_FTYPE_SI_SI, MASK_DSP),
11053   DIRECT_BUILTIN (repl_qb, MIPS_V4QI_FTYPE_SI, MASK_DSP),
11054   DIRECT_BUILTIN (repl_ph, MIPS_V2HI_FTYPE_SI, MASK_DSP),
11055   DIRECT_NO_TARGET_BUILTIN (cmpu_eq_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
11056   DIRECT_NO_TARGET_BUILTIN (cmpu_lt_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
11057   DIRECT_NO_TARGET_BUILTIN (cmpu_le_qb, MIPS_VOID_FTYPE_V4QI_V4QI, MASK_DSP),
11058   DIRECT_BUILTIN (cmpgu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
11059   DIRECT_BUILTIN (cmpgu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
11060   DIRECT_BUILTIN (cmpgu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSP),
11061   DIRECT_NO_TARGET_BUILTIN (cmp_eq_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
11062   DIRECT_NO_TARGET_BUILTIN (cmp_lt_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
11063   DIRECT_NO_TARGET_BUILTIN (cmp_le_ph, MIPS_VOID_FTYPE_V2HI_V2HI, MASK_DSP),
11064   DIRECT_BUILTIN (pick_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSP),
11065   DIRECT_BUILTIN (pick_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11066   DIRECT_BUILTIN (packrl_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSP),
11067   DIRECT_NO_TARGET_BUILTIN (wrdsp, MIPS_VOID_FTYPE_SI_SI, MASK_DSP),
11068   DIRECT_BUILTIN (rddsp, MIPS_SI_FTYPE_SI, MASK_DSP),
11069   DIRECT_BUILTIN (lbux, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
11070   DIRECT_BUILTIN (lhx, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
11071   DIRECT_BUILTIN (lwx, MIPS_SI_FTYPE_PTR_SI, MASK_DSP),
11072   BPOSGE_BUILTIN (32, MASK_DSP),
11073
11074   /* The following are for the MIPS DSP ASE REV 2.  */
11075   DIRECT_BUILTIN (absq_s_qb, MIPS_V4QI_FTYPE_V4QI, MASK_DSPR2),
11076   DIRECT_BUILTIN (addu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11077   DIRECT_BUILTIN (addu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11078   DIRECT_BUILTIN (adduh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11079   DIRECT_BUILTIN (adduh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11080   DIRECT_BUILTIN (append, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
11081   DIRECT_BUILTIN (balign, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
11082   DIRECT_BUILTIN (cmpgdu_eq_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11083   DIRECT_BUILTIN (cmpgdu_lt_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11084   DIRECT_BUILTIN (cmpgdu_le_qb, MIPS_SI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11085   DIRECT_BUILTIN (mul_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11086   DIRECT_BUILTIN (mul_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11087   DIRECT_BUILTIN (mulq_rs_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
11088   DIRECT_BUILTIN (mulq_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11089   DIRECT_BUILTIN (mulq_s_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
11090   DIRECT_BUILTIN (precr_qb_ph, MIPS_V4QI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11091   DIRECT_BUILTIN (precr_sra_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
11092   DIRECT_BUILTIN (precr_sra_r_ph_w, MIPS_V2HI_FTYPE_SI_SI_SI, MASK_DSPR2),
11093   DIRECT_BUILTIN (prepend, MIPS_SI_FTYPE_SI_SI_SI, MASK_DSPR2),
11094   DIRECT_BUILTIN (shra_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
11095   DIRECT_BUILTIN (shra_r_qb, MIPS_V4QI_FTYPE_V4QI_SI, MASK_DSPR2),
11096   DIRECT_BUILTIN (shrl_ph, MIPS_V2HI_FTYPE_V2HI_SI, MASK_DSPR2),
11097   DIRECT_BUILTIN (subu_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11098   DIRECT_BUILTIN (subu_s_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11099   DIRECT_BUILTIN (subuh_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11100   DIRECT_BUILTIN (subuh_r_qb, MIPS_V4QI_FTYPE_V4QI_V4QI, MASK_DSPR2),
11101   DIRECT_BUILTIN (addqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11102   DIRECT_BUILTIN (addqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11103   DIRECT_BUILTIN (addqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
11104   DIRECT_BUILTIN (addqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
11105   DIRECT_BUILTIN (subqh_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11106   DIRECT_BUILTIN (subqh_r_ph, MIPS_V2HI_FTYPE_V2HI_V2HI, MASK_DSPR2),
11107   DIRECT_BUILTIN (subqh_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2),
11108   DIRECT_BUILTIN (subqh_r_w, MIPS_SI_FTYPE_SI_SI, MASK_DSPR2)
11109 };
11110
11111 static const struct builtin_description dsp_32only_bdesc[] =
11112 {
11113   DIRECT_BUILTIN (dpau_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
11114   DIRECT_BUILTIN (dpau_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
11115   DIRECT_BUILTIN (dpsu_h_qbl, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
11116   DIRECT_BUILTIN (dpsu_h_qbr, MIPS_DI_FTYPE_DI_V4QI_V4QI, MASK_DSP),
11117   DIRECT_BUILTIN (dpaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11118   DIRECT_BUILTIN (dpsq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11119   DIRECT_BUILTIN (mulsaq_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11120   DIRECT_BUILTIN (dpaq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
11121   DIRECT_BUILTIN (dpsq_sa_l_w, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSP),
11122   DIRECT_BUILTIN (maq_s_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11123   DIRECT_BUILTIN (maq_s_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11124   DIRECT_BUILTIN (maq_sa_w_phl, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11125   DIRECT_BUILTIN (maq_sa_w_phr, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSP),
11126   DIRECT_BUILTIN (extr_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11127   DIRECT_BUILTIN (extr_r_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11128   DIRECT_BUILTIN (extr_rs_w, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11129   DIRECT_BUILTIN (extr_s_h, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11130   DIRECT_BUILTIN (extp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11131   DIRECT_BUILTIN (extpdp, MIPS_SI_FTYPE_DI_SI, MASK_DSP),
11132   DIRECT_BUILTIN (shilo, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
11133   DIRECT_BUILTIN (mthlip, MIPS_DI_FTYPE_DI_SI, MASK_DSP),
11134
11135   /* The following are for the MIPS DSP ASE REV 2.  */
11136   DIRECT_BUILTIN (dpa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11137   DIRECT_BUILTIN (dps_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11138   DIRECT_BUILTIN (madd, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
11139   DIRECT_BUILTIN (maddu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
11140   DIRECT_BUILTIN (msub, MIPS_DI_FTYPE_DI_SI_SI, MASK_DSPR2),
11141   DIRECT_BUILTIN (msubu, MIPS_DI_FTYPE_DI_USI_USI, MASK_DSPR2),
11142   DIRECT_BUILTIN (mulsa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11143   DIRECT_BUILTIN (mult, MIPS_DI_FTYPE_SI_SI, MASK_DSPR2),
11144   DIRECT_BUILTIN (multu, MIPS_DI_FTYPE_USI_USI, MASK_DSPR2),
11145   DIRECT_BUILTIN (dpax_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11146   DIRECT_BUILTIN (dpsx_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11147   DIRECT_BUILTIN (dpaqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11148   DIRECT_BUILTIN (dpaqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11149   DIRECT_BUILTIN (dpsqx_s_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2),
11150   DIRECT_BUILTIN (dpsqx_sa_w_ph, MIPS_DI_FTYPE_DI_V2HI_V2HI, MASK_DSPR2)
11151 };
11152
11153 /* This helps provide a mapping from builtin function codes to bdesc
11154    arrays.  */
11155
11156 struct bdesc_map
11157 {
11158   /* The builtin function table that this entry describes.  */
11159   const struct builtin_description *bdesc;
11160
11161   /* The number of entries in the builtin function table.  */
11162   unsigned int size;
11163
11164   /* The target processor that supports these builtin functions.
11165      PROCESSOR_MAX means we enable them for all processors.  */
11166   enum processor_type proc;
11167
11168   /* If the target has these flags, this builtin function table
11169      will not be supported.  */
11170   int unsupported_target_flags;
11171 };
11172
11173 static const struct bdesc_map bdesc_arrays[] =
11174 {
11175   { mips_bdesc, ARRAY_SIZE (mips_bdesc), PROCESSOR_MAX, 0 },
11176   { sb1_bdesc, ARRAY_SIZE (sb1_bdesc), PROCESSOR_SB1, 0 },
11177   { dsp_bdesc, ARRAY_SIZE (dsp_bdesc), PROCESSOR_MAX, 0 },
11178   { dsp_32only_bdesc, ARRAY_SIZE (dsp_32only_bdesc), PROCESSOR_MAX,
11179     MASK_64BIT }
11180 };
11181
11182 /* Take the argument ARGNUM of the arglist of EXP and convert it into a form
11183    suitable for input operand OP of instruction ICODE.  Return the value.  */
11184
11185 static rtx
11186 mips_prepare_builtin_arg (enum insn_code icode,
11187                           unsigned int op, tree exp, unsigned int argnum)
11188 {
11189   rtx value;
11190   enum machine_mode mode;
11191
11192   value = expand_normal (CALL_EXPR_ARG (exp, argnum));
11193   mode = insn_data[icode].operand[op].mode;
11194   if (!insn_data[icode].operand[op].predicate (value, mode))
11195     {
11196       value = copy_to_mode_reg (mode, value);
11197       /* Check the predicate again.  */
11198       if (!insn_data[icode].operand[op].predicate (value, mode))
11199         {
11200           error ("invalid argument to builtin function");
11201           return const0_rtx;
11202         }
11203     }
11204
11205   return value;
11206 }
11207
11208 /* Return an rtx suitable for output operand OP of instruction ICODE.
11209    If TARGET is non-null, try to use it where possible.  */
11210
11211 static rtx
11212 mips_prepare_builtin_target (enum insn_code icode, unsigned int op, rtx target)
11213 {
11214   enum machine_mode mode;
11215
11216   mode = insn_data[icode].operand[op].mode;
11217   if (target == 0 || !insn_data[icode].operand[op].predicate (target, mode))
11218     target = gen_reg_rtx (mode);
11219
11220   return target;
11221 }
11222
11223 /* Expand builtin functions.  This is called from TARGET_EXPAND_BUILTIN.  */
11224
11225 rtx
11226 mips_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
11227                      enum machine_mode mode ATTRIBUTE_UNUSED,
11228                      int ignore ATTRIBUTE_UNUSED)
11229 {
11230   enum insn_code icode;
11231   enum mips_builtin_type type;
11232   tree fndecl;
11233   unsigned int fcode;
11234   const struct builtin_description *bdesc;
11235   const struct bdesc_map *m;
11236
11237   fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
11238   fcode = DECL_FUNCTION_CODE (fndecl);
11239
11240   bdesc = NULL;
11241   for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
11242     {
11243       if (fcode < m->size)
11244         {
11245           bdesc = m->bdesc;
11246           icode = bdesc[fcode].icode;
11247           type = bdesc[fcode].builtin_type;
11248           break;
11249         }
11250       fcode -= m->size;
11251     }
11252   if (bdesc == NULL)
11253     return 0;
11254
11255   switch (type)
11256     {
11257     case MIPS_BUILTIN_DIRECT:
11258       return mips_expand_builtin_direct (icode, target, exp, true);
11259
11260     case MIPS_BUILTIN_DIRECT_NO_TARGET:
11261       return mips_expand_builtin_direct (icode, target, exp, false);
11262
11263     case MIPS_BUILTIN_MOVT:
11264     case MIPS_BUILTIN_MOVF:
11265       return mips_expand_builtin_movtf (type, icode, bdesc[fcode].cond,
11266                                         target, exp);
11267
11268     case MIPS_BUILTIN_CMP_ANY:
11269     case MIPS_BUILTIN_CMP_ALL:
11270     case MIPS_BUILTIN_CMP_UPPER:
11271     case MIPS_BUILTIN_CMP_LOWER:
11272     case MIPS_BUILTIN_CMP_SINGLE:
11273       return mips_expand_builtin_compare (type, icode, bdesc[fcode].cond,
11274                                           target, exp);
11275
11276     case MIPS_BUILTIN_BPOSGE32:
11277       return mips_expand_builtin_bposge (type, target);
11278
11279     default:
11280       return 0;
11281     }
11282 }
11283
11284 /* Init builtin functions.  This is called from TARGET_INIT_BUILTIN.  */
11285
11286 void
11287 mips_init_builtins (void)
11288 {
11289   const struct builtin_description *d;
11290   const struct bdesc_map *m;
11291   tree types[(int) MIPS_MAX_FTYPE_MAX];
11292   tree V2SF_type_node;
11293   tree V2HI_type_node;
11294   tree V4QI_type_node;
11295   unsigned int offset;
11296
11297   /* We have only builtins for -mpaired-single, -mips3d and -mdsp.  */
11298   if (!TARGET_PAIRED_SINGLE_FLOAT && !TARGET_DSP)
11299     return;
11300
11301   if (TARGET_PAIRED_SINGLE_FLOAT)
11302     {
11303       V2SF_type_node = build_vector_type_for_mode (float_type_node, V2SFmode);
11304
11305       types[MIPS_V2SF_FTYPE_V2SF]
11306         = build_function_type_list (V2SF_type_node, V2SF_type_node, NULL_TREE);
11307
11308       types[MIPS_V2SF_FTYPE_V2SF_V2SF]
11309         = build_function_type_list (V2SF_type_node,
11310                                     V2SF_type_node, V2SF_type_node, NULL_TREE);
11311
11312       types[MIPS_V2SF_FTYPE_V2SF_V2SF_INT]
11313         = build_function_type_list (V2SF_type_node,
11314                                     V2SF_type_node, V2SF_type_node,
11315                                     integer_type_node, NULL_TREE);
11316
11317       types[MIPS_V2SF_FTYPE_V2SF_V2SF_V2SF_V2SF]
11318         = build_function_type_list (V2SF_type_node,
11319                                     V2SF_type_node, V2SF_type_node,
11320                                     V2SF_type_node, V2SF_type_node, NULL_TREE);
11321
11322       types[MIPS_V2SF_FTYPE_SF_SF]
11323         = build_function_type_list (V2SF_type_node,
11324                                     float_type_node, float_type_node, NULL_TREE);
11325
11326       types[MIPS_INT_FTYPE_V2SF_V2SF]
11327         = build_function_type_list (integer_type_node,
11328                                     V2SF_type_node, V2SF_type_node, NULL_TREE);
11329
11330       types[MIPS_INT_FTYPE_V2SF_V2SF_V2SF_V2SF]
11331         = build_function_type_list (integer_type_node,
11332                                     V2SF_type_node, V2SF_type_node,
11333                                     V2SF_type_node, V2SF_type_node, NULL_TREE);
11334
11335       types[MIPS_INT_FTYPE_SF_SF]
11336         = build_function_type_list (integer_type_node,
11337                                     float_type_node, float_type_node, NULL_TREE);
11338
11339       types[MIPS_INT_FTYPE_DF_DF]
11340         = build_function_type_list (integer_type_node,
11341                                     double_type_node, double_type_node, NULL_TREE);
11342
11343       types[MIPS_SF_FTYPE_V2SF]
11344         = build_function_type_list (float_type_node, V2SF_type_node, NULL_TREE);
11345
11346       types[MIPS_SF_FTYPE_SF]
11347         = build_function_type_list (float_type_node,
11348                                     float_type_node, NULL_TREE);
11349
11350       types[MIPS_SF_FTYPE_SF_SF]
11351         = build_function_type_list (float_type_node,
11352                                     float_type_node, float_type_node, NULL_TREE);
11353
11354       types[MIPS_DF_FTYPE_DF]
11355         = build_function_type_list (double_type_node,
11356                                     double_type_node, NULL_TREE);
11357
11358       types[MIPS_DF_FTYPE_DF_DF]
11359         = build_function_type_list (double_type_node,
11360                                     double_type_node, double_type_node, NULL_TREE);
11361     }
11362
11363   if (TARGET_DSP)
11364     {
11365       V2HI_type_node = build_vector_type_for_mode (intHI_type_node, V2HImode);
11366       V4QI_type_node = build_vector_type_for_mode (intQI_type_node, V4QImode);
11367
11368       types[MIPS_V2HI_FTYPE_V2HI_V2HI]
11369         = build_function_type_list (V2HI_type_node,
11370                                     V2HI_type_node, V2HI_type_node,
11371                                     NULL_TREE);
11372
11373       types[MIPS_SI_FTYPE_SI_SI]
11374         = build_function_type_list (intSI_type_node,
11375                                     intSI_type_node, intSI_type_node,
11376                                     NULL_TREE);
11377
11378       types[MIPS_V4QI_FTYPE_V4QI_V4QI]
11379         = build_function_type_list (V4QI_type_node,
11380                                     V4QI_type_node, V4QI_type_node,
11381                                     NULL_TREE);
11382
11383       types[MIPS_SI_FTYPE_V4QI]
11384         = build_function_type_list (intSI_type_node,
11385                                     V4QI_type_node,
11386                                     NULL_TREE);
11387
11388       types[MIPS_V2HI_FTYPE_V2HI]
11389         = build_function_type_list (V2HI_type_node,
11390                                     V2HI_type_node,
11391                                     NULL_TREE);
11392
11393       types[MIPS_SI_FTYPE_SI]
11394         = build_function_type_list (intSI_type_node,
11395                                     intSI_type_node,
11396                                     NULL_TREE);
11397
11398       types[MIPS_V4QI_FTYPE_V2HI_V2HI]
11399         = build_function_type_list (V4QI_type_node,
11400                                     V2HI_type_node, V2HI_type_node,
11401                                     NULL_TREE);
11402
11403       types[MIPS_V2HI_FTYPE_SI_SI]
11404         = build_function_type_list (V2HI_type_node,
11405                                     intSI_type_node, intSI_type_node,
11406                                     NULL_TREE);
11407
11408       types[MIPS_SI_FTYPE_V2HI]
11409         = build_function_type_list (intSI_type_node,
11410                                     V2HI_type_node,
11411                                     NULL_TREE);
11412
11413       types[MIPS_V2HI_FTYPE_V4QI]
11414         = build_function_type_list (V2HI_type_node,
11415                                     V4QI_type_node,
11416                                     NULL_TREE);
11417
11418       types[MIPS_V4QI_FTYPE_V4QI_SI]
11419         = build_function_type_list (V4QI_type_node,
11420                                     V4QI_type_node, intSI_type_node,
11421                                     NULL_TREE);
11422
11423       types[MIPS_V2HI_FTYPE_V2HI_SI]
11424         = build_function_type_list (V2HI_type_node,
11425                                     V2HI_type_node, intSI_type_node,
11426                                     NULL_TREE);
11427
11428       types[MIPS_V2HI_FTYPE_V4QI_V2HI]
11429         = build_function_type_list (V2HI_type_node,
11430                                     V4QI_type_node, V2HI_type_node,
11431                                     NULL_TREE);
11432
11433       types[MIPS_SI_FTYPE_V2HI_V2HI]
11434         = build_function_type_list (intSI_type_node,
11435                                     V2HI_type_node, V2HI_type_node,
11436                                     NULL_TREE);
11437
11438       types[MIPS_DI_FTYPE_DI_V4QI_V4QI]
11439         = build_function_type_list (intDI_type_node,
11440                                     intDI_type_node, V4QI_type_node, V4QI_type_node,
11441                                     NULL_TREE);
11442
11443       types[MIPS_DI_FTYPE_DI_V2HI_V2HI]
11444         = build_function_type_list (intDI_type_node,
11445                                     intDI_type_node, V2HI_type_node, V2HI_type_node,
11446                                     NULL_TREE);
11447
11448       types[MIPS_DI_FTYPE_DI_SI_SI]
11449         = build_function_type_list (intDI_type_node,
11450                                     intDI_type_node, intSI_type_node, intSI_type_node,
11451                                     NULL_TREE);
11452
11453       types[MIPS_V4QI_FTYPE_SI]
11454         = build_function_type_list (V4QI_type_node,
11455                                     intSI_type_node,
11456                                     NULL_TREE);
11457
11458       types[MIPS_V2HI_FTYPE_SI]
11459         = build_function_type_list (V2HI_type_node,
11460                                     intSI_type_node,
11461                                     NULL_TREE);
11462
11463       types[MIPS_VOID_FTYPE_V4QI_V4QI]
11464         = build_function_type_list (void_type_node,
11465                                     V4QI_type_node, V4QI_type_node,
11466                                     NULL_TREE);
11467
11468       types[MIPS_SI_FTYPE_V4QI_V4QI]
11469         = build_function_type_list (intSI_type_node,
11470                                     V4QI_type_node, V4QI_type_node,
11471                                     NULL_TREE);
11472
11473       types[MIPS_VOID_FTYPE_V2HI_V2HI]
11474         = build_function_type_list (void_type_node,
11475                                     V2HI_type_node, V2HI_type_node,
11476                                     NULL_TREE);
11477
11478       types[MIPS_SI_FTYPE_DI_SI]
11479         = build_function_type_list (intSI_type_node,
11480                                     intDI_type_node, intSI_type_node,
11481                                     NULL_TREE);
11482
11483       types[MIPS_DI_FTYPE_DI_SI]
11484         = build_function_type_list (intDI_type_node,
11485                                     intDI_type_node, intSI_type_node,
11486                                     NULL_TREE);
11487
11488       types[MIPS_VOID_FTYPE_SI_SI]
11489         = build_function_type_list (void_type_node,
11490                                     intSI_type_node, intSI_type_node,
11491                                     NULL_TREE);
11492
11493       types[MIPS_SI_FTYPE_PTR_SI]
11494         = build_function_type_list (intSI_type_node,
11495                                     ptr_type_node, intSI_type_node,
11496                                     NULL_TREE);
11497
11498       types[MIPS_SI_FTYPE_VOID]
11499         = build_function_type (intSI_type_node, void_list_node);
11500
11501       if (TARGET_DSPR2)
11502         {
11503           types[MIPS_V4QI_FTYPE_V4QI]
11504             = build_function_type_list (V4QI_type_node,
11505                                         V4QI_type_node,
11506                                         NULL_TREE);
11507
11508           types[MIPS_SI_FTYPE_SI_SI_SI]
11509             = build_function_type_list (intSI_type_node,
11510                                         intSI_type_node, intSI_type_node,
11511                                         intSI_type_node, NULL_TREE);
11512
11513           types[MIPS_DI_FTYPE_DI_USI_USI]
11514             = build_function_type_list (intDI_type_node,
11515                                         intDI_type_node,
11516                                         unsigned_intSI_type_node,
11517                                         unsigned_intSI_type_node, NULL_TREE);
11518
11519           types[MIPS_DI_FTYPE_SI_SI]
11520             = build_function_type_list (intDI_type_node,
11521                                         intSI_type_node, intSI_type_node,
11522                                         NULL_TREE);
11523
11524           types[MIPS_DI_FTYPE_USI_USI]
11525             = build_function_type_list (intDI_type_node,
11526                                         unsigned_intSI_type_node,
11527                                         unsigned_intSI_type_node, NULL_TREE);
11528
11529           types[MIPS_V2HI_FTYPE_SI_SI_SI]
11530             = build_function_type_list (V2HI_type_node,
11531                                         intSI_type_node, intSI_type_node,
11532                                         intSI_type_node, NULL_TREE);
11533
11534         }
11535     }
11536
11537   /* Iterate through all of the bdesc arrays, initializing all of the
11538      builtin functions.  */
11539
11540   offset = 0;
11541   for (m = bdesc_arrays; m < &bdesc_arrays[ARRAY_SIZE (bdesc_arrays)]; m++)
11542     {
11543       if ((m->proc == PROCESSOR_MAX || (m->proc == mips_arch))
11544           && (m->unsupported_target_flags & target_flags) == 0)
11545         for (d = m->bdesc; d < &m->bdesc[m->size]; d++)
11546           if ((d->target_flags & target_flags) == d->target_flags)
11547             add_builtin_function (d->name, types[d->function_type],
11548                                   d - m->bdesc + offset,
11549                                   BUILT_IN_MD, NULL, NULL);
11550       offset += m->size;
11551     }
11552 }
11553
11554 /* Expand a MIPS_BUILTIN_DIRECT function.  ICODE is the code of the
11555    .md pattern and CALL is the function expr with arguments.  TARGET,
11556    if nonnull, suggests a good place to put the result.
11557    HAS_TARGET indicates the function must return something.  */
11558
11559 static rtx
11560 mips_expand_builtin_direct (enum insn_code icode, rtx target, tree exp,
11561                             bool has_target)
11562 {
11563   rtx ops[MAX_RECOG_OPERANDS];
11564   int i = 0;
11565   int j = 0;
11566
11567   if (has_target)
11568     {
11569       /* We save target to ops[0].  */
11570       ops[0] = mips_prepare_builtin_target (icode, 0, target);
11571       i = 1;
11572     }
11573
11574   /* We need to test if the arglist is not zero.  Some instructions have extra
11575      clobber registers.  */
11576   for (; i < insn_data[icode].n_operands && i <= call_expr_nargs (exp); i++, j++)
11577     ops[i] = mips_prepare_builtin_arg (icode, i, exp, j);
11578
11579   switch (i)
11580     {
11581     case 2:
11582       emit_insn (GEN_FCN (icode) (ops[0], ops[1]));
11583       break;
11584
11585     case 3:
11586       emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2]));
11587       break;
11588
11589     case 4:
11590       emit_insn (GEN_FCN (icode) (ops[0], ops[1], ops[2], ops[3]));
11591       break;
11592
11593     default:
11594       gcc_unreachable ();
11595     }
11596   return target;
11597 }
11598
11599 /* Expand a __builtin_mips_movt_*_ps() or __builtin_mips_movf_*_ps()
11600    function (TYPE says which).  EXP is the tree for the function
11601    function, ICODE is the instruction that should be used to compare
11602    the first two arguments, and COND is the condition it should test.
11603    TARGET, if nonnull, suggests a good place to put the result.  */
11604
11605 static rtx
11606 mips_expand_builtin_movtf (enum mips_builtin_type type,
11607                            enum insn_code icode, enum mips_fp_condition cond,
11608                            rtx target, tree exp)
11609 {
11610   rtx cmp_result, op0, op1;
11611
11612   cmp_result = mips_prepare_builtin_target (icode, 0, 0);
11613   op0 = mips_prepare_builtin_arg (icode, 1, exp, 0);
11614   op1 = mips_prepare_builtin_arg (icode, 2, exp, 1);
11615   emit_insn (GEN_FCN (icode) (cmp_result, op0, op1, GEN_INT (cond)));
11616
11617   icode = CODE_FOR_mips_cond_move_tf_ps;
11618   target = mips_prepare_builtin_target (icode, 0, target);
11619   if (type == MIPS_BUILTIN_MOVT)
11620     {
11621       op1 = mips_prepare_builtin_arg (icode, 2, exp, 2);
11622       op0 = mips_prepare_builtin_arg (icode, 1, exp, 3);
11623     }
11624   else
11625     {
11626       op0 = mips_prepare_builtin_arg (icode, 1, exp, 2);
11627       op1 = mips_prepare_builtin_arg (icode, 2, exp, 3);
11628     }
11629   emit_insn (gen_mips_cond_move_tf_ps (target, op0, op1, cmp_result));
11630   return target;
11631 }
11632
11633 /* Move VALUE_IF_TRUE into TARGET if CONDITION is true; move VALUE_IF_FALSE
11634    into TARGET otherwise.  Return TARGET.  */
11635
11636 static rtx
11637 mips_builtin_branch_and_move (rtx condition, rtx target,
11638                               rtx value_if_true, rtx value_if_false)
11639 {
11640   rtx true_label, done_label;
11641
11642   true_label = gen_label_rtx ();
11643   done_label = gen_label_rtx ();
11644
11645   /* First assume that CONDITION is false.  */
11646   emit_move_insn (target, value_if_false);
11647
11648   /* Branch to TRUE_LABEL if CONDITION is true and DONE_LABEL otherwise.  */
11649   emit_jump_insn (gen_condjump (condition, true_label));
11650   emit_jump_insn (gen_jump (done_label));
11651   emit_barrier ();
11652
11653   /* Fix TARGET if CONDITION is true.  */
11654   emit_label (true_label);
11655   emit_move_insn (target, value_if_true);
11656
11657   emit_label (done_label);
11658   return target;
11659 }
11660
11661 /* Expand a comparison builtin of type BUILTIN_TYPE.  ICODE is the code
11662    of the comparison instruction and COND is the condition it should test.
11663    EXP is the function call and arguments and TARGET, if nonnull,
11664    suggests a good place to put the boolean result.  */
11665
11666 static rtx
11667 mips_expand_builtin_compare (enum mips_builtin_type builtin_type,
11668                              enum insn_code icode, enum mips_fp_condition cond,
11669                              rtx target, tree exp)
11670 {
11671   rtx offset, condition, cmp_result, ops[MAX_RECOG_OPERANDS];
11672   int i;
11673   int j = 0;
11674
11675   if (target == 0 || GET_MODE (target) != SImode)
11676     target = gen_reg_rtx (SImode);
11677
11678   /* Prepare the operands to the comparison.  */
11679   cmp_result = mips_prepare_builtin_target (icode, 0, 0);
11680   for (i = 1; i < insn_data[icode].n_operands - 1; i++, j++)
11681     ops[i] = mips_prepare_builtin_arg (icode, i, exp, j);
11682
11683   switch (insn_data[icode].n_operands)
11684     {
11685     case 4:
11686       emit_insn (GEN_FCN (icode) (cmp_result, ops[1], ops[2], GEN_INT (cond)));
11687       break;
11688
11689     case 6:
11690       emit_insn (GEN_FCN (icode) (cmp_result, ops[1], ops[2],
11691                                   ops[3], ops[4], GEN_INT (cond)));
11692       break;
11693
11694     default:
11695       gcc_unreachable ();
11696     }
11697
11698   /* If the comparison sets more than one register, we define the result
11699      to be 0 if all registers are false and -1 if all registers are true.
11700      The value of the complete result is indeterminate otherwise.  */
11701   switch (builtin_type)
11702     {
11703     case MIPS_BUILTIN_CMP_ALL:
11704       condition = gen_rtx_NE (VOIDmode, cmp_result, constm1_rtx);
11705       return mips_builtin_branch_and_move (condition, target,
11706                                            const0_rtx, const1_rtx);
11707
11708     case MIPS_BUILTIN_CMP_UPPER:
11709     case MIPS_BUILTIN_CMP_LOWER:
11710       offset = GEN_INT (builtin_type == MIPS_BUILTIN_CMP_UPPER);
11711       condition = gen_single_cc (cmp_result, offset);
11712       return mips_builtin_branch_and_move (condition, target,
11713                                            const1_rtx, const0_rtx);
11714
11715     default:
11716       condition = gen_rtx_NE (VOIDmode, cmp_result, const0_rtx);
11717       return mips_builtin_branch_and_move (condition, target,
11718                                            const1_rtx, const0_rtx);
11719     }
11720 }
11721
11722 /* Expand a bposge builtin of type BUILTIN_TYPE.  TARGET, if nonnull,
11723    suggests a good place to put the boolean result.  */
11724
11725 static rtx
11726 mips_expand_builtin_bposge (enum mips_builtin_type builtin_type, rtx target)
11727 {
11728   rtx condition, cmp_result;
11729   int cmp_value;
11730
11731   if (target == 0 || GET_MODE (target) != SImode)
11732     target = gen_reg_rtx (SImode);
11733
11734   cmp_result = gen_rtx_REG (CCDSPmode, CCDSP_PO_REGNUM);
11735
11736   if (builtin_type == MIPS_BUILTIN_BPOSGE32)
11737     cmp_value = 32;
11738   else
11739     gcc_assert (0);
11740
11741   condition = gen_rtx_GE (VOIDmode, cmp_result, GEN_INT (cmp_value));
11742   return mips_builtin_branch_and_move (condition, target,
11743                                        const1_rtx, const0_rtx);
11744 }
11745 \f
11746 /* Set SYMBOL_REF_FLAGS for the SYMBOL_REF inside RTL, which belongs to DECL.
11747    FIRST is true if this is the first time handling this decl.  */
11748
11749 static void
11750 mips_encode_section_info (tree decl, rtx rtl, int first)
11751 {
11752   default_encode_section_info (decl, rtl, first);
11753
11754   if (TREE_CODE (decl) == FUNCTION_DECL)
11755     {
11756       rtx symbol = XEXP (rtl, 0);
11757
11758       if ((TARGET_LONG_CALLS && !mips_near_type_p (TREE_TYPE (decl)))
11759           || mips_far_type_p (TREE_TYPE (decl)))
11760         SYMBOL_REF_FLAGS (symbol) |= SYMBOL_FLAG_LONG_CALL;
11761     }
11762 }
11763
11764 /* Implement TARGET_EXTRA_LIVE_ON_ENTRY.  Some code models use the incoming
11765    value of PIC_FUNCTION_ADDR_REGNUM to set up the global pointer.  */
11766
11767 static void
11768 mips_extra_live_on_entry (bitmap regs)
11769 {
11770   if (TARGET_USE_GOT && !TARGET_ABSOLUTE_ABICALLS)
11771     bitmap_set_bit (regs, PIC_FUNCTION_ADDR_REGNUM);
11772 }
11773
11774 /* SImode values are represented as sign-extended to DImode.  */
11775
11776 int
11777 mips_mode_rep_extended (enum machine_mode mode, enum machine_mode mode_rep)
11778 {
11779   if (TARGET_64BIT && mode == SImode && mode_rep == DImode)
11780     return SIGN_EXTEND;
11781
11782   return UNKNOWN;
11783 }
11784 \f
11785 #include "gt-mips.h"