OSDN Git Service

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