OSDN Git Service

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