OSDN Git Service

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