OSDN Git Service

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