OSDN Git Service

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