OSDN Git Service

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